@lingxia/bridge 0.5.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.
@@ -0,0 +1 @@
1
+ "use strict";var __extends=this&&this.__extends||function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),__awaiter=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function c(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,c)}l((r=r.apply(e,t||[])).next())})},__generator=this&&this.__generator||function(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=c(0),a.throw=c(1),a.return=c(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function c(c){return function(l){return function(c){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&c[0]?r.return:c[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,c[1])).done)return o;switch(r=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return i.label++,{value:c[1],done:!1};case 5:i.label++,r=c[1],c=[0];continue;case 7:c=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){i=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){i.label=c[1];break}if(6===c[0]&&i.label<o[1]){i.label=o[1],o=c;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(c);break}o[2]&&i.ops.pop(),i.trys.pop();continue}c=t.call(e,i)}catch(e){c=[6,e],r=0}finally{n=o=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,l])}}},__spreadArray=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},LingXiaRuntime=function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});var t="BRIDGE_TIMEOUT",n="BRIDGE_CANCELED",r="BRIDGE_HANDSHAKE_FAILED",o="BRIDGE_MALFORMED_MESSAGE",i="BRIDGE_METHOD_NOT_FOUND",a="BRIDGE_CAPABILITY_DENIED",c="BRIDGE_INTERNAL_ERROR",l="BRIDGE_OUTBOX_FULL",s="BRIDGE_STREAM_CLOSED";function d(e){var t,n=e.os,r=e.send;if(!(typeof window>"u"||typeof document>"u")){var o="iOS"===n;if(o||"Android"===n){var i=Symbol.for("LingXia.NativeComponentCoverageMonitor");if(!(null===(t=window[i])||void 0===t?void 0:t.installed)){var a={installed:!0,coveredById:new Map,coveredCount:0,anyCovered:!1,scheduled:!1,hasAnyVideo:!1,scrollLocked:!1,scrollY:0,htmlOverflow:"",bodyOverflow:"",bodyPosition:"",bodyTop:"",bodyWidth:""};window[i]=a,new MutationObserver(s).observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0}),window.addEventListener("scroll",{handleEvent:function(){!a.hasAnyVideo&&0===a.coveredById.size||s()}},{capture:!0,passive:!0}),window.addEventListener("resize",{handleEvent:function(){return s()}}),s()}}}function c(e){var t,n,r=null===(t=e.getBoundingClientRect)||void 0===t?void 0:t.call(e);if(!r||r.width<2||r.height<2)return!1;var o=r.left+r.width/2,i=r.top+r.height/2;if(o<0||i<0||o>=window.innerWidth||i>=window.innerHeight)return!1;var a=null===(n=document.elementFromPoint)||void 0===n?void 0:n.call(document,o,i);return!(!a||a===document.documentElement||a===document.body)&&!(a===e||e.contains(a))}function l(){a.scheduled=!1;var e=document.querySelectorAll("lx-video[id]");if(a.hasAnyVideo=e.length>0,a.hasAnyVideo||0!==a.coveredById.size||a.anyCovered){for(var t=new Set,n=0,i=Array.from(e);n<i.length;n++){if(h=(p=i[n]).id){t.add(h);var l=c(p),s=a.coveredById.get(h);s!==l&&(!0===s&&(a.coveredCount-=1),!0===l&&(a.coveredCount+=1),a.coveredById.set(h,l),r({id:h,action:"component.coverage",covered:l}))}}for(var d=[],u=0,f=a.coveredById.entries();u<f.length;u++){var v=f[u],p=v[0],h=v[1];t.has(p)||(d.push(p),!0===h&&(a.coveredCount-=1))}for(var m=0,g=d;m<g.length;m++){p=g[m];a.coveredById.delete(p),r({id:p,action:"component.coverage",covered:!1})}var y=a.coveredCount>0;y!==a.anyCovered&&(a.anyCovered=y,o&&(y?function(){if(o&&!a.scrollLocked){var e=document.documentElement,t=document.body;!e||!t||(a.scrollLocked=!0,a.scrollY=window.scrollY||e.scrollTop||0,a.htmlOverflow=e.style.overflow||"",a.bodyOverflow=t.style.overflow||"",a.bodyPosition=t.style.position||"",a.bodyTop=t.style.top||"",a.bodyWidth=t.style.width||"",e.style.overflow="hidden",t.style.overflow="hidden",t.style.position="fixed",t.style.top="".concat(-a.scrollY,"px"),t.style.width="100%")}}():function(){if(o&&a.scrollLocked){var e=document.documentElement,t=document.body;!e||!t||(a.scrollLocked=!1,e.style.overflow=a.htmlOverflow,t.style.overflow=a.bodyOverflow,t.style.position=a.bodyPosition,t.style.top=a.bodyTop,t.style.width=a.bodyWidth,window.scrollTo(0,a.scrollY))}}()))}}function s(){a.scheduled||(a.scheduled=!0,requestAnimationFrame(l))}}var u=typeof window<"u"&&window.__LX_BRIDGE_CFG||{};function f(){return u.os||"unknown"}function v(){return"iOS"===u.os}function p(){return"macOS"===u.os}var h="__LingXiaRecvMessage",m=5e3,g="[LX.Bridge]",y="messageport",w="jsinterface",b={data:!1,proto:!1,all:!1},_=[];function k(e){return b.all||b[e]}function I(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.log.apply(console,__spreadArray([g],e,!1))}function x(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,__spreadArray([g],e,!1))}function E(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,__spreadArray([g],e,!1))}function M(e){try{return JSON.stringify(e)}catch(t){return function(e,t){var n=new WeakSet;return JSON.stringify(e,function(e,t){if("object"==typeof t&&null!==t){if(n.has(t))return"[Circular]";n.add(t)}return t},t)}(e)}}function O(e){try{return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}catch(e){return{}}}var S=function(e){function t(t,n,r){var o=this;return(o=e.call(this,n)||this).name="BridgeError",o.code=t,o.data=r,o}return __extends(t,e),t}(Error);function A(e){if(e instanceof S)return e;if(e&&"object"==typeof e){var t=e,n=c;("string"==typeof t.code&&""!==t.code.trim()||"number"==typeof t.code&&Number.isFinite(t.code))&&(n=t.code);var r="string"==typeof t.message&&""!==t.message.trim()?t.message:"Unknown error";return new S(n,r,"data"in t?t.data:void 0)}var o=e instanceof Error?e.message:"string"==typeof e?e:"Unknown error";return new S(c,o)}var j,C,P="iOS"===u.os||"macOS"===u.os?"webkit":"Harmony"===u.os?"messageport":"Android"===u.os?(null===(C=null===(j=window.LingXiaProxy)||void 0===j?void 0:j.supportsMessagePort)||void 0===C?void 0:C.call(j))?"messageport":"jsinterface":"unknown";typeof window>"u"||"function"!=typeof window[h]&&(window[h]=function(e){_.push(e)});var L=null,T=!1,N=null,B=null,R=null,D=200,X={listenerInstalled:!1,promise:null,resolve:null,reject:null,timer:null},H={handleEvent:function(e){var t,n,r=e;if("LingXia-port-init"===r.data){var o=null===(t=r.ports)||void 0===t?void 0:t[0];o&&(He._connectWebMessagePort(o),null===(n=X.resolve)||void 0===n||n.call(X,o))}}};function q(){X.listenerInstalled||(X.listenerInstalled=!0,window.addEventListener("message",H))}function F(){null!==X.timer&&(window.clearTimeout(X.timer),X.timer=null),X.resolve=null,X.reject=null,X.promise=null}function W(){return"webkit"===P&&(v()||p())}function G(){null!==R&&(clearTimeout(R),R=null)}function U(e){for(var t=0,n=Array.from(oe.keys());t<n.length;t++){ge(n[t],{code:s,message:e})}for(var r=0,o=Array.from(ie.keys());r<o.length;r++){ye(o[r],{code:s,message:e})}!function(e){for(var t=0,n=Array.from(ae.entries());t<n.length;t++){var r=n[t],o=r[0],i=r[1];ae.delete(o),i._emitClose(s,e)}}(e)}function J(){return __awaiter(this,void 0,void 0,function(){var e,t,n,r,o,i,a,c,l;return __generator(this,function(s){switch(s.label){case 0:e=new AbortController,B=e,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,fetch("/__lingxia/bridge/downstream",{method:"GET",cache:"no-store",headers:{Accept:"application/x-ndjson"},signal:e.signal})];case 2:return t=s.sent(),[3,4];case 3:if(n=s.sent(),e.signal.aborted)return[2];throw n;case 4:if(!t.ok)throw new Error("Apple downstream HTTP ".concat(t.status));if(!t.body)throw new Error("Apple downstream response body unavailable");T=!0,D=200,k("proto")&&I("Apple downstream connected"),Ee(),r=t.body.getReader(),o=new TextDecoder,i="",s.label=5;case 5:s.trys.push([5,,10,11]),s.label=6;case 6:return[4,r.read()];case 7:if(a=s.sent(),c=a.value,a.done)return[3,9];i=function(e){for(var t=e;;){var n=t.indexOf("\n");if(n<0)break;var r=t.slice(0,n).trim();if(t=t.slice(n+1),r)try{je(JSON.parse(r))}catch(e){x("Apple downstream parse error:",e,r)}}return t}(i+=o.decode(c,{stream:!0})),s.label=8;case 8:return[3,6];case 9:if(i+=o.decode(),l=i.trim())try{je(JSON.parse(l))}catch(e){x("Apple downstream trailing parse error:",e,l)}return[3,11];case 10:try{r.releaseLock()}catch(e){}return[7];case 11:return[2]}})})}function z(){W()&&(N||(G(),N=J().catch(function(e){(null==B?void 0:B.signal.aborted)||x("Apple downstream failed:",e)}).finally(function(){var e,t=null!==(e=null==B?void 0:B.signal.aborted)&&void 0!==e&&e;N=null,B=null;var n=T;T=!1,function(e,t){xe(),V=null,$=!1,K=!1,Q=0,t&&U(e)}("Apple downstream closed",n),t||function(e){if(W()){G();var t=D;D=Math.min(2*D,2e3),x("Apple downstream disconnected, retrying in ".concat(t,"ms: ").concat(e)),R=setTimeout(function(){R=null,z()},t)}}("stream closed")})))}function Y(e){var t,n,r,o=e.kind;("req"===o||"notify"===o)&&I("postToNative: ".concat(o," ").concat(e.method)),k("proto")&&console.log("→",JSON.stringify(e,null,2));try{if("webkit"===P)return void(null===(n=null===(t=window.webkit)||void 0===t?void 0:t.messageHandlers.LingXia)||void 0===n||n.postMessage(e));var i=M(e);if(P===y&&L)return void L.postMessage(i);if(P===w&&(null===(r=window.LingXiaProxy)||void 0===r?void 0:r.postMessage))return void window.LingXiaProxy.postMessage(i);x("Transport not ready")}catch(i){E("Send error:",i)}}var V=null,$=!1,K=!1,Q=0,Z=null,ee={},te=0;function ne(){return{data:new Set,end:new Set,error:new Set,close:new Set}}function re(e,t){var n,r=ne(),o=!1,i=function(){},a=function(){},c=[],l=[],s=new Promise(function(e,t){i=e,a=t});return(n={id:e,result:s,on:function(e,t){return"data"===e&&r.data.add(t),"end"===e&&r.end.add(t),"error"===e&&r.error.add(t),this}})[Symbol.asyncIterator]=function(){return{next:function(){return c.length>0?Promise.resolve({done:!1,value:c.shift()}):o?s.then(function(e){return{done:!0,value:e}},function(e){return Promise.reject(e)}):new Promise(function(e,t){l.push({resolve:e,reject:t})})}}},n.cancel=function(){o||t()},n._emitData=function(e){if(!o){l.length>0?l.shift().resolve({done:!1,value:e}):c.push(e);for(var t=0,n=r.data;t<n.length;t++){var i=n[t];try{i(e)}catch(e){x("Stream data listener failed:",e)}}}},n._resolve=function(e){if(!o){for(o=!0,i(e);l.length>0;)l.shift().resolve({done:!0,value:e});for(var t=0,n=r.end;t<n.length;t++){var a=n[t];try{a(e)}catch(e){x("Stream end listener failed:",e)}}}},n._reject=function(e){if(!o){for(o=!0,a(e);l.length>0;)l.shift().reject(e);for(var t=0,n=r.error;t<n.length;t++){var i=n[t];try{i(e)}catch(e){x("Stream error listener failed:",e)}}}},n}var oe=new Map,ie=new Map,ae=new Map,ce=[],le=-1,se={},de=new Set,ue=new WeakMap,fe=new Map;function ve(e){if(e.startsWith("host."))return"host";var t=e.indexOf(".");return t>0?e.slice(0,t):"page"}function pe(e){if(null!=e)return e}function he(){return P===y?!!L:W()?T:"webkit"===P||P===w}function me(){return he()&&$}function ge(e,t){var n,r=oe.get(e);if(r){oe.delete(e),null!==r.timerId&&clearTimeout(r.timerId);var o=A(t);if("stream"===r.mode&&r.stream)return void r.stream._reject(o);null===(n=r.reject)||void 0===n||n.call(r,o)}}function ye(e,t){var n=ie.get(e);if(n){ie.delete(e),null!==n.timerId&&clearTimeout(n.timerId);var r=A(t);n.channel._reject(r),n.reject(r)}}function we(e,t){oe.has(e)?ge(e,t):ie.has(e)&&ye(e,t)}function be(e){var n=oe.get(e);if(n){if(!Number.isFinite(n.timeoutMs)||n.timeoutMs<=0)return void(null!==n.timerId&&(clearTimeout(n.timerId),n.timerId=null));null!==n.timerId&&clearTimeout(n.timerId),n.timerId=setTimeout(function(){oe.has(e)&&ge(e,new S(t,"'".concat(n.method,"' timed out")))},n.timeoutMs)}}function _e(e){oe.has(e)?be(e):ie.has(e)&&function(e){var n=ie.get(e);n&&(null!==n.timerId&&clearTimeout(n.timerId),n.timerId=setTimeout(function(){ye(e,{code:t,message:"Channel '".concat(n.topic,"' timed out")})},m))}(e)}function ke(e){for(var t,n=ce.length-1;n>=0;n--)if((null===(t=ce[n])||void 0===t?void 0:t.reqId)===e)return ce.splice(n,1),!0;return!1}function Ie(e,t){var n=e.kind,r="hello"===n||"helloAck"===n||"ready"===n;if(!me()&&!r)return ce.length>=256?(E("Outbox full"),void(t&&we(t,{code:l,message:"Bridge outbox is full"}))):void ce.push({msg:e,reqId:t});t&&_e(t),Y(e)}function xe(){null!==Z&&(clearTimeout(Z),Z=null)}function Ee(){if(!$&&he()){xe();var e={v:2,kind:"hello",nonce:u.nonce||"",role:"view",protocolsSupported:[2]};K=!0,Y(e),Z=setTimeout(function(){if(!$)if(++Q<3)x("Handshake timeout (".concat(Q,"/").concat(3,"), retrying...")),K=!1,Ee();else{for(E("Handshake failed"),xe(),K=!1,Q=0;ce.length;){(null==(n=ce.shift())?void 0:n.reqId)&&we(n.reqId,{code:r,message:"Bridge handshake failed"})}for(var e=0,t=Array.from(ie.keys());e<t.length;e++){var n;ye(n=t[e],{code:r,message:"Bridge handshake failed"})}}},1e4)}}function Me(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Oe(e,t,n){void 0===n&&(n=!1);var r=function(e){if(""===e)return[];if(!e.startsWith("/"))throw new Error("Invalid JSON pointer: ".concat(e));return e.split("/").slice(1).map(Me)}(t);if(0===r.length)return{container:{$root:e},key:"$root"};for(var o=e,i=0;i<r.length-1;i++){var a=r[i];if(Array.isArray(o))o=o[Number(a)];else{if(!o||"object"!=typeof o)throw new Error("Invalid container at ".concat(a));var c=o;if(n&&void 0===c[a]){var l=r[i+1];c[a]=l&&/^\d+$/.test(l)?[]:{}}o=c[a]}}return{container:o,key:r[r.length-1]}}function Se(e){de.forEach(function(t){try{if(!ue.has(t))return ue.set(t,!0),void t(O(se),{rev:le,initial:!0});t(O(se),{rev:le,initial:e})}catch(e){x("Subscriber error:",e)}})}function Ae(e){He.call("state.getSnapshot",{scope:e}).catch(function(){})}function je(e){var t,n;if(e&&"object"==typeof e&&("event"===(u=e).type&&"nativecomponent"===u.name&&u.payload)){var r=(f=u.payload).id||f.componentId;if("string"==typeof r){var o=Ce.get(r);if(o)try{o(f)}catch(e){E("NC handler error:",e)}}return}var c=function(e){if(!e||"object"!=typeof e)return null;var t=e.v,n=e.kind;return 2!==t||"string"!=typeof n?null:e}(e);if(c)switch(c.kind){case"helloAck":return void(V=c.sessionId);case"ready":if(V&&c.sessionId!==V)return void x("sessionId mismatch");if(xe(),$=!0,Q=0,c.hostMethods)for(var l=0,s=Object.entries(c.hostMethods);l<s.length;l++){var d=s[l],u=d[0],f=d[1];ee[u]=f}return k("proto")&&I("Handshake complete, hostMethods:",Object.keys(ee).length),void function(){if(me())for(;ce.length;){var e=ce.shift();e&&(e.reqId&&_e(e.reqId),Y(e.msg))}}();case"res":if(!(u=oe.get(c.id)))return;if(oe.delete(c.id),null!==u.timerId&&clearTimeout(u.timerId),c.ok){if("state.getSnapshot"===u.method&&(function(e){if(!e||"object"!=typeof e)return!1;var t=e;return!("number"!=typeof t.rev||!Number.isFinite(t.rev)||!t.state||"object"!=typeof t.state||(se=t.state,le=t.rev,k("data")&&(console.group("[LX] snapshot(res)"),console.log("rev:",le,"state:",O(se)),console.groupEnd()),Se(!0),0))}(c.result)||x("Invalid state.getSnapshot result")),"stream"===u.mode&&u.stream)return void u.stream._resolve(c.result);null===(t=u.resolve)||void 0===t||t.call(u,c.result)}else{f=A(c.error);if("stream"===u.mode&&u.stream)return void u.stream._reject(f);null===(n=u.reject)||void 0===n||n.call(u,f)}return;case"event":return oe.has(c.id)?void("stream"===(null==(u=oe.get(c.id))?void 0:u.mode)&&u.stream?(be(c.id),u.stream._emitData(c.payload)):x("Received event for non-stream request '".concat(c.id,"'"))):void 0;case"state.snapshot":return se=c.state||{},le=c.rev,k("data")&&(console.group("[LX] snapshot"),console.log("rev:",le,"state:",O(se)),console.groupEnd()),void Se(!0);case"state.patch":if(c.baseRev!==le)return x("baseRev mismatch",{have:le,want:c.baseRev}),void Ae(c.scope);try{(function(e,t){for(var n=0,r=t;n<r.length;n++){var o=r[n],i="add"===o.op||"replace"===o.op,a=Oe(e,o.path,i),c=a.container,l=a.key;if("$root"!==l)if(Array.isArray(c)){if(f="-"===l?c.length:Number(l),!Number.isFinite(f)||f<0)throw new Error("Invalid index");"remove"===o.op?c.splice(f,1):"add"===o.op?c.splice(f,0,o.value):"replace"===o.op&&(c[f]=o.value)}else{if(!c||"object"!=typeof c)throw new Error("Invalid container");var s=c;"remove"===o.op?delete s[l]:s[l]=o.value}else{for(var d=0,u=Object.keys(e);d<u.length;d++)delete e[f=u[d]];var f;"remove"!==o.op&&(f=o.value)&&"object"==typeof f&&Object.assign(e,f)}}})(se,c.ops||[]),le=c.rev}catch(u){return E("Patch failed:",u),void Ae(c.scope)}return k("data")&&(console.group("[LX] patch"),console.log("rev:",le,"ops:",c.ops),console.groupEnd()),Se(!1),void(c.ack&&Ie({v:2,kind:"state.ack",scope:c.scope,rev:c.rev}));case"ch.ack":if(!(u=ie.get(c.id)))return;if(ie.delete(c.id),null!==u.timerId&&clearTimeout(u.timerId),c.ok)u.channel._markOpen(),ae.set(c.id,u.channel),u.resolve(u.channel);else{f=A(c.error);u.channel._reject(f),u.reject(f)}return;case"ch.data":if(!(u=ae.get(c.id)))return;return void u._emitData(c.payload);case"ch.close":if(u=ie.get(c.id))return ie.delete(c.id),void u.channel._emitClose(c.code,c.reason);if(!(f=ae.get(c.id)))return;return ae.delete(c.id),void f._emitClose(c.code,c.reason);case"req":var v=c;f=ve(v.method);if(!v.cap||v.cap!==f)return void Ie({v:2,kind:"res",id:v.id,ok:!1,error:{code:a,message:"Invalid cap for ".concat(v.method)}});var p=fe.get(v.method);return p?void Promise.resolve().then(function(){return p(v.params)}).then(function(e){Ie({v:2,kind:"res",id:v.id,ok:!0,result:e})}).catch(function(e){Ie({v:2,kind:"res",id:v.id,ok:!1,error:A(e)})}):void Ie({v:2,kind:"res",id:v.id,ok:!1,error:{code:i,message:"View handler not found: ".concat(v.method)}})}else x("Invalid V2 message:",e)}var Ce=new Map,Pe=[],Le=!1;function Te(){var e,t,n;return!(typeof window>"u")&&!(!(null===(t=null===(e=window.webkit)||void 0===e?void 0:e.messageHandlers)||void 0===t?void 0:t.NativeComponent)&&!(null===(n=window.NativeComponentBridge)||void 0===n?void 0:n.postMessage))}function Ne(e){var t,n,r;try{if(null===(n=null===(t=window.webkit)||void 0===t?void 0:t.messageHandlers)||void 0===n?void 0:n.NativeComponent)return void window.webkit.messageHandlers.NativeComponent.postMessage(e);if(null===(r=window.NativeComponentBridge)||void 0===r?void 0:r.postMessage)return void window.NativeComponentBridge.postMessage(M(e))}catch(e){E("NativeComponent send error:",e)}}function Be(){if(Te()&&0!==Pe.length)for(Le=!0;Pe.length;){var e=Pe.shift();try{Ne(e)}catch(e){break}}}function Re(e){try{if(!Te())return void Pe.push(e);Le||Be(),Ne(e)}catch(e){E("NC send failed:",e)}}function De(e){return"".concat(e,"_").concat(Date.now(),"_").concat(te++)}function Xe(e,t,n){if(t)if(t.aborted)n();else{var r={handleEvent:function(){t.removeEventListener("abort",r),n()}};t.addEventListener("abort",r)}}var He={call:function(e,t,r){return new Promise(function(i,a){var c;if(e&&"string"==typeof e){K||Ee();var l=De("c"),s=(null==r?void 0:r.cap)||ve(e),d=null!==(c=null==r?void 0:r.timeoutMs)&&void 0!==c?c:m;oe.set(l,{method:e,mode:"call",resolve:i,reject:function(e){return a(e)},timeoutMs:d,timerId:null}),Ie({v:2,kind:"req",id:l,method:e,params:pe(t),cap:s},l),Xe(0,null==r?void 0:r.signal,function(){var e=ke(l);ge(l,{code:n,message:"Bridge request aborted"}),!e&&$&&Ie({v:2,kind:"cancel",id:l})})}else a(new S(o,"Method name must be a non-empty string"))})},stream:function(e,t,r){var i;if(!e||"string"!=typeof e){var a=re("invalid",function(){});return a._reject({code:o,message:"Method name must be a non-empty string"}),a}K||Ee();var c=De("c"),l=re(c,function(){ke(c)?ge(c,{code:n,message:"Bridge request aborted"}):$&&Ie({v:2,kind:"cancel",id:c})}),s=(null==r?void 0:r.cap)||ve(e),d=null!==(i=null==r?void 0:r.timeoutMs)&&void 0!==i?i:m;return oe.set(c,{method:e,mode:"stream",stream:l,timeoutMs:d,timerId:null}),Ie({v:2,kind:"req",id:c,method:e,params:pe(t),cap:s},c),Xe(0,null==r?void 0:r.signal,function(){return l.cancel()}),l},notify:function(e,t,n){!e||"string"!=typeof e||(K||Ee(),Ie({v:2,kind:"notify",method:e,params:pe(t),cap:(null==n?void 0:n.cap)||ve(e)}))},state:{subscribe:function(e){if("function"!=typeof e)return function(){};if(de.add(e),le>=0){ue.set(e,!0);try{e(O(se),{rev:le,initial:!0})}catch(e){E("Callback error:",e)}}return function(){de.delete(e),ue.delete(e)}}},channel:{open:function(e,t,n){return e&&"string"==typeof e?(K||Ee(),new Promise(function(r,o){var i=De("ch"),a=function(e,t,n){var r,o=ne(),i=!1,a=0,c=!1,l=[],d=[],u=((r={id:e,send:function(n){i?t(n,a++):u._reject({code:s,message:"Channel '".concat(e,"' is closed")})},on:function(e,t){return"data"===e&&o.data.add(t),"close"===e&&o.close.add(t),"error"===e&&o.error.add(t),this}})[Symbol.asyncIterator]=function(){return{next:function(){return l.length>0?Promise.resolve({done:!1,value:l.shift()}):c?Promise.resolve({done:!0,value:void 0}):new Promise(function(e,t){d.push({resolve:e,reject:t})})}}},r.close=function(e,t){i&&(i=!1,c=!0,n(e,t),u._emitClose(e,t))},r._emitData=function(e){if(i){d.length>0?d.shift().resolve({done:!1,value:e}):l.push(e);for(var t=0,n=o.data;t<n.length;t++){var r=n[t];try{r(e)}catch(e){x("Channel listener failed:",e)}}}},r._emitClose=function(e,t){for(c=!0;d.length>0;)d.shift().resolve({done:!0,value:void 0});for(var n=0,r=o.close;n<r.length;n++){var i=r[n];try{i(e,t)}catch(e){x("Channel close listener failed:",e)}}},r._reject=function(e){for(c=!0;d.length>0;)d.shift().reject(e);for(var t=0,n=o.error;t<n.length;t++){var r=n[t];try{r(e)}catch(e){x("Channel error listener failed:",e)}}},r._markOpen=function(){i=!0,c=!1},r._isOpen=function(){return i},r._nextSeq=function(){return a++},r);return u}(i,function(e,t){Ie({v:2,kind:"ch.data",id:i,seq:t,payload:e})},function(e,t){var n=ie.get(i);n&&null!==n.timerId&&clearTimeout(n.timerId),ie.delete(i),ae.delete(i),Ie({v:2,kind:"ch.close",id:i,code:e,reason:t})});ie.set(i,{topic:e,channel:a,resolve:r,reject:o,timerId:null}),Ie({v:2,kind:"ch.open",id:i,topic:e,params:pe(t),cap:(null==n?void 0:n.cap)||ve(e)},i)})):Promise.reject(new S(o,"Topic name must be a non-empty string"))}},_connectWebMessagePort:function(e){if(P===y){if(L&&L!==e)try{L.onmessage=null,L.close()}catch(e){}L=e,e.onmessage=function(e){var t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch(e){return}je(t)};try{e.start()}catch(e){}I("Port connected"),Ee()}},_receiveEvaluateMessage:function(e){try{e&&je(JSON.parse(e))}catch(e){E("Parse error:",e)}},debug:new Proxy(b,{get:function(e,t){return e[t]},set:function(e,t,n){return t in e&&(e[t]=!!n,console.log("[LX] ".concat(t,": ").concat(n)),!0)}}),platform:{isHarmony:function(){return"Harmony"===u.os},isIOS:v,isAndroid:function(){return"Android"===u.os},isMacOS:p,isDesktop:function(){return p()},getOS:f},dom:{measureById:function(e){try{if(!e)return null;var t=document.getElementById(e);if(!t)return null;var n=t.getBoundingClientRect(),r=0;try{r=parseFloat(getComputedStyle(t).borderRadius)||0}catch(e){}return[n.left+window.scrollX,n.top+window.scrollY,n.width,n.height,r]}catch(e){return null}}},nativeComponents:{send:Re,hasHandler:Te,flush:Be,register:function(e,t){return e&&"function"==typeof t?(Ce.set(e,t),function(){return Ce.delete(e)}):function(){}},unregister:function(e){Ce.delete(e)}},isReady:function(){return $}};function qe(e){return new Proxy(function(){},{apply:function(t,n,r){var o=e.join("."),i=0===r.length?void 0:1===r.length?r[0]:r,a=He.stream("host.".concat(o),i,{cap:"host",timeoutMs:0}),c=a.result;return new Proxy(a,{get:function(e,t){if("then"===t)return c.then.bind(c);if("catch"===t)return c.catch.bind(c);var n=e[t];return"function"==typeof n?n.bind(e):n}})},get:function(t,n){if("then"!==n){if("__funcName"===n)return"host.".concat(e.join("."));if("__bridgeMode"===n)return"stream";if("string"==typeof n)return qe(__spreadArray(__spreadArray([],e,!0),[n],!1))}}})}function Fe(e){return new Proxy(function(){},{apply:function(t,n,r){var o=e.join("."),i=0===r.length?void 0:1===r.length?r[0]:r;return He.channel.open("host.".concat(o),i,{cap:"host"})},get:function(t,n){if("then"!==n){if("__funcName"===n)return"host.".concat(e.join("."));if("__bridgeMode"===n)return"channel";if("open"===n)return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=e.join("."),o=0===t.length?void 0:1===t.length?t[0]:t;return He.channel.open("host.".concat(r),o,{cap:"host"})};if("string"==typeof n)return Fe(__spreadArray(__spreadArray([],e,!0),[n],!1))}}})}var We=new Proxy({},{get:function(e,t){if("string"==typeof t)return"channel"===t?new Proxy({},{get:function(e,t){if("string"==typeof t)return Fe([t])}}):qe([t])}});function Ge(){I("Method: ".concat(P)),function(e){if(!(typeof window>"u"||(window[h]=e,0===_.length)))for(var t=0,n=_.splice(0,_.length);t<n.length;t++){var r=n[t];try{e(r)}catch(e){x("Failed to replay queued native message:",e)}}}(He._receiveEvaluateMessage),W()?z():P===y?(q(),function(){var e,t;if(L)return Promise.resolve(L);if(X.promise)return X.promise;q(),X.promise=new Promise(function(e,t){X.resolve=function(t){F(),e(t)},X.reject=function(e){F(),t(e)},X.timer=window.setTimeout(function(){var e;null===(e=X.reject)||void 0===e||e.call(X,new Error("MessagePort init timed out after ".concat(5e3,"ms")))},5e3)});try{null===(e=window.LingXiaProxy)||void 0===e||e.getPort("LingXiaPort")}catch(e){null===(t=X.reject)||void 0===t||t.call(X,e)}return X.promise}().catch(function(e){return x("Port init failed:",e)})):"webkit"===P||P===w?Ee():x("Unknown method"),window.LingXiaBridge=He,window.host=We,d({os:f(),send:Re}),I("Init complete")}function Ue(e){var t=document.createElement("div");return t.textContent=e,t.innerHTML}function Je(e){var t=e.failedPath,n=e.reason,r=document.createElement("style");r.textContent="\n* { margin: 0; padding: 0; box-sizing: border-box; }\nbody {\n font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', Roboto, sans-serif;\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n background: #f5f5f7;\n color: #1d1d1f;\n padding: 20px;\n -webkit-font-smoothing: antialiased;\n}\n.lx-error {\n text-align: center;\n max-width: 400px;\n}\n.lx-error-code {\n font-size: 120px;\n font-weight: 700;\n color: #d1d1d6;\n line-height: 1;\n letter-spacing: -4px;\n}\n.lx-error-title {\n font-size: 21px;\n font-weight: 600;\n margin: 16px 0 8px;\n color: #1d1d1f;\n}\n.lx-error-desc {\n font-size: 15px;\n color: #86868b;\n line-height: 1.5;\n}\n.lx-error-path {\n display: inline-block;\n margin-top: 20px;\n padding: 10px 16px;\n background: rgba(0,0,0,0.04);\n border-radius: 8px;\n font-family: 'SF Mono', ui-monospace, Menlo, Monaco, monospace;\n font-size: 13px;\n color: #1d1d1f;\n word-break: break-all;\n max-width: 100%;\n}\n@media (prefers-color-scheme: dark) {\n body { background: #000; color: #f5f5f7; }\n .lx-error-code { color: #3a3a3c; }\n .lx-error-title { color: #f5f5f7; }\n .lx-error-desc { color: #86868b; }\n .lx-error-path { background: rgba(255,255,255,0.08); color: #f5f5f7; }\n}\n",document.head.appendChild(r),document.body.innerHTML="",document.body.style.cssText="";var o=document.createElement("div");o.className="lx-error";var i='<div class="lx-error-code">404</div>';i+='<h1 class="lx-error-title">Page Not Found</h1>',i+="<p class=\"lx-error-desc\">The page you're looking for doesn't exist.</p>",t&&(i+='<div class="lx-error-path">'.concat(Ue(t),"</div>")),n&&(i+='<p class="lx-error-desc" style="margin-top:12px">'.concat(Ue(n),"</p>")),o.innerHTML=i,document.body.appendChild(o)}function ze(){var e=window.__LX_RUNTIME_CONFIG;return!(!e||!e.error)}function Ye(){var e;return(null===(e=window.__LX_RUNTIME_CONFIG)||void 0===e?void 0:e.error)||null}var Ve={handleEvent:function(){return $e()}};function $e(){if(ze()){var e=Ye();e&&Je(e)}}function Ke(){Ge(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Ve):$e()}function Qe(e){var t=e.trim();return function(e){return!(0===e.length||e.startsWith("lx://")||e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("file:"))&&(e.startsWith("http://")||e.startsWith("https://"))}(t)?function(e){return"".concat("lx://proxy/").concat(btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,""))}(t):e}return function(){var e=f();if(!("iOS"!==e&&"macOS"!==e||typeof window>"u"||typeof document>"u"||typeof HTMLImageElement>"u")){var t=HTMLImageElement.prototype;if(!t.__lxProxyPatched){t.__lxProxyPatched=!0;var n=t.setAttribute;t.setAttribute=function(e,t){return"string"==typeof e&&"src"===e.toLowerCase()&&"string"==typeof t?n.call(this,e,Qe(t)):n.call(this,e,t)};var r=Object.getOwnPropertyDescriptor(t,"src");(null==r?void 0:r.set)&&Object.defineProperty(t,"src",{configurable:r.configurable,enumerable:r.enumerable,get:r.get,set:function(e){var t,n;"string"==typeof e?null===(t=r.set)||void 0===t||t.call(this,Qe(e)):null===(n=r.set)||void 0===n||n.call(this,e)}});var o=function(){document.querySelectorAll("img[src]").forEach(function(e){var t=e.getAttribute("src");if(t){var r=Qe(t);r!==t&&n.call(e,"src",r)}})};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",{handleEvent:function(){return o()}}):o()}}}(),Ke(),e.LingXiaBridge=He,e.boot=function(){Ge(),$e()},e.bootWhenReady=Ke,e.getErrorInfo=Ye,e.hasError=ze,e.host=We,e.initBridge=Ge,e.renderErrorUI=Je,e}({});
@@ -0,0 +1,164 @@
1
+ export interface BridgeConfig {
2
+ os?: 'Harmony' | 'iOS' | 'Android' | 'macOS';
3
+ nonce?: string;
4
+ }
5
+ export interface RuntimeConfig {
6
+ error?: ErrorInfo;
7
+ }
8
+ export interface ErrorInfo {
9
+ failedPath?: string;
10
+ reason?: string;
11
+ code?: number;
12
+ }
13
+ export declare const BRIDGE_ERROR: {
14
+ readonly NOT_READY: "BRIDGE_NOT_READY";
15
+ readonly TIMEOUT: "BRIDGE_TIMEOUT";
16
+ readonly CANCELED: "BRIDGE_CANCELED";
17
+ readonly PROTOCOL_MISMATCH: "BRIDGE_PROTOCOL_MISMATCH";
18
+ readonly HANDSHAKE_FAILED: "BRIDGE_HANDSHAKE_FAILED";
19
+ readonly MALFORMED_MESSAGE: "BRIDGE_MALFORMED_MESSAGE";
20
+ readonly METHOD_NOT_FOUND: "BRIDGE_METHOD_NOT_FOUND";
21
+ readonly TOPIC_NOT_FOUND: "BRIDGE_TOPIC_NOT_FOUND";
22
+ readonly CAPABILITY_DENIED: "BRIDGE_CAPABILITY_DENIED";
23
+ readonly INTERNAL_ERROR: "BRIDGE_INTERNAL_ERROR";
24
+ readonly OUTBOX_FULL: "BRIDGE_OUTBOX_FULL";
25
+ readonly STREAM_OVERFLOW: "BRIDGE_STREAM_OVERFLOW";
26
+ readonly STREAM_CLOSED: "BRIDGE_STREAM_CLOSED";
27
+ };
28
+ export type BridgeErrorCode = (typeof BRIDGE_ERROR)[keyof typeof BRIDGE_ERROR];
29
+ export interface LxBridgeError {
30
+ code: string | number;
31
+ message?: string;
32
+ data?: unknown;
33
+ }
34
+ export interface StateInfo {
35
+ rev: number;
36
+ initial: boolean;
37
+ }
38
+ export type DataSubscriber = (data: Record<string, unknown>, info: StateInfo) => void;
39
+ export interface LingXiaBridgeMethodMap {
40
+ }
41
+ export type LxMethodParams<M extends keyof LingXiaBridgeMethodMap> = LingXiaBridgeMethodMap[M] extends {
42
+ params: infer P;
43
+ } ? P : LingXiaBridgeMethodMap[M] extends {
44
+ params?: infer P;
45
+ } ? P | undefined : unknown;
46
+ export type LxMethodResult<M extends keyof LingXiaBridgeMethodMap> = LingXiaBridgeMethodMap[M] extends {
47
+ result: infer R;
48
+ } ? R : unknown;
49
+ export type LxMethodStreamData<M extends keyof LingXiaBridgeMethodMap> = LingXiaBridgeMethodMap[M] extends {
50
+ stream: infer S;
51
+ } ? S : unknown;
52
+ export type LxMethod = keyof LingXiaBridgeMethodMap & string;
53
+ export interface NativeComponentMessage {
54
+ id: string;
55
+ action?: string;
56
+ [key: string]: unknown;
57
+ }
58
+ export interface CallOptions {
59
+ cap?: string;
60
+ timeoutMs?: number;
61
+ signal?: AbortSignal;
62
+ }
63
+ export interface NotifyOptions {
64
+ cap?: string;
65
+ }
66
+ export interface StreamCallOptions extends CallOptions {
67
+ }
68
+ export interface ChannelOpenOptions {
69
+ cap?: string;
70
+ }
71
+ export type StreamEventName = 'data' | 'end' | 'error';
72
+ export type ChannelEventName = 'data' | 'close' | 'error';
73
+ export interface LxStream<TData = unknown, TResult = unknown> extends AsyncIterable<TData> {
74
+ on(event: 'data', listener: (payload: TData) => void): this;
75
+ on(event: 'end', listener: (result: TResult) => void): this;
76
+ on(event: 'error', listener: (error: LxBridgeError) => void): this;
77
+ cancel(): void;
78
+ [Symbol.asyncIterator](): AsyncIterator<TData, TResult, void>;
79
+ readonly id: string;
80
+ readonly result: Promise<TResult>;
81
+ }
82
+ export interface HostChannelApi {
83
+ [namespace: string]: unknown;
84
+ }
85
+ export interface HostApi {
86
+ channel: HostChannelApi;
87
+ [namespace: string]: unknown;
88
+ }
89
+ export interface LxChannel<TIn = unknown, TOut = TIn> extends AsyncIterable<TIn> {
90
+ send(payload: TOut): void;
91
+ on(event: 'data', listener: (payload: TIn) => void): this;
92
+ on(event: 'close', listener: (code?: string, reason?: string) => void): this;
93
+ on(event: 'error', listener: (error: LxBridgeError) => void): this;
94
+ close(code?: string, reason?: string): void;
95
+ [Symbol.asyncIterator](): AsyncIterator<TIn, void, void>;
96
+ readonly id: string;
97
+ }
98
+ declare global {
99
+ interface Window {
100
+ __LX_BRIDGE_CFG?: BridgeConfig;
101
+ __LX_RUNTIME_CONFIG?: RuntimeConfig;
102
+ __pageBridge?: {
103
+ __names: string[];
104
+ [key: string]: unknown;
105
+ };
106
+ __LingXiaRecvMessage?: (message: string) => void;
107
+ LingXiaBridge?: LingXiaBridgeInterface;
108
+ LingXiaProxy?: {
109
+ supportsMessagePort: () => boolean;
110
+ getPort: (name: string) => string;
111
+ postMessage: (message: string) => void;
112
+ };
113
+ NativeComponentBridge?: {
114
+ postMessage: (message: string) => void;
115
+ };
116
+ host?: HostApi;
117
+ webkit?: {
118
+ messageHandlers: {
119
+ [key: string]: {
120
+ postMessage: (message: unknown) => void;
121
+ };
122
+ };
123
+ };
124
+ }
125
+ }
126
+ export interface LingXiaBridgeInterface {
127
+ call(method: string, params?: unknown, options?: CallOptions): Promise<unknown>;
128
+ call<M extends LxMethod>(method: M, params?: LxMethodParams<M>, options?: CallOptions): Promise<LxMethodResult<M>>;
129
+ stream(method: string, params?: unknown, options?: StreamCallOptions): LxStream<unknown, unknown>;
130
+ stream<M extends LxMethod>(method: M, params?: LxMethodParams<M>, options?: StreamCallOptions): LxStream<LxMethodStreamData<M>, LxMethodResult<M>>;
131
+ notify(method: string, params?: unknown, options?: NotifyOptions): void;
132
+ state: {
133
+ subscribe(callback: DataSubscriber): () => void;
134
+ };
135
+ channel: {
136
+ open<TIn = unknown, TOut = TIn>(topic: string, params?: unknown, options?: ChannelOpenOptions): Promise<LxChannel<TIn, TOut>>;
137
+ };
138
+ _connectWebMessagePort(port: MessagePort): void;
139
+ _receiveEvaluateMessage(messageString: string): void;
140
+ debug: {
141
+ data: boolean;
142
+ proto: boolean;
143
+ all: boolean;
144
+ };
145
+ platform: {
146
+ isHarmony(): boolean;
147
+ isIOS(): boolean;
148
+ isAndroid(): boolean;
149
+ isMacOS(): boolean;
150
+ isDesktop(): boolean;
151
+ getOS(): string;
152
+ };
153
+ dom: {
154
+ measureById(id: string): [number, number, number, number, number] | null;
155
+ };
156
+ nativeComponents: {
157
+ send(message: NativeComponentMessage): void;
158
+ hasHandler(): boolean;
159
+ flush(): void;
160
+ register(id: string, handler: (message: NativeComponentMessage) => void): () => void;
161
+ unregister(id: string): void;
162
+ };
163
+ isReady(): boolean;
164
+ }
@@ -0,0 +1,5 @@
1
+ interface ActionSheetResult {
2
+ tapIndex: number;
3
+ }
4
+ export declare function showActionSheet(params: unknown): Promise<ActionSheetResult>;
5
+ export {};
@@ -0,0 +1 @@
1
+ export declare function registerUIHandlers(): void;
@@ -0,0 +1,6 @@
1
+ interface ModalResult {
2
+ confirm: boolean;
3
+ cancel: boolean;
4
+ }
5
+ export declare function showModal(params: unknown): Promise<ModalResult>;
6
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare function showToast(params: unknown): Promise<void>;
2
+ export declare function hideToast(): Promise<void>;
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@lingxia/bridge",
3
+ "version": "0.5.0",
4
+ "private": false,
5
+ "description": "LingXia Web Runtime - Bridge, boot, and error handling for WebView",
6
+ "type": "module",
7
+ "main": "dist/runtime.es2020.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/runtime.es2020.js"
13
+ },
14
+ "./dist/runtime.es2020.js": "./dist/runtime.es2020.js",
15
+ "./dist/runtime.es5.js": "./dist/runtime.es5.js",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "scripts": {
19
+ "build": "npm run clean && npm run build:es2020 && npm run build:es5 && npm run build:types",
20
+ "build:es2020": "RUNTIME_OUTPUT=runtime.es2020.js rolldown -c",
21
+ "build:es5": "node ./scripts/build-es5.mjs",
22
+ "build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
23
+ "dev": "rolldown -c -w",
24
+ "clean": "rm -rf dist",
25
+ "prepublishOnly": "npm run build"
26
+ },
27
+ "devDependencies": {
28
+ "esbuild": "^0.25.3",
29
+ "rolldown": "^1.0.0-rc.13",
30
+ "rollup-plugin-esbuild": "^6.2.1",
31
+ "terser": "^5.39.0",
32
+ "tslib": "^2.6.2",
33
+ "typescript": "^5.3.0"
34
+ },
35
+ "files": [
36
+ "dist"
37
+ ],
38
+ "publishConfig": {
39
+ "registry": "https://registry.npmjs.org",
40
+ "access": "public"
41
+ },
42
+ "license": "MIT"
43
+ }