@webview-bridge/web 1.5.3 → 1.6.0-rc.0

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.
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty,R=Object.defineProperties,A=Object.getOwnPropertyDescriptor,D=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertyNames,T=Object.getOwnPropertySymbols;var O=Object.prototype.hasOwnProperty,J=Object.prototype.propertyIsEnumerable;var S=(t,e,r)=>e in t?p(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,l=(t,e)=>{for(var r in e||(e={}))O.call(e,r)&&S(t,r,e[r]);if(T)for(var r of T(e))J.call(e,r)&&S(t,r,e[r]);return t},B=(t,e)=>R(t,D(e));var I=(t,e)=>{for(var r in e)p(t,r,{get:e[r],enumerable:!0})},C=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!O.call(t,n)&&n!==r&&p(t,n,{get:()=>e[n],enumerable:!(o=A(e,n))||o.enumerable});return t};var $=t=>C(p({},"__esModule",{value:!0}),t);var w=(t,e,r)=>(S(t,typeof e!="symbol"?e+"":e,r),r);var M=(t,e,r)=>new Promise((o,n)=>{var i=a=>{try{c(r.next(a))}catch(d){n(d)}},s=a=>{try{c(r.throw(a))}catch(d){n(d)}},c=a=>a.done?o(a.value):Promise.resolve(a.value).then(i,s);c((r=r.apply(t,e)).next())});var G={};I(G,{MethodNotFoundError:()=>v,NativeMethodError:()=>f,linkBridge:()=>b,linkNativeMethod:()=>H,registerWebMethod:()=>q});module.exports=$(G);var v=class extends Error{constructor(e){super(`Method ${e} is not defined`),this.name="MethodNotFoundError"}},f=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 o=0,n=r.length;o<n;o++)r[o](...e)},on(t,e){var r;return(r=this.events[t])!=null&&r.push(e)||(this.events[t]=[e]),()=>{var o;this.events[t]=(o=this.events[t])==null?void 0:o.filter(n=>e!==n)}}}),P=({emitter:t,evaluate:e,eventId:r,failHandler:o=!1,methodName:n,onFallback:i})=>new Promise((s,c)=>{let a=t.on(`${n}-${r}`,(d,m)=>{a(),m?o instanceof Error?(i==null||i(),c(o)):s(void 0):s(d)});e()});var k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";var V=(t=21)=>Array.from({length:t},()=>k[Math.floor(Math.random()*k.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),o=Array.isArray(e),n,i,s;if(r&&o){if(i=t.length,i!==e.length)return!1;for(n=i;n--!==0;)if(!y(t[n],e[n]))return!1;return!0}if(r!==o)return!1;let c=Object.keys(t);if(i=c.length,i!==Object.keys(e).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(e,c[n]))return!1;for(n=i;n--!==0;)if(s=c[n],!y(t[s],e[s]))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 L=(t,e=!0)=>new Promise((r,o)=>{setTimeout(()=>{e?o(new Error("Timeout")):r(void 0)},t)});var N=()=>new Proxy({},{get:()=>()=>Promise.resolve()});var W=(t,e={},r={})=>{let o=()=>i,n=d=>{let m=l(l({},i),_(d));if(y(i,m))return;let g=i;i=m,c(i,g)};t.on("bridgeStateChange",d=>{n(d)});let i=l(l({},e),r),s=new Set,c=(d,m)=>{for(let g of s)g(d,m)};return{getState:o,subscribe:d=>(s.add(d),()=>s.delete(d))}};var E=()=>({state:{},getState(){return this.state},subscribe(){return()=>{}}});var x=class{constructor(e,r,o,n){this.options=e;this._emitter=r;this._bridgeMethods=o;this._nativeInitialState=n;w(this,"defaultTimeoutMs",2e3);w(this,"store",E());w(this,"loose",N());this._hydrate(o,n)}get isWebViewBridgeAvailable(){return!!window.ReactNativeWebView&&this._bridgeMethods.length>0}isNativeMethodAvailable(e){return typeof e=="string"&&!!window.ReactNativeWebView&&this._bridgeMethods.includes(e)}addEventListener(e,r){return this._emitter.on(`postMessage/${String(e)}`,r)}_postMessage(e,r){var o;(o=window.ReactNativeWebView)==null||o.postMessage(JSON.stringify(r?{type:e,body:r}:{type:e}))}_createNativeMethod(e,r,o,n){return(...i)=>{let s=V();return Promise.race([P({emitter:this._emitter,methodName:e,eventId:s,evaluate:()=>{this._postMessage("bridge",{method:e,eventId:s,args:i})},onFallback:()=>{n==null||n(e,i)},failHandler:r&&new f(e)}),o>0&&L(o,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:o}=this.options;return new Proxy(e,{get:(n,i)=>i in n&&!["isWebViewBridgeAvailable","isNativeMethodAvailable"].includes(i)?n[i]:this._createNativeMethod(i,this._willMethodThrowOnError(i),r,o)})}_hydrate(e,r={}){var s;this._bridgeMethods=e,this._nativeInitialState=r;let{timeout:o=this.defaultTimeoutMs,onFallback:n}=this.options,i=e.reduce((c,a)=>{let d=this._createNativeMethod(a,this._willMethodThrowOnError(a),o,n);return this[a]=d,B(l({},c),{[a]:d})},{});this.loose=this._createLoose(i),this.store=W(this._emitter,i,r),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this._postMessage("getBridgeState")}),this._postMessage("getBridgeState");for(let[c,...a]of(s=window.nativeBatchedEvents)!=null?s:[])this._emitter.emit(c,...a);return window.nativeBatchedEvents=[],!0}};var b=(t={timeout:2e3,throwOnError:!1})=>{var a,d;if(typeof window=="undefined")return{store:E()};window.ReactNativeWebView||console.warn("[WebViewBridge] Not in a WebView environment");let e=h();window.nativeEmitter||(window.nativeEmitter=e);let r=(a=window.__bridgeMethods__)!=null?a:[],o=(d=window.__bridgeInitialState__)!=null?d:{},n=new x(t,e,r,o);if(r.length===0){let m=e.on("hydrate",({bridgeMethods:g,nativeInitialState:u})=>{n._hydrate(g,u),m()})}let{onFallback:i,onReady:s}=t,c=new Proxy(n,{get:(m,g,u)=>g in m?m[g]:(u._postMessage("fallback",{method:g}),u._willMethodThrowOnError(g)?(...j)=>(i==null||i(g,j),Promise.reject(new v(g))):(console.warn(`[WebViewBridge] ${g} is not defined, using fallback.`),()=>Promise.resolve()))});return s==null||s(c),c};var H=(t={timeout:2e3,throwOnError:!1})=>b(t);var q=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),o=h();window.webEmitter=o;for(let[i,s]of e){let c=(a,d)=>M(void 0,null,function*(){var m,g;try{let u=yield s(...d);(m=window.ReactNativeWebView)==null||m.postMessage(JSON.stringify({type:"webMethodResponse",body:{funcName:i,eventId:a,value:u}}))}catch(u){(g=window.ReactNativeWebView)==null||g.postMessage(JSON.stringify({type:"webMethodError",body:{funcName:i,eventId:a,error:JSON.stringify(u)}}))}});o.on(i,c)}let n=()=>{var i;(i=window.ReactNativeWebView)==null||i.postMessage(JSON.stringify({type:"registerWebMethod",body:{bridgeNames:r}})),window.removeEventListener("DOMContentLoaded",n)};return window.ReactNativeWebView?(document.addEventListener("visibilitychange",()=>{var i;document.visibilityState==="visible"&&((i=window.ReactNativeWebView)==null||i.postMessage(JSON.stringify({type:"registerWebMethod",body:{bridgeNames:r}})))}),n(),t):(window.addEventListener("DOMContentLoaded",n),t)};0&&(module.exports={MethodNotFoundError,NativeMethodError,linkBridge,linkNativeMethod,registerWebMethod});
1
+ "use strict";var w=Object.defineProperty,R=Object.defineProperties,A=Object.getOwnPropertyDescriptor,D=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertyNames,O=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,J=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,f=(t,e)=>{for(var r in e||(e={}))B.call(e,r)&&x(t,r,e[r]);if(O)for(var r of O(e))J.call(e,r)&&x(t,r,e[r]);return t},T=(t,e)=>R(t,D(e));var I=(t,e)=>{for(var r in e)w(t,r,{get:e[r],enumerable:!0})},C=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of K(e))!B.call(t,i)&&i!==r&&w(t,i,{get:()=>e[i],enumerable:!(o=A(e,i))||o.enumerable});return t};var $=t=>C(w({},"__esModule",{value:!0}),t);var u=(t,e,r)=>(x(t,typeof e!="symbol"?e+"":e,r),r);var M=(t,e,r)=>new Promise((o,i)=>{var n=s=>{try{m(r.next(s))}catch(g){i(g)}},c=s=>{try{m(r.throw(s))}catch(g){i(g)}},m=s=>s.done?o(s.value):Promise.resolve(s.value).then(n,c);m((r=r.apply(t,e)).next())});var G={};I(G,{MethodNotFoundError:()=>v,NativeMethodError:()=>p,linkBridge:()=>S,linkNativeMethod:()=>H,registerWebMethod:()=>q});module.exports=$(G);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 o=0,i=r.length;o<i;o++)r[o](...e)},on(t,e){var r;return(r=this.events[t])!=null&&r.push(e)||(this.events[t]=[e]),()=>{var o;this.events[t]=(o=this.events[t])==null?void 0:o.filter(i=>e!==i)}}}),P=({emitter:t,evaluate:e,eventId:r,failHandler:o=!1,methodName:i,onFallback:n})=>new Promise((c,m)=>{let s=t.on(`${i}-${r}`,(g,a)=>{s(),a?o instanceof Error?(n==null||n(),m(o)):c(void 0):c(g)});e()});var _="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";var k=(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),o=Array.isArray(e),i,n,c;if(r&&o){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!==o)return!1;let m=Object.keys(t);if(n=m.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(e,m[i]))return!1;for(i=n;i--!==0;)if(c=m[i],!y(t[c],e[c]))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,o)=>{setTimeout(()=>{e?o(new Error("Timeout")):r(void 0)},t)});var j=()=>new Proxy({},{get:()=>()=>Promise.resolve()});var N=(t,e={})=>{let r=()=>i,o=s=>{let g=f(f({},i),V(s));if(y(i,g))return;let a=i;i=g,c(i,a)};t.on("bridgeStateChange",s=>{o(s)});let i=f({},e),n=new Set,c=(s,g)=>{for(let a of n)a(s,g)};return{getState:r,subscribe:s=>(n.add(s),()=>n.delete(s))}};var E=(t={})=>({state:t,getState(){return this.state},subscribe(){return()=>{}}});var b=class{constructor(e,r,o,i){this._options=e;this._emitter=r;this._bridgeMethods=o;this._nativeInitialState=i;u(this,"_defaultTimeoutMs",2e3);u(this,"_isListenerRegistered",!1);u(this,"store",E());u(this,"loose",j());this._hydrate(o,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 o;(o=window.ReactNativeWebView)==null||o.postMessage(JSON.stringify(r?{type:e,body:r}:{type:e}))}_createNativeMethod(e,r,o,i){return(...n)=>{let c=k();return Promise.race([P({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)}),o>0&&L(o,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:o}=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,o)})}_hydrate(e,r={}){var g;let{timeout:o=this._defaultTimeoutMs,onFallback:i,initialBridge:n={}}=this._options,c=Object.entries(n).filter(([a,d])=>typeof d=="function"),m=c.map(([a])=>a);Object.defineProperties(this,Object.fromEntries(c.map(([a,d])=>[a,{value:d,writable:!0}]))),this._bridgeMethods=[...e,...m],this._nativeInitialState=r;let s=e.reduce((a,d)=>{if(!this.isReactNativeWebView)return a;let l=this._createNativeMethod(d,this._willMethodThrowOnError(d),o,i);return Object.defineProperty(this,d,{value:l,writable:!1}),T(f({},a),{[d]:l})},n);if(this.loose=this._createLoose(s),this.store=N(this._emitter,f(f({},s),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 S=(t={timeout:2e3,throwOnError:!1})=>{var s,g;if(typeof window=="undefined")return{store:E(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=(s=window.__bridgeMethods__)!=null?s:[],o=(g=window.__bridgeInitialState__)!=null?g:{},i=new b(t,e,r,o);if(r.length===0){let a=e.on("hydrate",({bridgeMethods:d,nativeInitialState:l})=>{i._hydrate(d,l),a()})}let{onFallback:n,onReady:c}=t,m=new Proxy(i,{get:(a,d,l)=>d in a?a[d]:(l._postMessage("fallback",{method:d}),l._willMethodThrowOnError(d)?(...W)=>(n==null||n(d,W),Promise.reject(new v(d))):(console.warn(`[WebViewBridge] ${d} is not defined, using fallback.`),()=>Promise.resolve()))});return c==null||c(m),m};var H=(t={timeout:2e3,throwOnError:!1})=>S(t);var q=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),o=h();window.webEmitter=o;for(let[n,c]of e){let m=(s,g)=>M(void 0,null,function*(){var a,d;try{let l=yield c(...g);(a=window.ReactNativeWebView)==null||a.postMessage(JSON.stringify({type:"webMethodResponse",body:{funcName:n,eventId:s,value:l}}))}catch(l){(d=window.ReactNativeWebView)==null||d.postMessage(JSON.stringify({type:"webMethodError",body:{funcName:n,eventId:s,error:JSON.stringify(l)}}))}});o.on(n,m)}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,linkNativeMethod,registerWebMethod});
@@ -1 +1 @@
1
- var W=Object.defineProperty,j=Object.defineProperties;var R=Object.getOwnPropertyDescriptors;var S=Object.getOwnPropertySymbols;var A=Object.prototype.hasOwnProperty,D=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,l=(t,e)=>{for(var r in e||(e={}))A.call(e,r)&&x(t,r,e[r]);if(S)for(var r of S(e))D.call(e,r)&&x(t,r,e[r]);return t},b=(t,e)=>j(t,R(e));var v=(t,e,r)=>(x(t,typeof e!="symbol"?e+"":e,r),r);var T=(t,e,r)=>new Promise((o,n)=>{var i=a=>{try{c(r.next(a))}catch(d){n(d)}},s=a=>{try{c(r.throw(a))}catch(d){n(d)}},c=a=>a.done?o(a.value):Promise.resolve(a.value).then(i,s);c((r=r.apply(t,e)).next())});var f=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 o=0,n=r.length;o<n;o++)r[o](...e)},on(t,e){var r;return(r=this.events[t])!=null&&r.push(e)||(this.events[t]=[e]),()=>{var o;this.events[t]=(o=this.events[t])==null?void 0:o.filter(n=>e!==n)}}}),O=({emitter:t,evaluate:e,eventId:r,failHandler:o=!1,methodName:n,onFallback:i})=>new Promise((s,c)=>{let a=t.on(`${n}-${r}`,(d,m)=>{a(),m?o instanceof Error?(i==null||i(),c(o)):s(void 0):s(d)});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),o=Array.isArray(e),n,i,s;if(r&&o){if(i=t.length,i!==e.length)return!1;for(n=i;n--!==0;)if(!h(t[n],e[n]))return!1;return!0}if(r!==o)return!1;let c=Object.keys(t);if(i=c.length,i!==Object.keys(e).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(e,c[n]))return!1;for(n=i;n--!==0;)if(s=c[n],!h(t[s],e[s]))return!1;return!0}return t!==t&&e!==e};var P=t=>(Object.keys(t).forEach(e=>{t[e]===void 0&&delete t[e]}),t);var k=(t,e=!0)=>new Promise((r,o)=>{setTimeout(()=>{e?o(new Error("Timeout")):r(void 0)},t)});var V=()=>new Proxy({},{get:()=>()=>Promise.resolve()});var _=(t,e={},r={})=>{let o=()=>i,n=d=>{let m=l(l({},i),P(d));if(h(i,m))return;let g=i;i=m,c(i,g)};t.on("bridgeStateChange",d=>{n(d)});let i=l(l({},e),r),s=new Set,c=(d,m)=>{for(let g of s)g(d,m)};return{getState:o,subscribe:d=>(s.add(d),()=>s.delete(d))}};var y=()=>({state:{},getState(){return this.state},subscribe(){return()=>{}}});var E=class{constructor(e,r,o,n){this.options=e;this._emitter=r;this._bridgeMethods=o;this._nativeInitialState=n;v(this,"defaultTimeoutMs",2e3);v(this,"store",y());v(this,"loose",V());this._hydrate(o,n)}get isWebViewBridgeAvailable(){return!!window.ReactNativeWebView&&this._bridgeMethods.length>0}isNativeMethodAvailable(e){return typeof e=="string"&&!!window.ReactNativeWebView&&this._bridgeMethods.includes(e)}addEventListener(e,r){return this._emitter.on(`postMessage/${String(e)}`,r)}_postMessage(e,r){var o;(o=window.ReactNativeWebView)==null||o.postMessage(JSON.stringify(r?{type:e,body:r}:{type:e}))}_createNativeMethod(e,r,o,n){return(...i)=>{let s=M();return Promise.race([O({emitter:this._emitter,methodName:e,eventId:s,evaluate:()=>{this._postMessage("bridge",{method:e,eventId:s,args:i})},onFallback:()=>{n==null||n(e,i)},failHandler:r&&new p(e)}),o>0&&k(o,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:o}=this.options;return new Proxy(e,{get:(n,i)=>i in n&&!["isWebViewBridgeAvailable","isNativeMethodAvailable"].includes(i)?n[i]:this._createNativeMethod(i,this._willMethodThrowOnError(i),r,o)})}_hydrate(e,r={}){var s;this._bridgeMethods=e,this._nativeInitialState=r;let{timeout:o=this.defaultTimeoutMs,onFallback:n}=this.options,i=e.reduce((c,a)=>{let d=this._createNativeMethod(a,this._willMethodThrowOnError(a),o,n);return this[a]=d,b(l({},c),{[a]:d})},{});this.loose=this._createLoose(i),this.store=_(this._emitter,i,r),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this._postMessage("getBridgeState")}),this._postMessage("getBridgeState");for(let[c,...a]of(s=window.nativeBatchedEvents)!=null?s:[])this._emitter.emit(c,...a);return window.nativeBatchedEvents=[],!0}};var L=(t={timeout:2e3,throwOnError:!1})=>{var a,d;if(typeof window=="undefined")return{store:y()};window.ReactNativeWebView||console.warn("[WebViewBridge] Not in a WebView environment");let e=w();window.nativeEmitter||(window.nativeEmitter=e);let r=(a=window.__bridgeMethods__)!=null?a:[],o=(d=window.__bridgeInitialState__)!=null?d:{},n=new E(t,e,r,o);if(r.length===0){let m=e.on("hydrate",({bridgeMethods:g,nativeInitialState:u})=>{n._hydrate(g,u),m()})}let{onFallback:i,onReady:s}=t,c=new Proxy(n,{get:(m,g,u)=>g in m?m[g]:(u._postMessage("fallback",{method:g}),u._willMethodThrowOnError(g)?(...N)=>(i==null||i(g,N),Promise.reject(new f(g))):(console.warn(`[WebViewBridge] ${g} is not defined, using fallback.`),()=>Promise.resolve()))});return s==null||s(c),c};var xe=(t={timeout:2e3,throwOnError:!1})=>L(t);var Te=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),o=w();window.webEmitter=o;for(let[i,s]of e){let c=(a,d)=>T(void 0,null,function*(){var m,g;try{let u=yield s(...d);(m=window.ReactNativeWebView)==null||m.postMessage(JSON.stringify({type:"webMethodResponse",body:{funcName:i,eventId:a,value:u}}))}catch(u){(g=window.ReactNativeWebView)==null||g.postMessage(JSON.stringify({type:"webMethodError",body:{funcName:i,eventId:a,error:JSON.stringify(u)}}))}});o.on(i,c)}let n=()=>{var i;(i=window.ReactNativeWebView)==null||i.postMessage(JSON.stringify({type:"registerWebMethod",body:{bridgeNames:r}})),window.removeEventListener("DOMContentLoaded",n)};return window.ReactNativeWebView?(document.addEventListener("visibilitychange",()=>{var i;document.visibilityState==="visible"&&((i=window.ReactNativeWebView)==null||i.postMessage(JSON.stringify({type:"registerWebMethod",body:{bridgeNames:r}})))}),n(),t):(window.addEventListener("DOMContentLoaded",n),t)};export{f as MethodNotFoundError,p as NativeMethodError,L as linkBridge,xe as linkNativeMethod,Te as registerWebMethod};
1
+ var N=Object.defineProperty,W=Object.defineProperties;var R=Object.getOwnPropertyDescriptors;var x=Object.getOwnPropertySymbols;var A=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable;var b=(t,e,r)=>e in t?N(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,f=(t,e)=>{for(var r in e||(e={}))A.call(e,r)&&b(t,r,e[r]);if(x)for(var r of x(e))D.call(e,r)&&b(t,r,e[r]);return t},S=(t,e)=>W(t,R(e));var u=(t,e,r)=>(b(t,typeof e!="symbol"?e+"":e,r),r);var O=(t,e,r)=>new Promise((o,i)=>{var n=s=>{try{m(r.next(s))}catch(g){i(g)}},c=s=>{try{m(r.throw(s))}catch(g){i(g)}},m=s=>s.done?o(s.value):Promise.resolve(s.value).then(n,c);m((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 o=0,i=r.length;o<i;o++)r[o](...e)},on(t,e){var r;return(r=this.events[t])!=null&&r.push(e)||(this.events[t]=[e]),()=>{var o;this.events[t]=(o=this.events[t])==null?void 0:o.filter(i=>e!==i)}}}),B=({emitter:t,evaluate:e,eventId:r,failHandler:o=!1,methodName:i,onFallback:n})=>new Promise((c,m)=>{let s=t.on(`${i}-${r}`,(g,a)=>{s(),a?o instanceof Error?(n==null||n(),m(o)):c(void 0):c(g)});e()});var T="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";var M=(t=21)=>Array.from({length:t},()=>T[Math.floor(Math.random()*T.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),o=Array.isArray(e),i,n,c;if(r&&o){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!==o)return!1;let m=Object.keys(t);if(n=m.length,n!==Object.keys(e).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(e,m[i]))return!1;for(i=n;i--!==0;)if(c=m[i],!h(t[c],e[c]))return!1;return!0}return t!==t&&e!==e};var P=t=>(Object.keys(t).forEach(e=>{t[e]===void 0&&delete t[e]}),t);var _=(t,e=!0)=>new Promise((r,o)=>{setTimeout(()=>{e?o(new Error("Timeout")):r(void 0)},t)});var k=()=>new Proxy({},{get:()=>()=>Promise.resolve()});var V=(t,e={})=>{let r=()=>i,o=s=>{let g=f(f({},i),P(s));if(h(i,g))return;let a=i;i=g,c(i,a)};t.on("bridgeStateChange",s=>{o(s)});let i=f({},e),n=new Set,c=(s,g)=>{for(let a of n)a(s,g)};return{getState:r,subscribe:s=>(n.add(s),()=>n.delete(s))}};var y=(t={})=>({state:t,getState(){return this.state},subscribe(){return()=>{}}});var E=class{constructor(e,r,o,i){this._options=e;this._emitter=r;this._bridgeMethods=o;this._nativeInitialState=i;u(this,"_defaultTimeoutMs",2e3);u(this,"_isListenerRegistered",!1);u(this,"store",y());u(this,"loose",k());this._hydrate(o,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 o;(o=window.ReactNativeWebView)==null||o.postMessage(JSON.stringify(r?{type:e,body:r}:{type:e}))}_createNativeMethod(e,r,o,i){return(...n)=>{let c=M();return Promise.race([B({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)}),o>0&&_(o,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:o}=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,o)})}_hydrate(e,r={}){var g;let{timeout:o=this._defaultTimeoutMs,onFallback:i,initialBridge:n={}}=this._options,c=Object.entries(n).filter(([a,d])=>typeof d=="function"),m=c.map(([a])=>a);Object.defineProperties(this,Object.fromEntries(c.map(([a,d])=>[a,{value:d,writable:!0}]))),this._bridgeMethods=[...e,...m],this._nativeInitialState=r;let s=e.reduce((a,d)=>{if(!this.isReactNativeWebView)return a;let l=this._createNativeMethod(d,this._willMethodThrowOnError(d),o,i);return Object.defineProperty(this,d,{value:l,writable:!1}),S(f({},a),{[d]:l})},n);if(this.loose=this._createLoose(s),this.store=V(this._emitter,f(f({},s),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 L=(t={timeout:2e3,throwOnError:!1})=>{var s,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=(s=window.__bridgeMethods__)!=null?s:[],o=(g=window.__bridgeInitialState__)!=null?g:{},i=new E(t,e,r,o);if(r.length===0){let a=e.on("hydrate",({bridgeMethods:d,nativeInitialState:l})=>{i._hydrate(d,l),a()})}let{onFallback:n,onReady:c}=t,m=new Proxy(i,{get:(a,d,l)=>d in a?a[d]:(l._postMessage("fallback",{method:d}),l._willMethodThrowOnError(d)?(...j)=>(n==null||n(d,j),Promise.reject(new v(d))):(console.warn(`[WebViewBridge] ${d} is not defined, using fallback.`),()=>Promise.resolve()))});return c==null||c(m),m};var be=(t={timeout:2e3,throwOnError:!1})=>L(t);var Oe=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),o=w();window.webEmitter=o;for(let[n,c]of e){let m=(s,g)=>O(void 0,null,function*(){var a,d;try{let l=yield c(...g);(a=window.ReactNativeWebView)==null||a.postMessage(JSON.stringify({type:"webMethodResponse",body:{funcName:n,eventId:s,value:l}}))}catch(l){(d=window.ReactNativeWebView)==null||d.postMessage(JSON.stringify({type:"webMethodError",body:{funcName:n,eventId:s,error:JSON.stringify(l)}}))}});o.on(n,m)}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,L as linkBridge,be as linkNativeMethod,Oe 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 options;
6
+ private _options;
7
7
  private _emitter;
8
8
  private _bridgeMethods;
9
9
  _nativeInitialState: PrimitiveObject;
10
- constructor(options: LinkBridgeOptions<T, V>, _emitter: DefaultEmitter, _bridgeMethods: string[], _nativeInitialState: PrimitiveObject);
11
- private defaultTimeoutMs;
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>, nativeInitialState?: Partial<T>) => Omit<T, "setState">;
7
+ export declare const linkBridgeStore: <T extends BridgeStore<T extends Bridge ? T : any>>(emitter: DefaultEmitter, initialState?: Partial<T>) => Omit<T, "setState">;
@@ -1,5 +1,6 @@
1
- export declare const mockStore: () => {
2
- state: {};
3
- getState(): {};
4
- subscribe(): () => void;
1
+ import { PrimitiveObject } from "../../../../shared/util/src/types";
2
+ export declare const mockStore: (initialState?: PrimitiveObject) => {
3
+ readonly state: PrimitiveObject;
4
+ readonly getState: () => PrimitiveObject;
5
+ readonly subscribe: () => () => void;
5
6
  };
@@ -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 +1,7 @@
1
1
  {
2
2
  "name": "@webview-bridge/web",
3
3
  "type": "module",
4
- "version": "1.5.3",
4
+ "version": "1.6.0-rc.0",
5
5
  "description": "Fully Type-Safe Integration for React Native WebView and Web",
6
6
  "publishConfig": {
7
7
  "access": "public"