@trimjs/web-app 0.0.2 → 0.0.3
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/index.cjs +0 -1
- package/dist/index.iife.js +0 -1
- package/dist/index.js +0 -1
- package/dist/index.umd.cjs +0 -1
- package/package.json +5 -3
- package/src/index.ts +3 -3
- package/src/web/index.ts +4 -4
- package/dist/index.cjs.map +0 -1
- package/dist/index.iife.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/index.umd.cjs.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
1
|
"use strict";var we=Object.defineProperty;var ve=(r,e,t)=>e in r?we(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var A=(r,e,t)=>ve(r,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class Ee{constructor(){A(this,"debug",!1)}setDebug(e){this.debug=e}isDebug(){return this.debug}log(...e){this.debug&&console.log("[Trim App]",...e)}warn(...e){this.debug&&console.warn("[Trim App]",...e)}error(...e){this.debug&&console.error("[Trim App]",...e)}info(...e){this.debug&&console.info("[Trim App]",...e)}}const d=new Ee;function Se(r){const e=/FNOS\/([\d.]+)|FNAppType\/(\w+)|FNAppVer\/([\d.]+)/g,t={};let n;for(;(n=e.exec(r))!==null;)n[1]&&(t.fnOSVersion=n[1]),n[2]&&(t.fnAppType=n[2]),n[3]&&(t.fnAppVersion=n[3]);return t}const ce=()=>Se(navigator.userAgent).fnAppVersion,Ae=()=>new Promise(r=>{var e;(e=window.flutter_inappwebview)!=null&&e._platformReady?(d.log("flutter_inappwebview is ready"),r(window.flutter_inappwebview)):window.addEventListener("flutterInAppWebViewPlatformReady",()=>{d.log("flutter_inappwebview is ready"),r(window.flutter_inappwebview)})}),$e=async(r,e,t)=>{d.log(`callHandler: ${e}, params: ${t}`);const n=await r.callHandler(e,t);if(n)try{const o=JSON.parse(n);d.log(`messageData: ${JSON.stringify(o)}`);const i=JSON.parse(o.result);return d.log(`appMessage: ${JSON.stringify(i)}`),i}catch(o){return d.error(`error: ${o}`),null}return null},Q=new Map;function Pe(){window.fnAppMessage=r=>{d.log("app-message",r);const e=JSON.parse(r),t=Q.get(e.reqId);t&&(t(e),Q.delete(e.reqId))}}ce()&&Pe();var F=(r=>(r.Call="call",r.Reply="reply",r.Syn="syn",r.SynAck="synAck",r.Ack="ack",r))(F||{}),j=(r=>(r.Fulfilled="fulfilled",r.Rejected="rejected",r))(j||{}),z=(r=>(r.ConnectionDestroyed="ConnectionDestroyed",r.ConnectionTimeout="ConnectionTimeout",r.NoIframeSrc="NoIframeSrc",r))(z||{}),ae=(r=>(r.DataCloneError="DataCloneError",r))(ae||{}),R=(r=>(r.Message="message",r))(R||{});const Me=(r,e)=>{const t=[];let n=!1;return{destroy(o){n||(n=!0,e(`${r}: Destroying connection`),t.forEach(i=>{i(o)}))},onDestroy(o){n?o():t.push(o)}}},_e=r=>(...e)=>{r&&console.log("[Penpal]",...e)},G=({name:r,message:e,stack:t})=>({name:r,message:e,stack:t}),Ce=r=>{const e=new Error;return Object.keys(r).forEach(t=>e[t]=r[t]),e},Te=(r,e,t)=>{const{localName:n,local:o,remote:i,originForSending:s,originForReceiving:c}=r;let f=!1;const w=b=>{if(b.source!==i||b.data.penpal!==F.Call)return;if(c!=="*"&&b.origin!==c){t(`${n} received message from origin ${b.origin} which did not match expected origin ${c}`);return}const v=b.data,{methodName:g,args:p,id:m}=v;t(`${n}: Received ${g}() call`);const a=y=>S=>{if(t(`${n}: Sending ${g}() reply`),f){t(`${n}: Unable to send ${g}() reply due to destroyed connection`);return}const $={penpal:F.Reply,id:m,resolution:y,returnValue:S};y===j.Rejected&&S instanceof Error&&($.returnValue=G(S),$.returnValueIsError=!0);try{i.postMessage($,s)}catch(M){if(M.name===ae.DataCloneError){const _={penpal:F.Reply,id:m,resolution:j.Rejected,returnValue:G(M),returnValueIsError:!0};i.postMessage(_,s)}throw M}};new Promise(y=>y(e[g].apply(e,p))).then(a(j.Fulfilled),a(j.Rejected))};return o.addEventListener(R.Message,w),()=>{f=!0,o.removeEventListener(R.Message,w)}};let Fe=0;const Oe=()=>++Fe,le=".",ue=r=>r?r.split(le):[],Re=r=>r.join(le),xe=(r,e)=>{const t=ue(e||"");return t.push(r),Re(t)},De=(r,e,t)=>{const n=ue(e);return n.reduce((o,i,s)=>(typeof o[i]>"u"&&(o[i]={}),s===n.length-1&&(o[i]=t),o[i]),r),r},fe=(r,e)=>{const t={};return Object.keys(r).forEach(n=>{const o=r[n],i=xe(n,e);typeof o=="object"&&Object.assign(t,fe(o,i)),typeof o=="function"&&(t[i]=o)}),t},Ie=r=>{const e={};for(const t in r)De(e,t,r[t]);return e},je=(r,e,t,n,o)=>{const{localName:i,local:s,remote:c,originForSending:f,originForReceiving:w}=e;let b=!1;o(`${i}: Connecting call sender`);const v=p=>(...m)=>{o(`${i}: Sending ${p}() call`);let a;try{c.closed&&(a=!0)}catch{a=!0}if(a&&n(),b){const y=new Error(`Unable to send ${p}() call due to destroyed connection`);throw y.code=z.ConnectionDestroyed,y}return new Promise((y,S)=>{const $=Oe(),M=C=>{if(C.source!==c||C.data.penpal!==F.Reply||C.data.id!==$)return;if(w!=="*"&&C.origin!==w){o(`${i} received message from origin ${C.origin} which did not match expected origin ${w}`);return}const k=C.data;o(`${i}: Received ${p}() reply`),s.removeEventListener(R.Message,M);let V=k.returnValue;k.returnValueIsError&&(V=Ce(V)),(k.resolution===j.Fulfilled?y:S)(V)};s.addEventListener(R.Message,M);const _={penpal:F.Call,id:$,methodName:p,args:m};c.postMessage(_,f)})},g=t.reduce((p,m)=>(p[m]=v(m),p),{});return Object.assign(r,Ie(g)),()=>{b=!0}},ke=(r,e)=>{let t;return r!==void 0&&(t=window.setTimeout(()=>{const n=new Error(`Connection timed out after ${r}ms`);n.code=z.ConnectionTimeout,e(n)},r)),()=>{clearTimeout(t)}},Ve="@fn/micro-app-postmate",qe="0.1.2",We="module",Ne="src/index.ts",Le={dev:"vite",build:"tsc -b && vite build",lint:"eslint ."},He=["src","dist"],Ue={"@fn/micro-app-event":"^0.0.1",rxjs:"^7.8.0"},Be={"@eslint/js":"^9.13.0","@fn/micro-app-event":"workspace:*",eslint:"^9.13.0",globals:"^15.11.0",typescript:"~5.6.2","typescript-eslint":"^8.11.0",rxjs:"^7.8.0",vite:"^5.4.10"},Je={registry:"http://verdaccio.teiron-inc.cn:4873"},Ye={name:Ve,version:qe,type:We,main:Ne,scripts:Le,files:He,peerDependencies:Ue,devDependencies:Be,publishConfig:Je},ze=(r,e,t,n,o)=>{const{destroy:i,onDestroy:s}=n;return c=>{if(!(r instanceof RegExp?r.test(c.origin):r==="*"||r===c.origin)){o(`Child: Handshake - Received SYN-ACK from origin ${c.origin} which did not match expected origin ${r}`);return}o("Child: Handshake - Received SYN-ACK, responding with ACK");const w=c.origin==="null"?"*":c.origin,b={penpal:F.Ack,methodNames:Object.keys(e),config:t};window.parent.postMessage(b,w);const v={localName:"Child",local:window,remote:window.parent,originForSending:w,originForReceiving:c.origin},g=Te(v,e,o);s(g);const p={},m=je(p,v,c.data.methodNames,i,o);return s(m),p}};function X(r,e){console==null||console.warn(`[fnApp warn]: ${r}`,e)}function Z(r,e){console==null||console.error(`[fnApp error]: ${r}`,e)}const I="_fn_all_event",ee="事件订阅数量为空",q=window.__POWERED_BY_FNAPP__?window.__FNAPP.inject.appEventObjMap:new Map;class te{constructor(e,t){A(this,"id");A(this,"appName");A(this,"eventObj");A(this,"getEventCallBackLength",e=>{var t;return((t=this.eventObj[e])==null?void 0:t.length)||0});console.log("id",e,t),this.id=e,this.appName=t,this.$clear(),q.get(this.id)||q.set(this.id,{}),this.eventObj=q.get(this.id)}$on(e,t){const n=this.eventObj[e];return n?(n.includes(t)||n.push(t),this):(this.eventObj[e]=[t],this)}$onAll(e){return this.$on(I,e)}$once(e,t){t.$__once=!0,this.$on(e,t)}$off(e,t){const n=this.eventObj[e];if(!e||!n||!n.length)return X(`${e} ${ee}`),this;let o,i=n.length;for(;i--;)if(o=n[i],o===t){n.splice(i,1);break}return this}$offAll(e){return this.$off(I,e)}$emit(e,...t){return e=`${this.appName}/${e}`,this.$pureEmit(e,...t)}$pureEmit(e,...t){let n=0,o=0;return q.forEach(i=>{if(i[e])for(let s=i[e].length-1;s>=0;s--){n++;const c=i[e][s];c.$__once&&i[e].splice(s,1);try{c(...t)}catch(f){Z(f)}}if(i[I])for(let s=i[I].length-1;s>=0;s--){n++;const c=i[I][s];c.$__once&&i[I].splice(s,1);try{c(...t)}catch(f){Z(f)}}}),(!e||n===0&&o===0)&&X(`${e} ${ee}`),this}$clear(){const e=q.get(this.id)??{};return Object.keys(e).forEach(n=>delete e[n]),this}}var U=function(r,e){return U=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])},U(r,e)};function pe(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");U(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function re(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function B(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(c){s={error:c}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return i}function J(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))}function O(r){return typeof r=="function"}function Ke(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var L=Ke(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
2
2
|
`+t.map(function(n,o){return o+1+") "+n.toString()}).join(`
|
|
3
3
|
`):"",this.name="UnsubscriptionError",this.errors=t}});function ne(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var K=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=re(s),f=c.next();!f.done;f=c.next()){var w=f.value;w.remove(this)}}catch(a){e={error:a}}finally{try{f&&!f.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else s.remove(this);var b=this.initialTeardown;if(O(b))try{b()}catch(a){i=a instanceof L?a.errors:[a]}var v=this._finalizers;if(v){this._finalizers=null;try{for(var g=re(v),p=g.next();!p.done;p=g.next()){var m=p.value;try{ie(m)}catch(a){i=i??[],a instanceof L?i=J(J([],B(i)),B(a.errors)):i.push(a)}}}catch(a){n={error:a}}finally{try{p&&!p.done&&(o=g.return)&&o.call(g)}finally{if(n)throw n.error}}}if(i)throw new L(i)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)ie(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ne(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ne(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}();K.EMPTY;function de(r){return r instanceof K||r&&"closed"in r&&O(r.remove)&&O(r.add)&&O(r.unsubscribe)}function ie(r){O(r)?r():r.unsubscribe()}var he={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Qe={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,J([r,e],B(t)))},clearTimeout:function(r){return clearTimeout(r)},delegate:void 0};function Ge(r){Qe.setTimeout(function(){throw r})}function oe(){}function Xe(r){r()}var ge=function(r){pe(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,de(t)&&t.add(n)):n.destination=rt,n}return e.create=function(t,n,o){return new Y(t,n,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(K),Ze=Function.prototype.bind;function H(r,e){return Ze.call(r,e)}var et=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){N(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){N(n)}else N(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){N(t)}},r}(),Y=function(r){pe(e,r);function e(t,n,o){var i=r.call(this)||this,s;if(O(t)||!t)s={next:t??void 0,error:n??void 0,complete:o??void 0};else{var c;i&&he.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return i.unsubscribe()},s={next:t.next&&H(t.next,c),error:t.error&&H(t.error,c),complete:t.complete&&H(t.complete,c)}):s=t}return i.destination=new et(s),i}return e}(ge);function N(r){Ge(r)}function tt(r){throw r}var rt={closed:!0,next:oe,error:tt,complete:oe},nt=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function it(r){return r}function ot(r){return r.length===0?it:r.length===1?r[0]:function(t){return r.reduce(function(n,o){return o(n)},t)}}var st=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var o=this,i=at(e)?e:new Y(e,t,n);return Xe(function(){var s=o,c=s.operator,f=s.source;i.add(c?c.call(i,f):f?o._subscribe(i):o._trySubscribe(i))}),i},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=se(t),new t(function(o,i){var s=new Y({next:function(c){try{e(c)}catch(f){i(f),s.unsubscribe()}},error:i,complete:o});n.subscribe(s)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[nt]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ot(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=se(e),new e(function(n,o){var i;t.subscribe(function(s){return i=s},function(s){return o(s)},function(){return n(i)})})},r.create=function(e){return new r(e)},r}();function se(r){var e;return(e=r??he.Promise)!==null&&e!==void 0?e:Promise}function ct(r){return r&&O(r.next)&&O(r.error)&&O(r.complete)}function at(r){return r&&r instanceof ge||ct(r)&&de(r)}const lt=()=>{try{clearTimeout(void 0)}catch{return!1}return!0},ut=(r={})=>{const{parentOrigin:e="*",timeout:t,debug:n=!1,config:o={}}=r,i=_e(n),s=Me("App",i),{destroy:c,onDestroy:f}=s,w=()=>{i("Child: Handshake - Sending SYN");const v={penpal:F.Syn},g=e instanceof RegExp?"*":e;window.parent.postMessage(v,g)};return{promise:new Promise((v,g)=>{const p=ke(t,c),m=a=>{if(lt()&&!(a.source!==parent||!a.data)&&a.data.penpal===F.SynAck){const y=a.data,S=new te(y.id,y.appName),$=new te(y.id+"/api",y.appName),M=y.id,_={},C=l=>"api/"+l,k={$emit:(l,...u)=>{S.getEventCallBackLength(l)>0?S.$pureEmit(l,...u):_==null||_.$off(l,()=>{},!0)},onQueryResult:l=>{$.$pureEmit(C(l.reqid),l)},onOsNotify:l=>{}},V=l=>function(h){const P=C(l);$.$on(P,function D(E){h.next(E),E.reqid&&E.result==="succ"&&(h.complete(),$.$off(P,D))})},me=fe(k),x=ze(e,me,{...o,postmateVersion:Ye.version},s,i)(a),T={},W=x.bus;if(W){const l=(u,h,P)=>{P?(h.$__once=!0,S.$once(u,h)):S.$on(u,h),T[u]?T[u].push(h):(T[u]=[h],W.$on(u,M))};Object.assign(_,W,{$on:l,$off:(u,h,P)=>{var D;if(T[u]){const E=T[u].indexOf(h);E>-1&&(T[u].splice(E,1),S.$off(u,h))}P&&delete T[u],(D=T[u])!=null&&D.length||(W.$off(u,M),delete T[u])},$once:(u,h)=>{l(u,h,!0)}})}const be={...x,bus:_,query:async(l,u)=>{const h=(l==null?void 0:l.reqid)||await x.genReqId();return new Promise((P,D)=>{x.query({...l,reqid:h},u).then(E=>{(E==null?void 0:E.result)==="succ"?P(E):D(E)})})},createObservableQuery:async(l,u={})=>{const h=(l==null?void 0:l.reqid)||await x.genReqId(),P=new st(V(h));return x.query({...l,reqid:h},{...u,observable:!0}),P}};x&&(window.removeEventListener(R.Message,m),p(),v({methods:be,config:a.data.config}))}};window.addEventListener(R.Message,m),w(),f(a=>{window.removeEventListener(R.Message,m),a&&g(a)})}),destroy(){c()}}},ft=r=>ut({debug:r==null?void 0:r.debug}).promise;class ye{constructor(e={}){A(this,"options");A(this,"flutterInAppWebView",null);A(this,"osConnector",null);A(this,"initPromise");A(this,"isWeb",!0);this.options=e,e.debug&&(d.setDebug(!0),d.log("Trim App initialized with debug mode")),d.log("Options:",e),this.initPromise=this.init()}async init(){return d.log("Starting initialization..."),new Promise(e=>{ce()?(this.isWeb=!1,d.log("Initializing mobile platform..."),Ae().then(t=>{this.flutterInAppWebView=t,d.log("Mobile platform initialized"),e()})):(this.isWeb=!0,d.log("Initializing web platform..."),ft().then(t=>{this.osConnector=t,d.log("Web platform initialized"),e()}))})}async callAppMethod(e,t){return this.flutterInAppWebView?$e(this.flutterInAppWebView,e,t):null}async ready(){return this.initPromise}getOptions(){return this.options}setOptions(e){this.options={...this.options,...e},e.debug!==void 0&&d.setDebug(e.debug),d.log("Options updated:",this.options)}async getPlatformConfig(){var e;if(await this.initPromise,this.isWeb){const t=await((e=this.osConnector)==null?void 0:e.methods.getPlatformConfig());if(!t)throw new Error("Failed to get platform config");return t}else{const t=await this.callAppMethod("getAppMessage");if(!t)throw new Error("Failed to get platform config");return{theme:t.nightMode,language:t.language,appVersion:t.appVersion,systemVersion:t.systemVersion,format:{date:t.dateFormat,time:t.timeFormat}}}}async setTitle(e){var t;return await this.initPromise,d.log("Setting title:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setTitle(e):this.callAppMethod("updateTitle",e)}async setExitPageTips(e){var t;return await this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setExitPageTips(e):this.callAppMethod("setExitPageTips",e?JSON.stringify(e):"")}async openFile(e){var t;return await this.initPromise,d.log("Opening file:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFile(e):this.callAppMethod("openFile",e)}async openFileManager(e){var t;return await this.initPromise,d.log("Opening file manager:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFileManagerApp(e):this.callAppMethod("openFileManager",e)}async close(){var e;if(await this.initPromise,this.isWeb)return(e=this.osConnector)==null?void 0:e.methods.close();throw new Error("close is not supported on mobile platform")}async query(e,t){var n;if(await this.initPromise,this.isWeb){const o=await((n=this.osConnector)==null?void 0:n.methods.query(e,t));if(!o)throw new Error("Failed to query");return o}else throw new Error("query is not supported on mobile platform")}async pickFile(e){var t;return await this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.pickFile(e):this.callAppMethod("openFolder",JSON.stringify(e))}}exports.TrimApp=ye;exports.default=ye;
|
|
4
|
-
//# sourceMappingURL=index.cjs.map
|
package/dist/index.iife.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
1
|
var TrimApp=function($){"use strict";var nt=Object.defineProperty;var rt=($,_,l)=>_ in $?nt($,_,{enumerable:!0,configurable:!0,writable:!0,value:l}):$[_]=l;var A=($,_,l)=>rt($,typeof _!="symbol"?_+"":_,l);class _{constructor(){A(this,"debug",!1)}setDebug(e){this.debug=e}isDebug(){return this.debug}log(...e){this.debug&&console.log("[Trim App]",...e)}warn(...e){this.debug&&console.warn("[Trim App]",...e)}error(...e){this.debug&&console.error("[Trim App]",...e)}info(...e){this.debug&&console.info("[Trim App]",...e)}}const l=new _;function we(n){const e=/FNOS\/([\d.]+)|FNAppType\/(\w+)|FNAppVer\/([\d.]+)/g,t={};let r;for(;(r=e.exec(n))!==null;)r[1]&&(t.fnOSVersion=r[1]),r[2]&&(t.fnAppType=r[2]),r[3]&&(t.fnAppVersion=r[3]);return t}const X=()=>we(navigator.userAgent).fnAppVersion,ve=()=>new Promise(n=>{var e;(e=window.flutter_inappwebview)!=null&&e._platformReady?(l.log("flutter_inappwebview is ready"),n(window.flutter_inappwebview)):window.addEventListener("flutterInAppWebViewPlatformReady",()=>{l.log("flutter_inappwebview is ready"),n(window.flutter_inappwebview)})}),Ee=async(n,e,t)=>{l.log(`callHandler: ${e}, params: ${t}`);const r=await n.callHandler(e,t);if(r)try{const o=JSON.parse(r);l.log(`messageData: ${JSON.stringify(o)}`);const i=JSON.parse(o.result);return l.log(`appMessage: ${JSON.stringify(i)}`),i}catch(o){return l.error(`error: ${o}`),null}return null},Z=new Map;function Se(){window.fnAppMessage=n=>{l.log("app-message",n);const e=JSON.parse(n),t=Z.get(e.reqId);t&&(t(e),Z.delete(e.reqId))}}X()&&Se();var C=(n=>(n.Call="call",n.Reply="reply",n.Syn="syn",n.SynAck="synAck",n.Ack="ack",n))(C||{}),j=(n=>(n.Fulfilled="fulfilled",n.Rejected="rejected",n))(j||{}),U=(n=>(n.ConnectionDestroyed="ConnectionDestroyed",n.ConnectionTimeout="ConnectionTimeout",n.NoIframeSrc="NoIframeSrc",n))(U||{}),ee=(n=>(n.DataCloneError="DataCloneError",n))(ee||{}),x=(n=>(n.Message="message",n))(x||{});const Ae=(n,e)=>{const t=[];let r=!1;return{destroy(o){r||(r=!0,e(`${n}: Destroying connection`),t.forEach(i=>{i(o)}))},onDestroy(o){r?o():t.push(o)}}},$e=n=>(...e)=>{n&&console.log("[Penpal]",...e)},te=({name:n,message:e,stack:t})=>({name:n,message:e,stack:t}),Pe=n=>{const e=new Error;return Object.keys(n).forEach(t=>e[t]=n[t]),e},Me=(n,e,t)=>{const{localName:r,local:o,remote:i,originForSending:s,originForReceiving:c}=n;let p=!1;const w=b=>{if(b.source!==i||b.data.penpal!==C.Call)return;if(c!=="*"&&b.origin!==c){t(`${r} received message from origin ${b.origin} which did not match expected origin ${c}`);return}const v=b.data,{methodName:g,args:d,id:m}=v;t(`${r}: Received ${g}() call`);const a=y=>S=>{if(t(`${r}: Sending ${g}() reply`),p){t(`${r}: Unable to send ${g}() reply due to destroyed connection`);return}const P={penpal:C.Reply,id:m,resolution:y,returnValue:S};y===j.Rejected&&S instanceof Error&&(P.returnValue=te(S),P.returnValueIsError=!0);try{i.postMessage(P,s)}catch(F){if(F.name===ee.DataCloneError){const O={penpal:C.Reply,id:m,resolution:j.Rejected,returnValue:te(F),returnValueIsError:!0};i.postMessage(O,s)}throw F}};new Promise(y=>y(e[g].apply(e,d))).then(a(j.Fulfilled),a(j.Rejected))};return o.addEventListener(x.Message,w),()=>{p=!0,o.removeEventListener(x.Message,w)}};let _e=0;const Ce=()=>++_e,ne=".",re=n=>n?n.split(ne):[],Te=n=>n.join(ne),Fe=(n,e)=>{const t=re(e||"");return t.push(n),Te(t)},Oe=(n,e,t)=>{const r=re(e);return r.reduce((o,i,s)=>(typeof o[i]>"u"&&(o[i]={}),s===r.length-1&&(o[i]=t),o[i]),n),n},ie=(n,e)=>{const t={};return Object.keys(n).forEach(r=>{const o=n[r],i=Fe(r,e);typeof o=="object"&&Object.assign(t,ie(o,i)),typeof o=="function"&&(t[i]=o)}),t},Re=n=>{const e={};for(const t in n)Oe(e,t,n[t]);return e},De=(n,e,t,r,o)=>{const{localName:i,local:s,remote:c,originForSending:p,originForReceiving:w}=e;let b=!1;o(`${i}: Connecting call sender`);const v=d=>(...m)=>{o(`${i}: Sending ${d}() call`);let a;try{c.closed&&(a=!0)}catch{a=!0}if(a&&r(),b){const y=new Error(`Unable to send ${d}() call due to destroyed connection`);throw y.code=U.ConnectionDestroyed,y}return new Promise((y,S)=>{const P=Ce(),F=R=>{if(R.source!==c||R.data.penpal!==C.Reply||R.data.id!==P)return;if(w!=="*"&&R.origin!==w){o(`${i} received message from origin ${R.origin} which did not match expected origin ${w}`);return}const W=R.data;o(`${i}: Received ${d}() reply`),s.removeEventListener(x.Message,F);let N=W.returnValue;W.returnValueIsError&&(N=Pe(N)),(W.resolution===j.Fulfilled?y:S)(N)};s.addEventListener(x.Message,F);const O={penpal:C.Call,id:P,methodName:d,args:m};c.postMessage(O,p)})},g=t.reduce((d,m)=>(d[m]=v(m),d),{});return Object.assign(n,Re(g)),()=>{b=!0}},xe=(n,e)=>{let t;return n!==void 0&&(t=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${n}ms`);r.code=U.ConnectionTimeout,e(r)},n)),()=>{clearTimeout(t)}},Ie={name:"@fn/micro-app-postmate",version:"0.1.2",type:"module",main:"src/index.ts",scripts:{dev:"vite",build:"tsc -b && vite build",lint:"eslint ."},files:["src","dist"],peerDependencies:{"@fn/micro-app-event":"^0.0.1",rxjs:"^7.8.0"},devDependencies:{"@eslint/js":"^9.13.0","@fn/micro-app-event":"workspace:*",eslint:"^9.13.0",globals:"^15.11.0",typescript:"~5.6.2","typescript-eslint":"^8.11.0",rxjs:"^7.8.0",vite:"^5.4.10"},publishConfig:{registry:"http://verdaccio.teiron-inc.cn:4873"}},je=(n,e,t,r,o)=>{const{destroy:i,onDestroy:s}=r;return c=>{if(!(n instanceof RegExp?n.test(c.origin):n==="*"||n===c.origin)){o(`Child: Handshake - Received SYN-ACK from origin ${c.origin} which did not match expected origin ${n}`);return}o("Child: Handshake - Received SYN-ACK, responding with ACK");const w=c.origin==="null"?"*":c.origin,b={penpal:C.Ack,methodNames:Object.keys(e),config:t};window.parent.postMessage(b,w);const v={localName:"Child",local:window,remote:window.parent,originForSending:w,originForReceiving:c.origin},g=Me(v,e,o);s(g);const d={},m=De(d,v,c.data.methodNames,i,o);return s(m),d}};function oe(n,e){console==null||console.warn(`[fnApp warn]: ${n}`,e)}function se(n,e){console==null||console.error(`[fnApp error]: ${n}`,e)}const k="_fn_all_event",ce="事件订阅数量为空",q=window.__POWERED_BY_FNAPP__?window.__FNAPP.inject.appEventObjMap:new Map;class ae{constructor(e,t){A(this,"id");A(this,"appName");A(this,"eventObj");A(this,"getEventCallBackLength",e=>{var t;return((t=this.eventObj[e])==null?void 0:t.length)||0});console.log("id",e,t),this.id=e,this.appName=t,this.$clear(),q.get(this.id)||q.set(this.id,{}),this.eventObj=q.get(this.id)}$on(e,t){const r=this.eventObj[e];return r?(r.includes(t)||r.push(t),this):(this.eventObj[e]=[t],this)}$onAll(e){return this.$on(k,e)}$once(e,t){t.$__once=!0,this.$on(e,t)}$off(e,t){const r=this.eventObj[e];if(!e||!r||!r.length)return oe(`${e} ${ce}`),this;let o,i=r.length;for(;i--;)if(o=r[i],o===t){r.splice(i,1);break}return this}$offAll(e){return this.$off(k,e)}$emit(e,...t){return e=`${this.appName}/${e}`,this.$pureEmit(e,...t)}$pureEmit(e,...t){let r=0,o=0;return q.forEach(i=>{if(i[e])for(let s=i[e].length-1;s>=0;s--){r++;const c=i[e][s];c.$__once&&i[e].splice(s,1);try{c(...t)}catch(p){se(p)}}if(i[k])for(let s=i[k].length-1;s>=0;s--){r++;const c=i[k][s];c.$__once&&i[k].splice(s,1);try{c(...t)}catch(p){se(p)}}}),(!e||r===0&&o===0)&&oe(`${e} ${ce}`),this}$clear(){const e=q.get(this.id)??{};return Object.keys(e).forEach(r=>delete e[r]),this}}var B=function(n,e){return B=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])},B(n,e)};function le(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");B(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function ue(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function J(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(c){s={error:c}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(s)throw s.error}}return i}function Y(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return n.concat(i||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;function T(n){return typeof n=="function"}function ke(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var z=ke(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
2
2
|
`+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
|
|
3
3
|
`):"",this.name="UnsubscriptionError",this.errors=t}});function fe(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var K=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=ue(s),p=c.next();!p.done;p=c.next()){var w=p.value;w.remove(this)}}catch(a){e={error:a}}finally{try{p&&!p.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else s.remove(this);var b=this.initialTeardown;if(T(b))try{b()}catch(a){i=a instanceof z?a.errors:[a]}var v=this._finalizers;if(v){this._finalizers=null;try{for(var g=ue(v),d=g.next();!d.done;d=g.next()){var m=d.value;try{de(m)}catch(a){i=i??[],a instanceof z?i=Y(Y([],J(i)),J(a.errors)):i.push(a)}}}catch(a){r={error:a}}finally{try{d&&!d.done&&(o=g.return)&&o.call(g)}finally{if(r)throw r.error}}}if(i)throw new z(i)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)de(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&fe(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&fe(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}();K.EMPTY;function pe(n){return n instanceof K||n&&"closed"in n&&T(n.remove)&&T(n.add)&&T(n.unsubscribe)}function de(n){T(n)?n():n.unsubscribe()}var he={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Ve={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,Y([n,e],J(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function qe(n){Ve.setTimeout(function(){throw n})}function ge(){}function We(n){n()}var ye=function(n){le(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,pe(t)&&t.add(r)):r.destination=Ue,r}return e.create=function(t,r,o){return new G(t,r,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(K),Ne=Function.prototype.bind;function Q(n,e){return Ne.call(n,e)}var Le=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){L(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){L(r)}else L(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){L(t)}},n}(),G=function(n){le(e,n);function e(t,r,o){var i=n.call(this)||this,s;if(T(t)||!t)s={next:t??void 0,error:r??void 0,complete:o??void 0};else{var c;i&&he.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return i.unsubscribe()},s={next:t.next&&Q(t.next,c),error:t.error&&Q(t.error,c),complete:t.complete&&Q(t.complete,c)}):s=t}return i.destination=new Le(s),i}return e}(ye);function L(n){qe(n)}function He(n){throw n}var Ue={closed:!0,next:ge,error:He,complete:ge},Be=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Je(n){return n}function Ye(n){return n.length===0?Je:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var ze=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,i=Qe(e)?e:new G(e,t,r);return We(function(){var s=o,c=s.operator,p=s.source;i.add(c?c.call(i,p):p?o._subscribe(i):o._trySubscribe(i))}),i},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=me(t),new t(function(o,i){var s=new G({next:function(c){try{e(c)}catch(p){i(p),s.unsubscribe()}},error:i,complete:o});r.subscribe(s)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Be]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ye(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=me(e),new e(function(r,o){var i;t.subscribe(function(s){return i=s},function(s){return o(s)},function(){return r(i)})})},n.create=function(e){return new n(e)},n}();function me(n){var e;return(e=n??he.Promise)!==null&&e!==void 0?e:Promise}function Ke(n){return n&&T(n.next)&&T(n.error)&&T(n.complete)}function Qe(n){return n&&n instanceof ye||Ke(n)&&pe(n)}const Ge=()=>{try{clearTimeout(void 0)}catch{return!1}return!0},Xe=(n={})=>{const{parentOrigin:e="*",timeout:t,debug:r=!1,config:o={}}=n,i=$e(r),s=Ae("App",i),{destroy:c,onDestroy:p}=s,w=()=>{i("Child: Handshake - Sending SYN");const v={penpal:C.Syn},g=e instanceof RegExp?"*":e;window.parent.postMessage(v,g)};return{promise:new Promise((v,g)=>{const d=xe(t,c),m=a=>{if(Ge()&&!(a.source!==parent||!a.data)&&a.data.penpal===C.SynAck){const y=a.data,S=new ae(y.id,y.appName),P=new ae(y.id+"/api",y.appName),F=y.id,O={},R=u=>"api/"+u,W={$emit:(u,...f)=>{S.getEventCallBackLength(u)>0?S.$pureEmit(u,...f):O==null||O.$off(u,()=>{},!0)},onQueryResult:u=>{P.$pureEmit(R(u.reqid),u)},onOsNotify:u=>{}},N=u=>function(h){const M=R(u);P.$on(M,function V(E){h.next(E),E.reqid&&E.result==="succ"&&(h.complete(),P.$off(M,V))})},et=ie(W),I=je(e,et,{...o,postmateVersion:Ie.version},s,i)(a),D={},H=I.bus;if(H){const u=(f,h,M)=>{M?(h.$__once=!0,S.$once(f,h)):S.$on(f,h),D[f]?D[f].push(h):(D[f]=[h],H.$on(f,F))};Object.assign(O,H,{$on:u,$off:(f,h,M)=>{var V;if(D[f]){const E=D[f].indexOf(h);E>-1&&(D[f].splice(E,1),S.$off(f,h))}M&&delete D[f],(V=D[f])!=null&&V.length||(H.$off(f,F),delete D[f])},$once:(f,h)=>{u(f,h,!0)}})}const tt={...I,bus:O,query:async(u,f)=>{const h=(u==null?void 0:u.reqid)||await I.genReqId();return new Promise((M,V)=>{I.query({...u,reqid:h},f).then(E=>{(E==null?void 0:E.result)==="succ"?M(E):V(E)})})},createObservableQuery:async(u,f={})=>{const h=(u==null?void 0:u.reqid)||await I.genReqId(),M=new ze(N(h));return I.query({...u,reqid:h},{...f,observable:!0}),M}};I&&(window.removeEventListener(x.Message,m),d(),v({methods:tt,config:a.data.config}))}};window.addEventListener(x.Message,m),w(),p(a=>{window.removeEventListener(x.Message,m),a&&g(a)})}),destroy(){c()}}},Ze=n=>Xe({debug:n==null?void 0:n.debug}).promise;class be{constructor(e={}){A(this,"options");A(this,"flutterInAppWebView",null);A(this,"osConnector",null);A(this,"initPromise");A(this,"isWeb",!0);this.options=e,e.debug&&(l.setDebug(!0),l.log("Trim App initialized with debug mode")),l.log("Options:",e),this.initPromise=this.init()}async init(){return l.log("Starting initialization..."),new Promise(e=>{X()?(this.isWeb=!1,l.log("Initializing mobile platform..."),ve().then(t=>{this.flutterInAppWebView=t,l.log("Mobile platform initialized"),e()})):(this.isWeb=!0,l.log("Initializing web platform..."),Ze().then(t=>{this.osConnector=t,l.log("Web platform initialized"),e()}))})}async callAppMethod(e,t){return this.flutterInAppWebView?Ee(this.flutterInAppWebView,e,t):null}async ready(){return this.initPromise}getOptions(){return this.options}setOptions(e){this.options={...this.options,...e},e.debug!==void 0&&l.setDebug(e.debug),l.log("Options updated:",this.options)}async getPlatformConfig(){var e;if(await this.initPromise,this.isWeb){const t=await((e=this.osConnector)==null?void 0:e.methods.getPlatformConfig());if(!t)throw new Error("Failed to get platform config");return t}else{const t=await this.callAppMethod("getAppMessage");if(!t)throw new Error("Failed to get platform config");return{theme:t.nightMode,language:t.language,appVersion:t.appVersion,systemVersion:t.systemVersion,format:{date:t.dateFormat,time:t.timeFormat}}}}async setTitle(e){var t;return await this.initPromise,l.log("Setting title:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setTitle(e):this.callAppMethod("updateTitle",e)}async setExitPageTips(e){var t;return await this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setExitPageTips(e):this.callAppMethod("setExitPageTips",e?JSON.stringify(e):"")}async openFile(e){var t;return await this.initPromise,l.log("Opening file:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFile(e):this.callAppMethod("openFile",e)}async openFileManager(e){var t;return await this.initPromise,l.log("Opening file manager:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFileManagerApp(e):this.callAppMethod("openFileManager",e)}async close(){var e;if(await this.initPromise,this.isWeb)return(e=this.osConnector)==null?void 0:e.methods.close();throw new Error("close is not supported on mobile platform")}async query(e,t){var r;if(await this.initPromise,this.isWeb){const o=await((r=this.osConnector)==null?void 0:r.methods.query(e,t));if(!o)throw new Error("Failed to query");return o}else throw new Error("query is not supported on mobile platform")}async pickFile(e){var t;return await this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.pickFile(e):this.callAppMethod("openFolder",JSON.stringify(e))}}return $.TrimApp=be,$.default=be,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),$}({});
|
|
4
|
-
//# sourceMappingURL=index.iife.js.map
|
package/dist/index.js
CHANGED
package/dist/index.umd.cjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
1
|
(function(w,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(w=typeof globalThis<"u"?globalThis:w||self,v(w.TrimApp={}))})(this,function(w){"use strict";var nt=Object.defineProperty;var rt=(w,v,l)=>v in w?nt(w,v,{enumerable:!0,configurable:!0,writable:!0,value:l}):w[v]=l;var P=(w,v,l)=>rt(w,typeof v!="symbol"?v+"":v,l);class v{constructor(){P(this,"debug",!1)}setDebug(e){this.debug=e}isDebug(){return this.debug}log(...e){this.debug&&console.log("[Trim App]",...e)}warn(...e){this.debug&&console.warn("[Trim App]",...e)}error(...e){this.debug&&console.error("[Trim App]",...e)}info(...e){this.debug&&console.info("[Trim App]",...e)}}const l=new v;function we(n){const e=/FNOS\/([\d.]+)|FNAppType\/(\w+)|FNAppVer\/([\d.]+)/g,t={};let r;for(;(r=e.exec(n))!==null;)r[1]&&(t.fnOSVersion=r[1]),r[2]&&(t.fnAppType=r[2]),r[3]&&(t.fnAppVersion=r[3]);return t}const X=()=>we(navigator.userAgent).fnAppVersion,ve=()=>new Promise(n=>{var e;(e=window.flutter_inappwebview)!=null&&e._platformReady?(l.log("flutter_inappwebview is ready"),n(window.flutter_inappwebview)):window.addEventListener("flutterInAppWebViewPlatformReady",()=>{l.log("flutter_inappwebview is ready"),n(window.flutter_inappwebview)})}),Ee=async(n,e,t)=>{l.log(`callHandler: ${e}, params: ${t}`);const r=await n.callHandler(e,t);if(r)try{const o=JSON.parse(r);l.log(`messageData: ${JSON.stringify(o)}`);const i=JSON.parse(o.result);return l.log(`appMessage: ${JSON.stringify(i)}`),i}catch(o){return l.error(`error: ${o}`),null}return null},Z=new Map;function Se(){window.fnAppMessage=n=>{l.log("app-message",n);const e=JSON.parse(n),t=Z.get(e.reqId);t&&(t(e),Z.delete(e.reqId))}}X()&&Se();var C=(n=>(n.Call="call",n.Reply="reply",n.Syn="syn",n.SynAck="synAck",n.Ack="ack",n))(C||{}),I=(n=>(n.Fulfilled="fulfilled",n.Rejected="rejected",n))(I||{}),U=(n=>(n.ConnectionDestroyed="ConnectionDestroyed",n.ConnectionTimeout="ConnectionTimeout",n.NoIframeSrc="NoIframeSrc",n))(U||{}),ee=(n=>(n.DataCloneError="DataCloneError",n))(ee||{}),D=(n=>(n.Message="message",n))(D||{});const Ae=(n,e)=>{const t=[];let r=!1;return{destroy(o){r||(r=!0,e(`${n}: Destroying connection`),t.forEach(i=>{i(o)}))},onDestroy(o){r?o():t.push(o)}}},$e=n=>(...e)=>{n&&console.log("[Penpal]",...e)},te=({name:n,message:e,stack:t})=>({name:n,message:e,stack:t}),Pe=n=>{const e=new Error;return Object.keys(n).forEach(t=>e[t]=n[t]),e},Me=(n,e,t)=>{const{localName:r,local:o,remote:i,originForSending:s,originForReceiving:c}=n;let p=!1;const E=b=>{if(b.source!==i||b.data.penpal!==C.Call)return;if(c!=="*"&&b.origin!==c){t(`${r} received message from origin ${b.origin} which did not match expected origin ${c}`);return}const S=b.data,{methodName:g,args:d,id:m}=S;t(`${r}: Received ${g}() call`);const a=y=>$=>{if(t(`${r}: Sending ${g}() reply`),p){t(`${r}: Unable to send ${g}() reply due to destroyed connection`);return}const M={penpal:C.Reply,id:m,resolution:y,returnValue:$};y===I.Rejected&&$ instanceof Error&&(M.returnValue=te($),M.returnValueIsError=!0);try{i.postMessage(M,s)}catch(F){if(F.name===ee.DataCloneError){const O={penpal:C.Reply,id:m,resolution:I.Rejected,returnValue:te(F),returnValueIsError:!0};i.postMessage(O,s)}throw F}};new Promise(y=>y(e[g].apply(e,d))).then(a(I.Fulfilled),a(I.Rejected))};return o.addEventListener(D.Message,E),()=>{p=!0,o.removeEventListener(D.Message,E)}};let _e=0;const Ce=()=>++_e,ne=".",re=n=>n?n.split(ne):[],Te=n=>n.join(ne),Fe=(n,e)=>{const t=re(e||"");return t.push(n),Te(t)},Oe=(n,e,t)=>{const r=re(e);return r.reduce((o,i,s)=>(typeof o[i]>"u"&&(o[i]={}),s===r.length-1&&(o[i]=t),o[i]),n),n},ie=(n,e)=>{const t={};return Object.keys(n).forEach(r=>{const o=n[r],i=Fe(r,e);typeof o=="object"&&Object.assign(t,ie(o,i)),typeof o=="function"&&(t[i]=o)}),t},Re=n=>{const e={};for(const t in n)Oe(e,t,n[t]);return e},xe=(n,e,t,r,o)=>{const{localName:i,local:s,remote:c,originForSending:p,originForReceiving:E}=e;let b=!1;o(`${i}: Connecting call sender`);const S=d=>(...m)=>{o(`${i}: Sending ${d}() call`);let a;try{c.closed&&(a=!0)}catch{a=!0}if(a&&r(),b){const y=new Error(`Unable to send ${d}() call due to destroyed connection`);throw y.code=U.ConnectionDestroyed,y}return new Promise((y,$)=>{const M=Ce(),F=R=>{if(R.source!==c||R.data.penpal!==C.Reply||R.data.id!==M)return;if(E!=="*"&&R.origin!==E){o(`${i} received message from origin ${R.origin} which did not match expected origin ${E}`);return}const W=R.data;o(`${i}: Received ${d}() reply`),s.removeEventListener(D.Message,F);let N=W.returnValue;W.returnValueIsError&&(N=Pe(N)),(W.resolution===I.Fulfilled?y:$)(N)};s.addEventListener(D.Message,F);const O={penpal:C.Call,id:M,methodName:d,args:m};c.postMessage(O,p)})},g=t.reduce((d,m)=>(d[m]=S(m),d),{});return Object.assign(n,Re(g)),()=>{b=!0}},De=(n,e)=>{let t;return n!==void 0&&(t=window.setTimeout(()=>{const r=new Error(`Connection timed out after ${n}ms`);r.code=U.ConnectionTimeout,e(r)},n)),()=>{clearTimeout(t)}},je={name:"@fn/micro-app-postmate",version:"0.1.2",type:"module",main:"src/index.ts",scripts:{dev:"vite",build:"tsc -b && vite build",lint:"eslint ."},files:["src","dist"],peerDependencies:{"@fn/micro-app-event":"^0.0.1",rxjs:"^7.8.0"},devDependencies:{"@eslint/js":"^9.13.0","@fn/micro-app-event":"workspace:*",eslint:"^9.13.0",globals:"^15.11.0",typescript:"~5.6.2","typescript-eslint":"^8.11.0",rxjs:"^7.8.0",vite:"^5.4.10"},publishConfig:{registry:"http://verdaccio.teiron-inc.cn:4873"}},Ie=(n,e,t,r,o)=>{const{destroy:i,onDestroy:s}=r;return c=>{if(!(n instanceof RegExp?n.test(c.origin):n==="*"||n===c.origin)){o(`Child: Handshake - Received SYN-ACK from origin ${c.origin} which did not match expected origin ${n}`);return}o("Child: Handshake - Received SYN-ACK, responding with ACK");const E=c.origin==="null"?"*":c.origin,b={penpal:C.Ack,methodNames:Object.keys(e),config:t};window.parent.postMessage(b,E);const S={localName:"Child",local:window,remote:window.parent,originForSending:E,originForReceiving:c.origin},g=Me(S,e,o);s(g);const d={},m=xe(d,S,c.data.methodNames,i,o);return s(m),d}};function oe(n,e){console==null||console.warn(`[fnApp warn]: ${n}`,e)}function se(n,e){console==null||console.error(`[fnApp error]: ${n}`,e)}const k="_fn_all_event",ce="事件订阅数量为空",q=window.__POWERED_BY_FNAPP__?window.__FNAPP.inject.appEventObjMap:new Map;class ae{constructor(e,t){P(this,"id");P(this,"appName");P(this,"eventObj");P(this,"getEventCallBackLength",e=>{var t;return((t=this.eventObj[e])==null?void 0:t.length)||0});console.log("id",e,t),this.id=e,this.appName=t,this.$clear(),q.get(this.id)||q.set(this.id,{}),this.eventObj=q.get(this.id)}$on(e,t){const r=this.eventObj[e];return r?(r.includes(t)||r.push(t),this):(this.eventObj[e]=[t],this)}$onAll(e){return this.$on(k,e)}$once(e,t){t.$__once=!0,this.$on(e,t)}$off(e,t){const r=this.eventObj[e];if(!e||!r||!r.length)return oe(`${e} ${ce}`),this;let o,i=r.length;for(;i--;)if(o=r[i],o===t){r.splice(i,1);break}return this}$offAll(e){return this.$off(k,e)}$emit(e,...t){return e=`${this.appName}/${e}`,this.$pureEmit(e,...t)}$pureEmit(e,...t){let r=0,o=0;return q.forEach(i=>{if(i[e])for(let s=i[e].length-1;s>=0;s--){r++;const c=i[e][s];c.$__once&&i[e].splice(s,1);try{c(...t)}catch(p){se(p)}}if(i[k])for(let s=i[k].length-1;s>=0;s--){r++;const c=i[k][s];c.$__once&&i[k].splice(s,1);try{c(...t)}catch(p){se(p)}}}),(!e||r===0&&o===0)&&oe(`${e} ${ce}`),this}$clear(){const e=q.get(this.id)??{};return Object.keys(e).forEach(r=>delete e[r]),this}}var B=function(n,e){return B=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])},B(n,e)};function le(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");B(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function ue(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function J(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(c){s={error:c}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(s)throw s.error}}return i}function Y(n,e,t){if(t||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return n.concat(i||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;function T(n){return typeof n=="function"}function ke(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var z=ke(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
2
2
|
`+t.map(function(r,o){return o+1+") "+r.toString()}).join(`
|
|
3
3
|
`):"",this.name="UnsubscriptionError",this.errors=t}});function fe(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var K=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=ue(s),p=c.next();!p.done;p=c.next()){var E=p.value;E.remove(this)}}catch(a){e={error:a}}finally{try{p&&!p.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else s.remove(this);var b=this.initialTeardown;if(T(b))try{b()}catch(a){i=a instanceof z?a.errors:[a]}var S=this._finalizers;if(S){this._finalizers=null;try{for(var g=ue(S),d=g.next();!d.done;d=g.next()){var m=d.value;try{de(m)}catch(a){i=i??[],a instanceof z?i=Y(Y([],J(i)),J(a.errors)):i.push(a)}}}catch(a){r={error:a}}finally{try{d&&!d.done&&(o=g.return)&&o.call(g)}finally{if(r)throw r.error}}}if(i)throw new z(i)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)de(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&fe(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&fe(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}();K.EMPTY;function pe(n){return n instanceof K||n&&"closed"in n&&T(n.remove)&&T(n.add)&&T(n.unsubscribe)}function de(n){T(n)?n():n.unsubscribe()}var he={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Ve={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,Y([n,e],J(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function qe(n){Ve.setTimeout(function(){throw n})}function ge(){}function We(n){n()}var ye=function(n){le(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,pe(t)&&t.add(r)):r.destination=Ue,r}return e.create=function(t,r,o){return new G(t,r,o)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(K),Ne=Function.prototype.bind;function Q(n,e){return Ne.call(n,e)}var Le=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){L(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){L(r)}else L(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){L(t)}},n}(),G=function(n){le(e,n);function e(t,r,o){var i=n.call(this)||this,s;if(T(t)||!t)s={next:t??void 0,error:r??void 0,complete:o??void 0};else{var c;i&&he.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return i.unsubscribe()},s={next:t.next&&Q(t.next,c),error:t.error&&Q(t.error,c),complete:t.complete&&Q(t.complete,c)}):s=t}return i.destination=new Le(s),i}return e}(ye);function L(n){qe(n)}function He(n){throw n}var Ue={closed:!0,next:ge,error:He,complete:ge},Be=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Je(n){return n}function Ye(n){return n.length===0?Je:n.length===1?n[0]:function(t){return n.reduce(function(r,o){return o(r)},t)}}var ze=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var o=this,i=Qe(e)?e:new G(e,t,r);return We(function(){var s=o,c=s.operator,p=s.source;i.add(c?c.call(i,p):p?o._subscribe(i):o._trySubscribe(i))}),i},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=me(t),new t(function(o,i){var s=new G({next:function(c){try{e(c)}catch(p){i(p),s.unsubscribe()}},error:i,complete:o});r.subscribe(s)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Be]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ye(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=me(e),new e(function(r,o){var i;t.subscribe(function(s){return i=s},function(s){return o(s)},function(){return r(i)})})},n.create=function(e){return new n(e)},n}();function me(n){var e;return(e=n??he.Promise)!==null&&e!==void 0?e:Promise}function Ke(n){return n&&T(n.next)&&T(n.error)&&T(n.complete)}function Qe(n){return n&&n instanceof ye||Ke(n)&&pe(n)}const Ge=()=>{try{clearTimeout(void 0)}catch{return!1}return!0},Xe=(n={})=>{const{parentOrigin:e="*",timeout:t,debug:r=!1,config:o={}}=n,i=$e(r),s=Ae("App",i),{destroy:c,onDestroy:p}=s,E=()=>{i("Child: Handshake - Sending SYN");const S={penpal:C.Syn},g=e instanceof RegExp?"*":e;window.parent.postMessage(S,g)};return{promise:new Promise((S,g)=>{const d=De(t,c),m=a=>{if(Ge()&&!(a.source!==parent||!a.data)&&a.data.penpal===C.SynAck){const y=a.data,$=new ae(y.id,y.appName),M=new ae(y.id+"/api",y.appName),F=y.id,O={},R=u=>"api/"+u,W={$emit:(u,...f)=>{$.getEventCallBackLength(u)>0?$.$pureEmit(u,...f):O==null||O.$off(u,()=>{},!0)},onQueryResult:u=>{M.$pureEmit(R(u.reqid),u)},onOsNotify:u=>{}},N=u=>function(h){const _=R(u);M.$on(_,function V(A){h.next(A),A.reqid&&A.result==="succ"&&(h.complete(),M.$off(_,V))})},et=ie(W),j=Ie(e,et,{...o,postmateVersion:je.version},s,i)(a),x={},H=j.bus;if(H){const u=(f,h,_)=>{_?(h.$__once=!0,$.$once(f,h)):$.$on(f,h),x[f]?x[f].push(h):(x[f]=[h],H.$on(f,F))};Object.assign(O,H,{$on:u,$off:(f,h,_)=>{var V;if(x[f]){const A=x[f].indexOf(h);A>-1&&(x[f].splice(A,1),$.$off(f,h))}_&&delete x[f],(V=x[f])!=null&&V.length||(H.$off(f,F),delete x[f])},$once:(f,h)=>{u(f,h,!0)}})}const tt={...j,bus:O,query:async(u,f)=>{const h=(u==null?void 0:u.reqid)||await j.genReqId();return new Promise((_,V)=>{j.query({...u,reqid:h},f).then(A=>{(A==null?void 0:A.result)==="succ"?_(A):V(A)})})},createObservableQuery:async(u,f={})=>{const h=(u==null?void 0:u.reqid)||await j.genReqId(),_=new ze(N(h));return j.query({...u,reqid:h},{...f,observable:!0}),_}};j&&(window.removeEventListener(D.Message,m),d(),S({methods:tt,config:a.data.config}))}};window.addEventListener(D.Message,m),E(),p(a=>{window.removeEventListener(D.Message,m),a&&g(a)})}),destroy(){c()}}},Ze=n=>Xe({debug:n==null?void 0:n.debug}).promise;class be{constructor(e={}){P(this,"options");P(this,"flutterInAppWebView",null);P(this,"osConnector",null);P(this,"initPromise");P(this,"isWeb",!0);this.options=e,e.debug&&(l.setDebug(!0),l.log("Trim App initialized with debug mode")),l.log("Options:",e),this.initPromise=this.init()}async init(){return l.log("Starting initialization..."),new Promise(e=>{X()?(this.isWeb=!1,l.log("Initializing mobile platform..."),ve().then(t=>{this.flutterInAppWebView=t,l.log("Mobile platform initialized"),e()})):(this.isWeb=!0,l.log("Initializing web platform..."),Ze().then(t=>{this.osConnector=t,l.log("Web platform initialized"),e()}))})}async callAppMethod(e,t){return this.flutterInAppWebView?Ee(this.flutterInAppWebView,e,t):null}async ready(){return this.initPromise}getOptions(){return this.options}setOptions(e){this.options={...this.options,...e},e.debug!==void 0&&l.setDebug(e.debug),l.log("Options updated:",this.options)}async getPlatformConfig(){var e;if(await this.initPromise,this.isWeb){const t=await((e=this.osConnector)==null?void 0:e.methods.getPlatformConfig());if(!t)throw new Error("Failed to get platform config");return t}else{const t=await this.callAppMethod("getAppMessage");if(!t)throw new Error("Failed to get platform config");return{theme:t.nightMode,language:t.language,appVersion:t.appVersion,systemVersion:t.systemVersion,format:{date:t.dateFormat,time:t.timeFormat}}}}async setTitle(e){var t;return await this.initPromise,l.log("Setting title:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setTitle(e):this.callAppMethod("updateTitle",e)}async setExitPageTips(e){var t;return await this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.setExitPageTips(e):this.callAppMethod("setExitPageTips",e?JSON.stringify(e):"")}async openFile(e){var t;return await this.initPromise,l.log("Opening file:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFile(e):this.callAppMethod("openFile",e)}async openFileManager(e){var t;return await this.initPromise,l.log("Opening file manager:",e),this.isWeb?(t=this.osConnector)==null?void 0:t.methods.openFileManagerApp(e):this.callAppMethod("openFileManager",e)}async close(){var e;if(await this.initPromise,this.isWeb)return(e=this.osConnector)==null?void 0:e.methods.close();throw new Error("close is not supported on mobile platform")}async query(e,t){var r;if(await this.initPromise,this.isWeb){const o=await((r=this.osConnector)==null?void 0:r.methods.query(e,t));if(!o)throw new Error("Failed to query");return o}else throw new Error("query is not supported on mobile platform")}async pickFile(e){var t;return await this.initPromise,this.isWeb?(t=this.osConnector)==null?void 0:t.methods.pickFile(e):this.callAppMethod("openFolder",JSON.stringify(e))}}w.TrimApp=be,w.default=be,Object.defineProperties(w,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
4
|
-
//# sourceMappingURL=index.umd.cjs.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trimjs/web-app",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.3",
|
|
4
4
|
"description": "web app sdk for nas",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -15,10 +15,12 @@
|
|
|
15
15
|
"src",
|
|
16
16
|
"dist"
|
|
17
17
|
],
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@fn/micro-app-postmate": "^0.1.2",
|
|
20
|
+
"@fn/micro-app-event": "^0.0.1"
|
|
21
|
+
},
|
|
18
22
|
"devDependencies": {
|
|
19
|
-
"@fn/micro-app-postmate": "workspace:*",
|
|
20
23
|
"@eslint/js": "^9.13.0",
|
|
21
|
-
"@fn/micro-app-event": "workspace:*",
|
|
22
24
|
"eslint": "^9.13.0",
|
|
23
25
|
"globals": "^15.11.0",
|
|
24
26
|
"typescript": "~5.6.2",
|
package/src/index.ts
CHANGED
|
@@ -5,10 +5,10 @@ import { isFnApp } from "./utils/platform";
|
|
|
5
5
|
import { callHandler, initMobile } from "./mobile/index";
|
|
6
6
|
import { initWeb, OSConnection } from "./web/index";
|
|
7
7
|
import { AppMessage } from "./mobile/types";
|
|
8
|
-
import { ResponseData } from "@fn/micro-app-postmate/src/child/os-type";
|
|
8
|
+
import { type ResponseData } from "@fn/micro-app-postmate/src/child/os-type";
|
|
9
9
|
import {
|
|
10
|
-
FilePickerParams,
|
|
11
|
-
QueryConfig,
|
|
10
|
+
type FilePickerParams,
|
|
11
|
+
type QueryConfig,
|
|
12
12
|
} from "@fn/micro-app-postmate/src/child/type";
|
|
13
13
|
|
|
14
14
|
/**
|
package/src/web/index.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { connectToOS } from "@fn/micro-app-postmate";
|
|
2
|
-
import { OSConfig } from "@fn/micro-app-postmate/src/parent/type";
|
|
2
|
+
import { type OSConfig } from "@fn/micro-app-postmate/src/parent/type";
|
|
3
3
|
import {
|
|
4
|
-
OSMethods,
|
|
5
|
-
ConnectionResult,
|
|
6
|
-
AsyncMethodReturns,
|
|
4
|
+
type OSMethods,
|
|
5
|
+
type ConnectionResult,
|
|
6
|
+
type AsyncMethodReturns,
|
|
7
7
|
} from "@fn/micro-app-postmate/src/types";
|
|
8
8
|
import type { PlatformConfig, TrimAppOptions } from "../types";
|
|
9
9
|
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/logger.ts","../src/utils/platform.ts","../src/mobile/index.ts","../../postmate/src/enums.ts","../../postmate/src/createDestructor.ts","../../postmate/src/createLogger.ts","../../postmate/src/errorSerialization.ts","../../postmate/src/connectCallReceiver.ts","../../postmate/src/generateId.ts","../../postmate/src/methodSerialization.ts","../../postmate/src/connectCallSender.ts","../../postmate/src/startConnectionTimeout.ts","../../postmate/src/child/handleSynAckMessageFactory.ts","../../event/src/utils.ts","../../event/src/constant.ts","../../event/src/index.ts","../../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/isFunction.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/arrRemove.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/Subscription.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/config.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/noop.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/errorContext.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/Subscriber.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/symbol/observable.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/identity.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/pipe.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/Observable.js","../../postmate/src/child/connectToOS.ts","../src/web/index.ts","../src/index.ts"],"sourcesContent":["/**\n * Logger 工具类\n * 只有在 debug 模式下才会输出日志\n */\nclass Logger {\n private debug: boolean = false;\n\n /**\n * 设置 debug 模式\n * @param enabled 是否启用 debug\n */\n setDebug(enabled: boolean) {\n this.debug = enabled;\n }\n\n /**\n * 获取当前 debug 状态\n */\n isDebug(): boolean {\n return this.debug;\n }\n\n /**\n * 输出日志(只在 debug 模式下)\n * @param args 日志参数\n */\n log(...args: any[]) {\n if (this.debug) {\n console.log('[Trim App]', ...args);\n }\n }\n\n /**\n * 输出警告日志(只在 debug 模式下)\n * @param args 日志参数\n */\n warn(...args: any[]) {\n if (this.debug) {\n console.warn('[Trim App]', ...args);\n }\n }\n\n /**\n * 输出错误日志(只在 debug 模式下)\n * @param args 日志参数\n */\n error(...args: any[]) {\n if (this.debug) {\n console.error('[Trim App]', ...args);\n }\n }\n\n /**\n * 输出信息日志(只在 debug 模式下)\n * @param args 日志参数\n */\n info(...args: any[]) {\n if (this.debug) {\n console.info('[Trim App]', ...args);\n }\n }\n}\n\n// 导出单例\nexport const logger = new Logger();\n","export function fnAppUAMatch(ua: string) {\n const regex = /FNOS\\/([\\d.]+)|FNAppType\\/(\\w+)|FNAppVer\\/([\\d.]+)/g;\n\n const matches: any = {};\n let match;\n while ((match = regex.exec(ua)) !== null) {\n if (match[1]) matches.fnOSVersion = match[1];\n if (match[2]) matches.fnAppType = match[2];\n if (match[3]) matches.fnAppVersion = match[3];\n }\n\n return matches;\n}\n\nexport const isFnApp = () => {\n return fnAppUAMatch(navigator.userAgent).fnAppVersion;\n};\n","import { logger } from \"../logger\";\nimport { isFnApp } from \"../utils/platform\";\n\nexport interface FlutterInAppWebView {\n callHandler: (fn: string, params?: string) => Promise<string>;\n _platformReady?: boolean;\n}\n\ndeclare global {\n interface Window {\n flutter_inappwebview: FlutterInAppWebView;\n fnAppMessage?: (message: string) => void;\n onAppHeaderGoBack?: () => boolean | number | string; // 随意返回\n }\n}\n\nexport const initMobile = () => {\n /**\n * 处理app有回掉的方法消息\n */\n return new Promise<FlutterInAppWebView>((res) => {\n if (window.flutter_inappwebview?._platformReady) {\n logger.log(\"flutter_inappwebview is ready\");\n res(window.flutter_inappwebview);\n } else {\n window.addEventListener(\"flutterInAppWebViewPlatformReady\", () => {\n logger.log(\"flutter_inappwebview is ready\");\n res(window.flutter_inappwebview);\n });\n }\n });\n};\n\nexport interface FnAppMessage<T> {\n reqId: string;\n method: string;\n result: T;\n}\n\nexport const callHandler = async <T>(\n flutterInAppWebView: FlutterInAppWebView,\n fn: string,\n params?: string\n): Promise<T | null> => {\n logger.log(`callHandler: ${fn}, params: ${params}`);\n const res = await flutterInAppWebView.callHandler(fn, params);\n if (res) {\n try {\n const messageData: FnAppMessage<string> = JSON.parse(res);\n logger.log(`messageData: ${JSON.stringify(messageData)}`);\n const appMessage: T = JSON.parse(messageData.result);\n logger.log(`appMessage: ${JSON.stringify(appMessage)}`);\n return appMessage;\n } catch (error) {\n logger.error(`error: ${error}`);\n return null;\n }\n }\n return null;\n};\n\n// 存储app消息的回调\nconst fnAppMessageHandleMap = new Map<\n string,\n (Response: FnAppMessage<any>) => void\n>();\n\nfunction initAppMessageEvent() {\n window.fnAppMessage = (message: string) => {\n logger.log(\"app-message\", message);\n const data: FnAppMessage<any> = JSON.parse(message);\n\n const handle = fnAppMessageHandleMap.get(data.reqId);\n if (handle) {\n handle(data);\n fnAppMessageHandleMap.delete(data.reqId);\n }\n };\n}\n\nif (isFnApp()) {\n initAppMessageEvent();\n}\n\nexport async function pickFilePromise(\n flutterInAppWebView: FlutterInAppWebView,\n params: {\n title: string;\n multiple: boolean;\n directory: boolean;\n }\n): Promise<string[] | undefined> {\n return new Promise((resolve, reject) => {\n flutterInAppWebView\n ?.callHandler(\"openFolder\", JSON.stringify(params))\n .then((reqId) => {\n if (reqId) {\n function handle(data: FnAppMessage<string[]>) {\n resolve(data.result);\n }\n fnAppMessageHandleMap.set(reqId, handle);\n } else {\n reject(new Error(\"openFolder failed\"));\n }\n });\n });\n}\n","export enum MessageType {\n Call = 'call',\n Reply = 'reply',\n Syn = 'syn',\n SynAck = 'synAck',\n Ack = 'ack',\n}\n\nexport enum Resolution {\n Fulfilled = 'fulfilled',\n Rejected = 'rejected',\n}\n\nexport enum ErrorCode {\n ConnectionDestroyed = 'ConnectionDestroyed',\n ConnectionTimeout = 'ConnectionTimeout',\n NoIframeSrc = 'NoIframeSrc',\n}\n\nexport enum NativeErrorName {\n DataCloneError = 'DataCloneError',\n}\n\nexport enum NativeEventType {\n Message = 'message',\n}\n","import { PenpalError } from './types';\n\nexport type Destructor = {\n /**\n * Calls all onDestroy callbacks.\n */\n destroy(error?: PenpalError): void;\n /**\n * Registers a callback to be called when destroy is called.\n */\n onDestroy(callback: Function): void;\n};\n\nexport default (localName: 'OS' | 'App', log: Function): Destructor => {\n const callbacks: Function[] = [];\n let destroyed = false;\n\n return {\n destroy(error) {\n if (!destroyed) {\n destroyed = true;\n log(`${localName}: Destroying connection`);\n callbacks.forEach((callback) => {\n callback(error);\n });\n }\n },\n onDestroy(callback) {\n destroyed ? callback() : callbacks.push(callback);\n },\n };\n};\n","export default (debug: boolean) => {\n /**\n * Logs a message if debug is enabled.\n */\n return (...args: any) => {\n if (debug) {\n console.log('[Penpal]', ...args); // eslint-disable-line no-console\n }\n };\n};\n","type SerializedError = {\n name: string;\n message: string;\n stack: string | undefined;\n};\n\n/**\n * Converts an error object into a plain object.\n */\nexport const serializeError = ({\n name,\n message,\n stack,\n}: Error): SerializedError => ({\n name,\n message,\n stack,\n});\n\n/**\n * Converts a plain object into an error object.\n */\nexport const deserializeError = (obj: SerializedError): Error => {\n const deserializedError = new Error();\n // @ts-ignore\n Object.keys(obj).forEach((key) => (deserializedError[key] = obj[key]));\n return deserializedError;\n};\n","import { serializeError } from './errorSerialization';\nimport {\n CallMessage,\n SerializedMethods,\n ReplyMessage,\n WindowsInfo,\n} from './types';\nimport {\n MessageType,\n NativeEventType,\n NativeErrorName,\n Resolution,\n} from './enums';\n\n/**\n * Listens for \"call\" messages coming from the remote, executes the corresponding method, and\n * responds with the return value.\n */\nexport default (\n info: WindowsInfo,\n serializedMethods: SerializedMethods,\n log: Function\n) => {\n const {\n localName,\n local,\n remote,\n originForSending,\n originForReceiving,\n } = info;\n let destroyed = false;\n\n const handleMessageEvent = (event: MessageEvent) => {\n if (event.source !== remote || event.data.penpal !== MessageType.Call) {\n return;\n }\n\n if (originForReceiving !== '*' && event.origin !== originForReceiving) {\n log(\n `${localName} received message from origin ${event.origin} which did not match expected origin ${originForReceiving}`\n );\n return;\n }\n\n const callMessage: CallMessage = event.data;\n const { methodName, args, id } = callMessage;\n\n log(`${localName}: Received ${methodName}() call`);\n\n const createPromiseHandler = (resolution: Resolution) => {\n return (returnValue: any) => {\n log(`${localName}: Sending ${methodName}() reply`);\n\n if (destroyed) {\n // It's possible to throw an error here, but it would need to be thrown asynchronously\n // and would only be catchable using window.onerror. This is because the consumer\n // is merely returning a value from their method and not calling any function\n // that they could wrap in a try-catch. Even if the consumer were to catch the error,\n // the value of doing so is questionable. Instead, we'll just log a message.\n log(\n `${localName}: Unable to send ${methodName}() reply due to destroyed connection`\n );\n return;\n }\n\n const message: ReplyMessage = {\n penpal: MessageType.Reply,\n id,\n resolution,\n returnValue,\n };\n\n if (\n resolution === Resolution.Rejected &&\n returnValue instanceof Error\n ) {\n message.returnValue = serializeError(returnValue);\n message.returnValueIsError = true;\n }\n\n try {\n remote.postMessage(message, originForSending);\n } catch (err) {\n // If a consumer attempts to send an object that's not cloneable (e.g., window),\n // we want to ensure the receiver's promise gets rejected.\n if (err.name === NativeErrorName.DataCloneError) {\n const errorReplyMessage: ReplyMessage = {\n penpal: MessageType.Reply,\n id,\n resolution: Resolution.Rejected,\n returnValue: serializeError(err),\n returnValueIsError: true,\n };\n remote.postMessage(errorReplyMessage, originForSending);\n }\n\n throw err;\n }\n };\n };\n\n new Promise((resolve) =>\n resolve(serializedMethods[methodName].apply(serializedMethods, args))\n ).then(\n createPromiseHandler(Resolution.Fulfilled),\n createPromiseHandler(Resolution.Rejected)\n );\n };\n\n local.addEventListener(NativeEventType.Message, handleMessageEvent);\n\n return () => {\n destroyed = true;\n local.removeEventListener(NativeEventType.Message, handleMessageEvent);\n };\n};\n","let id = 0;\n/**\n * @return {number} A unique ID (not universally unique)\n */\nexport default () => ++id;\n","import { SerializedMethods, Methods } from './types';\n\nconst KEY_PATH_DELIMITER = '.';\n\nconst keyPathToSegments = (keyPath: string) =>\n keyPath ? keyPath.split(KEY_PATH_DELIMITER) : [];\nconst segmentsToKeyPath = (segments: string[]) =>\n segments.join(KEY_PATH_DELIMITER);\n\nconst createKeyPath = (key: string, prefix?: string) => {\n const segments = keyPathToSegments(prefix || '');\n segments.push(key);\n return segmentsToKeyPath(segments);\n};\n\n/**\n * Given a `keyPath`, set it to be `value` on `subject`, creating any intermediate\n * objects along the way.\n *\n * @param {Object} subject The object on which to set value.\n * @param {string} keyPath The key path at which to set value.\n * @param {Object} value The value to store at the given key path.\n * @returns {Object} Updated subject.\n */\nexport const setAtKeyPath = (\n subject: Record<string, any>,\n keyPath: string,\n value: any\n) => {\n const segments = keyPathToSegments(keyPath);\n\n segments.reduce((prevSubject, key, idx) => {\n if (typeof prevSubject[key] === 'undefined') {\n prevSubject[key] = {};\n }\n\n if (idx === segments.length - 1) {\n prevSubject[key] = value;\n }\n\n return prevSubject[key];\n }, subject);\n\n return subject;\n};\n\n/**\n * Given a dictionary of (nested) keys to function, flatten them to a map\n * from key path to function.\n *\n * @param {Object} methods The (potentially nested) object to serialize.\n * @param {string} prefix A string with which to prefix entries. Typically not intended to be used by consumers.\n * @returns {Object} An map from key path in `methods` to functions.\n */\nexport const serializeMethods = (\n methods: Methods,\n prefix?: string\n): SerializedMethods => {\n const flattenedMethods: SerializedMethods = {};\n\n Object.keys(methods).forEach((key) => {\n const value = methods[key];\n const keyPath = createKeyPath(key, prefix);\n\n if (typeof value === 'object') {\n // Recurse into any nested children.\n Object.assign(flattenedMethods, serializeMethods(value, keyPath));\n }\n\n if (typeof value === 'function') {\n // If we've found a method, expose it.\n flattenedMethods[keyPath] = value;\n }\n });\n\n return flattenedMethods;\n};\n\n/**\n * Given a map of key paths to functions, unpack the key paths to an object.\n *\n * @param {Object} flattenedMethods A map of key paths to functions to unpack.\n * @returns {Object} A (potentially nested) map of functions.\n */\nexport const deserializeMethods = (\n flattenedMethods: SerializedMethods\n): Methods => {\n const methods: Methods = {};\n\n for (const keyPath in flattenedMethods) {\n setAtKeyPath(methods, keyPath, flattenedMethods[keyPath]);\n }\n\n return methods;\n};\n","import generateId from './generateId';\nimport { deserializeError } from './errorSerialization';\nimport { deserializeMethods } from './methodSerialization';\nimport {\n CallMessage,\n CallSender,\n PenpalError,\n ReplyMessage,\n WindowsInfo,\n} from './types';\nimport { ErrorCode, MessageType, NativeEventType, Resolution } from './enums';\n\n/**\n * Augments an object with methods that match those defined by the remote. When these methods are\n * called, a \"call\" message will be sent to the remote, the remote's corresponding method will be\n * executed, and the method's return value will be returned via a message.\n * @param {Object} callSender Sender object that should be augmented with methods.\n * @param {Object} info Information about the local and remote windows.\n * @param {Array} methodKeyPaths Key paths of methods available to be called on the remote.\n * @param {Promise} destructionPromise A promise resolved when destroy() is called on the penpal\n * connection.\n * @returns {Object} The call sender object with methods that may be called.\n */\nexport default (\n callSender: CallSender,\n info: WindowsInfo,\n methodKeyPaths: string[],\n destroyConnection: Function,\n log: Function\n) => {\n const {\n localName,\n local,\n remote,\n originForSending,\n originForReceiving,\n } = info;\n let destroyed = false;\n\n log(`${localName}: Connecting call sender`);\n\n const createMethodProxy = (methodName: string) => {\n return (...args: any) => {\n log(`${localName}: Sending ${methodName}() call`);\n\n // This handles the case where the iframe has been removed from the DOM\n // (and therefore its window closed), the consumer has not yet\n // called destroy(), and the user calls a method exposed by\n // the remote. We detect the iframe has been removed and force\n // a destroy() immediately so that the consumer sees the error saying\n // the connection has been destroyed. We wrap this check in a try catch\n // because Edge throws an \"Object expected\" error when accessing\n // contentWindow.closed on a contentWindow from an iframe that's been\n // removed from the DOM.\n let iframeRemoved;\n try {\n if (remote.closed) {\n iframeRemoved = true;\n }\n } catch (e) {\n iframeRemoved = true;\n }\n\n if (iframeRemoved) {\n destroyConnection();\n }\n\n if (destroyed) {\n const error: PenpalError = new Error(\n `Unable to send ${methodName}() call due ` + `to destroyed connection`\n ) as PenpalError;\n\n error.code = ErrorCode.ConnectionDestroyed;\n throw error;\n }\n\n return new Promise((resolve, reject) => {\n const id = generateId();\n const handleMessageEvent = (event: MessageEvent) => {\n if (\n event.source !== remote ||\n event.data.penpal !== MessageType.Reply ||\n event.data.id !== id\n ) {\n return;\n }\n\n if (\n originForReceiving !== '*' &&\n event.origin !== originForReceiving\n ) {\n log(\n `${localName} received message from origin ${event.origin} which did not match expected origin ${originForReceiving}`\n );\n return;\n }\n\n const replyMessage: ReplyMessage = event.data;\n\n log(`${localName}: Received ${methodName}() reply`);\n local.removeEventListener(\n NativeEventType.Message,\n handleMessageEvent\n );\n\n let returnValue = replyMessage.returnValue;\n\n if (replyMessage.returnValueIsError) {\n returnValue = deserializeError(returnValue);\n }\n\n (replyMessage.resolution === Resolution.Fulfilled ? resolve : reject)(\n returnValue\n );\n };\n\n local.addEventListener(NativeEventType.Message, handleMessageEvent);\n const callMessage: CallMessage = {\n penpal: MessageType.Call,\n id,\n methodName,\n args,\n };\n remote.postMessage(callMessage, originForSending);\n });\n };\n };\n\n // Wrap each method in a proxy which sends it to the corresponding receiver.\n const flattenedMethods = methodKeyPaths.reduce<\n Record<string, () => Promise<unknown>>\n >((api, name) => {\n api[name] = createMethodProxy(name);\n return api;\n }, {});\n\n // Unpack the structure of the provided methods object onto the CallSender, exposing\n // the methods in the same shape they were provided.\n Object.assign(callSender, deserializeMethods(flattenedMethods));\n\n return () => {\n destroyed = true;\n };\n};\n","import { PenpalError } from './types';\nimport { ErrorCode } from './enums';\n\n/**\n * Starts a timeout and calls the callback with an error\n * if the timeout completes before the stop function is called.\n */\nexport default (timeout: number | undefined, callback: Function): Function => {\n let timeoutId: number;\n\n if (timeout !== undefined) {\n timeoutId = window.setTimeout(() => {\n const error: PenpalError = new Error(\n `Connection timed out after ${timeout}ms`\n ) as PenpalError;\n error.code = ErrorCode.ConnectionTimeout;\n callback(error);\n }, timeout);\n }\n\n return () => {\n clearTimeout(timeoutId);\n };\n};\n","import {\n AckMessage,\n CallSender,\n SerializedMethods,\n WindowsInfo,\n} from '../types';\nimport { MessageType } from '../enums';\nimport connectCallReceiver from '../connectCallReceiver';\nimport connectCallSender from '../connectCallSender';\nimport { Destructor } from '../createDestructor';\n\n/**\n * Handles a SYN-ACK handshake message.\n */\nexport default (\n parentOrigin: string | RegExp,\n serializedMethods: SerializedMethods,\n config: any,\n destructor: Destructor,\n log: Function\n) => {\n const { destroy, onDestroy } = destructor;\n\n return (event: MessageEvent): CallSender | undefined => {\n let originQualifies =\n parentOrigin instanceof RegExp\n ? parentOrigin.test(event.origin)\n : parentOrigin === '*' || parentOrigin === event.origin;\n\n if (!originQualifies) {\n log(\n `Child: Handshake - Received SYN-ACK from origin ${event.origin} which did not match expected origin ${parentOrigin}`\n );\n return;\n }\n\n log('Child: Handshake - Received SYN-ACK, responding with ACK');\n\n // If event.origin is \"null\", the remote protocol is file: or data: and we\n // must post messages with \"*\" as targetOrigin when sending messages.\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Using_window.postMessage_in_extensions\n const originForSending = event.origin === 'null' ? '*' : event.origin;\n\n const ackMessage: AckMessage = {\n penpal: MessageType.Ack,\n methodNames: Object.keys(serializedMethods),\n config,\n };\n\n window.parent.postMessage(ackMessage, originForSending);\n\n const info: WindowsInfo = {\n localName: 'Child',\n local: window,\n remote: window.parent,\n originForSending,\n originForReceiving: event.origin,\n };\n\n const destroyCallReceiver = connectCallReceiver(\n info,\n serializedMethods,\n log\n );\n onDestroy(destroyCallReceiver);\n\n const callSender: CallSender = {};\n const destroyCallSender = connectCallSender(\n callSender,\n info,\n event.data.methodNames,\n destroy,\n log\n );\n onDestroy(destroyCallSender);\n\n return callSender;\n };\n};\n","export function warn(msg: string, data?: any): void {\n console?.warn(`[fnApp warn]: ${msg}`, data);\n}\n\nexport function error(msg: string, data?: any): void {\n console?.error(`[fnApp error]: ${msg}`, data);\n}","// 需要使用的某些固定变量\nexport const FNAPP_ALL_EVENT = \"_fn_all_event\";\n\n// 提醒类\nexport const FNAPP_TIPS_NO_SUBJECT = \"事件订阅数量为空\";\n","import { warn, error } from \"./utils\";\nimport { FNAPP_ALL_EVENT, FNAPP_TIPS_NO_SUBJECT } from \"./constant\";\n\nexport type EventObj = { [event: string]: Array<Function> };\n\n// 全部事件存储map\nexport const appEventObjMap: Map<String, EventObj> = (window as any).__POWERED_BY_FNAPP__\n ? (window as any).__FNAPP.inject.appEventObjMap\n : new Map<String, EventObj>();\n\n// eventBus 事件中心\nexport class EventBus {\n private id: string;\n private appName: string;\n private eventObj: EventObj;\n\n constructor(id: string, appName: string) {\n console.log('id', id, appName)\n this.id = id;\n this.appName = appName;\n this.$clear();\n if (!appEventObjMap.get(this.id)) {\n appEventObjMap.set(this.id, {});\n }\n this.eventObj = appEventObjMap.get(this.id)!;\n }\n\n public getEventCallBackLength = (event: string) => {\n return this.eventObj[event]?.length || 0\n }\n\n // 监听事件\n public $on(event: string, fn: Function): EventBus {\n const cbs = this.eventObj[event];\n if (!cbs) {\n this.eventObj[event] = [fn];\n return this;\n }\n if (!cbs.includes(fn)) cbs.push(fn);\n return this;\n }\n\n /** 任何$emit都会导致监听函数触发,第一个参数为事件名,后续的参数为$emit的参数 */\n public $onAll(fn: (event: string, ...args: Array<any>) => any): EventBus {\n return this.$on(FNAPP_ALL_EVENT, fn);\n }\n\n // 一次性监听事件\n public $once(event: string, fn: Function): void {\n (fn as any).$__once = true;\n this.$on(event, fn);\n }\n\n // 取消监听\n public $off(event: string, fn: Function): EventBus {\n const cbs = this.eventObj[event];\n if (!event || !cbs || !cbs.length) {\n warn(`${event} ${FNAPP_TIPS_NO_SUBJECT}`);\n return this;\n }\n\n let cb;\n let i = cbs.length;\n while (i--) {\n cb = cbs[i];\n if (cb === fn) {\n cbs.splice(i, 1);\n break;\n }\n }\n return this;\n }\n\n // 取消监听$onAll\n public $offAll(fn: Function): EventBus {\n return this.$off(FNAPP_ALL_EVENT, fn);\n }\n\n // 发送事件\n public $emit(event: string, ...args: Array<any>): EventBus {\n event = `${this.appName}/${event}`\n // console.log('event', event, this.appName)\n return this.$pureEmit(event, ...args)\n }\n\n // 发送事件\n public $pureEmit(event: string, ...args: Array<any>): EventBus {\n let cbsLength = 0;\n let allCbsLength = 0;\n\n appEventObjMap.forEach((eventObj) => {\n if (eventObj[event]) {\n for (let i = eventObj[event].length - 1; i >= 0; i--) {\n cbsLength++\n const fn = eventObj[event][i];\n if ((fn as any).$__once) {\n eventObj[event].splice(i, 1)\n }\n try {\n fn(...args)\n } catch (e: any) {\n error(e);\n }\n }\n };\n if (eventObj[FNAPP_ALL_EVENT]) {\n for (let i = eventObj[FNAPP_ALL_EVENT].length - 1; i >= 0; i--) {\n cbsLength++\n const fn = eventObj[FNAPP_ALL_EVENT][i];\n if ((fn as any).$__once) {\n eventObj[FNAPP_ALL_EVENT].splice(i, 1)\n }\n try {\n fn(...args)\n } catch (e: any) {\n error(e);\n }\n }\n };\n });\n\n if (!event || (cbsLength === 0 && allCbsLength=== 0)) {\n warn(`${event} ${FNAPP_TIPS_NO_SUBJECT}`);\n }\n return this;\n }\n\n // 清空当前所有的监听事件\n public $clear(): EventBus {\n const eventObj = appEventObjMap.get(this.id) ?? {};\n const events = Object.keys(eventObj);\n events.forEach((event) => delete eventObj[event]);\n return this;\n }\n}\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","export function isFunction(value) {\n return typeof value === 'function';\n}\n//# sourceMappingURL=isFunction.js.map","export function createErrorClass(createImpl) {\n var _super = function (instance) {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n var ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n//# sourceMappingURL=createErrorClass.js.map","import { createErrorClass } from './createErrorClass';\nexport var UnsubscriptionError = createErrorClass(function (_super) {\n return function UnsubscriptionErrorImpl(errors) {\n _super(this);\n this.message = errors\n ? errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ')\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n };\n});\n//# sourceMappingURL=UnsubscriptionError.js.map","export function arrRemove(arr, item) {\n if (arr) {\n var index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n//# sourceMappingURL=arrRemove.js.map","import { __read, __spreadArray, __values } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { arrRemove } from './util/arrRemove';\nvar Subscription = (function () {\n function Subscription(initialTeardown) {\n this.initialTeardown = initialTeardown;\n this.closed = false;\n this._parentage = null;\n this._finalizers = null;\n }\n Subscription.prototype.unsubscribe = function () {\n var e_1, _a, e_2, _b;\n var errors;\n if (!this.closed) {\n this.closed = true;\n var _parentage = this._parentage;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n try {\n for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {\n var parent_1 = _parentage_1_1.value;\n parent_1.remove(this);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n else {\n _parentage.remove(this);\n }\n }\n var initialFinalizer = this.initialTeardown;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n var _finalizers = this._finalizers;\n if (_finalizers) {\n this._finalizers = null;\n try {\n for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {\n var finalizer = _finalizers_1_1.value;\n try {\n execFinalizer(finalizer);\n }\n catch (err) {\n errors = errors !== null && errors !== void 0 ? errors : [];\n if (err instanceof UnsubscriptionError) {\n errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));\n }\n else {\n errors.push(err);\n }\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n };\n Subscription.prototype.add = function (teardown) {\n var _a;\n if (teardown && teardown !== this) {\n if (this.closed) {\n execFinalizer(teardown);\n }\n else {\n if (teardown instanceof Subscription) {\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);\n }\n }\n };\n Subscription.prototype._hasParent = function (parent) {\n var _parentage = this._parentage;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n };\n Subscription.prototype._addParent = function (parent) {\n var _parentage = this._parentage;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n };\n Subscription.prototype._removeParent = function (parent) {\n var _parentage = this._parentage;\n if (_parentage === parent) {\n this._parentage = null;\n }\n else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n };\n Subscription.prototype.remove = function (teardown) {\n var _finalizers = this._finalizers;\n _finalizers && arrRemove(_finalizers, teardown);\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n };\n Subscription.EMPTY = (function () {\n var empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n return Subscription;\n}());\nexport { Subscription };\nexport var EMPTY_SUBSCRIPTION = Subscription.EMPTY;\nexport function isSubscription(value) {\n return (value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));\n}\nfunction execFinalizer(finalizer) {\n if (isFunction(finalizer)) {\n finalizer();\n }\n else {\n finalizer.unsubscribe();\n }\n}\n//# sourceMappingURL=Subscription.js.map","export var config = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n//# sourceMappingURL=config.js.map","import { __read, __spreadArray } from \"tslib\";\nexport var timeoutProvider = {\n setTimeout: function (handler, timeout) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n var delegate = timeoutProvider.delegate;\n if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {\n return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));\n }\n return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));\n },\n clearTimeout: function (handle) {\n var delegate = timeoutProvider.delegate;\n return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);\n },\n delegate: undefined,\n};\n//# sourceMappingURL=timeoutProvider.js.map","import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\nexport function reportUnhandledError(err) {\n timeoutProvider.setTimeout(function () {\n var onUnhandledError = config.onUnhandledError;\n if (onUnhandledError) {\n onUnhandledError(err);\n }\n else {\n throw err;\n }\n });\n}\n//# sourceMappingURL=reportUnhandledError.js.map","export function noop() { }\n//# sourceMappingURL=noop.js.map","import { config } from '../config';\nvar context = null;\nexport function errorContext(cb) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n var isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n var _a = context, errorThrown = _a.errorThrown, error = _a.error;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n }\n else {\n cb();\n }\n}\nexport function captureError(err) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n//# sourceMappingURL=errorContext.js.map","import { __extends } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\nvar Subscriber = (function (_super) {\n __extends(Subscriber, _super);\n function Subscriber(destination) {\n var _this = _super.call(this) || this;\n _this.isStopped = false;\n if (destination) {\n _this.destination = destination;\n if (isSubscription(destination)) {\n destination.add(_this);\n }\n }\n else {\n _this.destination = EMPTY_OBSERVER;\n }\n return _this;\n }\n Subscriber.create = function (next, error, complete) {\n return new SafeSubscriber(next, error, complete);\n };\n Subscriber.prototype.next = function (value) {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n }\n else {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n }\n else {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n }\n else {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (!this.closed) {\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n this.destination = null;\n }\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n try {\n this.destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n };\n Subscriber.prototype._complete = function () {\n try {\n this.destination.complete();\n }\n finally {\n this.unsubscribe();\n }\n };\n return Subscriber;\n}(Subscription));\nexport { Subscriber };\nvar _bind = Function.prototype.bind;\nfunction bind(fn, thisArg) {\n return _bind.call(fn, thisArg);\n}\nvar ConsumerObserver = (function () {\n function ConsumerObserver(partialObserver) {\n this.partialObserver = partialObserver;\n }\n ConsumerObserver.prototype.next = function (value) {\n var partialObserver = this.partialObserver;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n ConsumerObserver.prototype.error = function (err) {\n var partialObserver = this.partialObserver;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n else {\n handleUnhandledError(err);\n }\n };\n ConsumerObserver.prototype.complete = function () {\n var partialObserver = this.partialObserver;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n return ConsumerObserver;\n}());\nvar SafeSubscriber = (function (_super) {\n __extends(SafeSubscriber, _super);\n function SafeSubscriber(observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n var partialObserver;\n if (isFunction(observerOrNext) || !observerOrNext) {\n partialObserver = {\n next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),\n error: error !== null && error !== void 0 ? error : undefined,\n complete: complete !== null && complete !== void 0 ? complete : undefined,\n };\n }\n else {\n var context_1;\n if (_this && config.useDeprecatedNextContext) {\n context_1 = Object.create(observerOrNext);\n context_1.unsubscribe = function () { return _this.unsubscribe(); };\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context_1),\n error: observerOrNext.error && bind(observerOrNext.error, context_1),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),\n };\n }\n else {\n partialObserver = observerOrNext;\n }\n }\n _this.destination = new ConsumerObserver(partialObserver);\n return _this;\n }\n return SafeSubscriber;\n}(Subscriber));\nexport { SafeSubscriber };\nfunction handleUnhandledError(error) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n }\n else {\n reportUnhandledError(error);\n }\n}\nfunction defaultErrorHandler(err) {\n throw err;\n}\nfunction handleStoppedNotification(notification, subscriber) {\n var onStoppedNotification = config.onStoppedNotification;\n onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });\n}\nexport var EMPTY_OBSERVER = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n//# sourceMappingURL=Subscriber.js.map","export var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();\n//# sourceMappingURL=observable.js.map","export function identity(x) {\n return x;\n}\n//# sourceMappingURL=identity.js.map","import { identity } from './identity';\nexport function pipe() {\n var fns = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fns[_i] = arguments[_i];\n }\n return pipeFromArray(fns);\n}\nexport function pipeFromArray(fns) {\n if (fns.length === 0) {\n return identity;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n };\n}\n//# sourceMappingURL=pipe.js.map","import { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription } from './Subscription';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\nvar Observable = (function () {\n function Observable(subscribe) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n Observable.prototype.lift = function (operator) {\n var observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n };\n Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n var _this = this;\n var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n errorContext(function () {\n var _a = _this, operator = _a.operator, source = _a.source;\n subscriber.add(operator\n ?\n operator.call(subscriber, source)\n : source\n ?\n _this._subscribe(subscriber)\n :\n _this._trySubscribe(subscriber));\n });\n return subscriber;\n };\n Observable.prototype._trySubscribe = function (sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n sink.error(err);\n }\n };\n Observable.prototype.forEach = function (next, promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var subscriber = new SafeSubscriber({\n next: function (value) {\n try {\n next(value);\n }\n catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n _this.subscribe(subscriber);\n });\n };\n Observable.prototype._subscribe = function (subscriber) {\n var _a;\n return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);\n };\n Observable.prototype[Symbol_observable] = function () {\n return this;\n };\n Observable.prototype.pipe = function () {\n var operations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n operations[_i] = arguments[_i];\n }\n return pipeFromArray(operations)(this);\n };\n Observable.prototype.toPromise = function (promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var value;\n _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });\n });\n };\n Observable.create = function (subscribe) {\n return new Observable(subscribe);\n };\n return Observable;\n}());\nexport { Observable };\nfunction getPromiseCtor(promiseCtor) {\n var _a;\n return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;\n}\nfunction isObserver(value) {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\nfunction isSubscriber(value) {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n//# sourceMappingURL=Observable.js.map","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-unsafe-function-type */\nimport createDestructor from \"../createDestructor\";\nimport createLogger from \"../createLogger\";\nimport {\n SynMessage,\n Methods,\n PenpalError,\n CallSender,\n AsyncMethodReturns,\n SynAckMessage,\n ConnectionResult,\n} from \"../types\";\nimport { ErrorCode, MessageType, NativeEventType } from \"../enums\";\nimport handleSynAckMessageFactory from \"./handleSynAckMessageFactory\";\nimport { serializeMethods } from \"../methodSerialization\";\nimport startConnectionTimeout from \"../startConnectionTimeout\";\nimport { EventBus } from \"@fn/micro-app-event\";\nimport { Observable } from \"rxjs\";\nimport { AppConfig, OSMethods, OSProxyMethods } from \"./type\";\nimport { ResponseData } from \"./os-type\";\nimport pkg from \"../../package.json\";\n\nconst areGlobalsAccessible = () => {\n try {\n clearTimeout(undefined as unknown as number);\n } catch (_) {\n return false;\n }\n return true;\n};\n\ntype Options = {\n config?: AppConfig;\n /**\n * Valid parent origin used to restrict communication.\n */\n parentOrigin?: string | RegExp;\n /**\n * The amount of time, in milliseconds, Penpal should wait\n * for the parent to respond before rejecting the connection promise.\n */\n timeout?: number;\n /**\n * Whether log messages should be emitted to the console.\n */\n debug?: boolean;\n};\n\ntype Connection<TCallSender extends object = CallSender> = {\n /**\n * A promise which will be resolved once a connection has been established.\n */\n promise: Promise<AsyncMethodReturns<TCallSender>>;\n /**\n * A method that, when called, will disconnect any messaging channels.\n * You may call this even before a connection has been established.\n */\n destroy: Function;\n};\n\n/**\n * Attempts to establish communication with the parent window.\n */\nexport default (\n options: Options = {}\n): Connection<ConnectionResult<OSMethods>> => {\n const { parentOrigin = \"*\", timeout, debug = false, config = {} } = options;\n const log = createLogger(debug);\n const destructor = createDestructor(\"App\", log);\n const { destroy, onDestroy } = destructor;\n\n const sendSynMessage = () => {\n log(\"Child: Handshake - Sending SYN\");\n const synMessage: SynMessage = { penpal: MessageType.Syn };\n const parentOriginForSyn =\n parentOrigin instanceof RegExp ? \"*\" : parentOrigin;\n window.parent.postMessage(synMessage, parentOriginForSyn);\n };\n\n const promise: Promise<ConnectionResult<OSMethods>> = new Promise(\n (resolve, reject) => {\n const stopConnectionTimeout = startConnectionTimeout(timeout, destroy);\n const handleMessage = (event: MessageEvent) => {\n // Under niche scenarios, we get into this function after\n // the iframe has been removed from the DOM. In Edge, this\n // results in \"Object expected\" errors being thrown when we\n // try to access properties on window (global properties).\n // For this reason, we try to access a global up front (clearTimeout)\n // and if it fails we can assume the iframe has been removed\n // and we ignore the message event.\n if (!areGlobalsAccessible()) {\n return;\n }\n\n if (event.source !== parent || !event.data) {\n return;\n }\n\n if (event.data.penpal === MessageType.SynAck) {\n const data = event.data as SynAckMessage;\n const bus = new EventBus(data.id, data.appName);\n const queryBus = new EventBus(data.id + \"/api\", data.appName);\n const id = data.id;\n const proxyBus = {} as any;\n const getQueryBusEvent = (reqid: string) => {\n return \"api/\" + reqid;\n };\n const methods = {\n $emit: (event: string, ...args: Array<any>) => {\n if (bus.getEventCallBackLength(event) > 0) {\n bus.$pureEmit(event, ...args);\n } else {\n (proxyBus as any)?.$off(event, () => void 0, true);\n }\n },\n onQueryResult: (res) => {\n queryBus.$pureEmit(getQueryBusEvent(res.reqid), res);\n },\n onOsNotify: (data) => {\n // console.log('onOsNotify data', data)\n },\n };\n\n const genSubscribe = (reqid: string) => {\n return function subscribe(observer) {\n const event = getQueryBusEvent(reqid);\n queryBus.$on(event, function onReqId(res: ResponseData<any>) {\n observer.next(res);\n if (res.reqid && res.result === \"succ\") {\n observer.complete();\n queryBus.$off(event, onReqId);\n }\n });\n };\n };\n\n const serializedMethods = serializeMethods(methods);\n const handleSynAckMessage = handleSynAckMessageFactory(\n parentOrigin,\n serializedMethods,\n {\n ...config,\n postmateVersion: pkg.version,\n },\n destructor,\n log\n );\n const callSender = handleSynAckMessage(\n event\n ) as unknown as AsyncMethodReturns<OSProxyMethods>;\n const busFns = {} as { [key in string]: Function[] };\n const callSenderBus = callSender[\"bus\"];\n if (callSenderBus) {\n const on = (\n event: string,\n cb: (...args: any[]) => void,\n once?: boolean\n ) => {\n if (once) {\n (cb as any).$__once = true;\n bus.$once(event, cb);\n } else {\n bus.$on(event, cb);\n }\n if (busFns[event]) {\n busFns[event].push(cb);\n } else {\n busFns[event] = [cb];\n callSenderBus.$on(event, id);\n }\n };\n Object.assign(proxyBus, callSenderBus, {\n $on: on,\n $off: (\n event: string,\n cb: (...args: any[]) => void,\n force?: boolean\n ) => {\n if (busFns[event]) {\n const index = busFns[event].indexOf(cb);\n if (index > -1) {\n busFns[event].splice(index, 1);\n bus.$off(event, cb);\n }\n }\n if (force) {\n delete busFns[event];\n }\n if (!busFns[event]?.length) {\n callSenderBus.$off(event, id);\n delete busFns[event];\n }\n },\n $once: (event: string, cb: (...args: any[]) => void) => {\n on(event, cb, true);\n },\n });\n }\n const proxyCallSender = {\n ...callSender,\n bus: proxyBus,\n query: async (params: any, config?: any) => {\n const reqid = params?.reqid || (await callSender.genReqId());\n return new Promise<ResponseData<any>>((resolve, reject) => {\n callSender\n .query(\n {\n ...params,\n reqid,\n },\n config\n )\n .then((res) => {\n if (res?.result === \"succ\") {\n resolve(res);\n } else {\n reject(res);\n }\n });\n });\n },\n createObservableQuery: async (params: any, config: any = {}) => {\n const reqid = params?.reqid || (await callSender.genReqId());\n const observable = new Observable<ResponseData<any>>(\n genSubscribe(reqid)\n );\n callSender.query(\n {\n ...params,\n reqid,\n },\n {\n ...config,\n observable: true,\n }\n );\n return observable;\n },\n } as any;\n if (callSender) {\n window.removeEventListener(NativeEventType.Message, handleMessage);\n stopConnectionTimeout();\n resolve({\n methods: proxyCallSender,\n config: event.data.config,\n });\n }\n }\n };\n\n window.addEventListener(NativeEventType.Message, handleMessage);\n\n sendSynMessage();\n\n onDestroy((error?: PenpalError) => {\n window.removeEventListener(NativeEventType.Message, handleMessage);\n\n if (error) {\n reject(error);\n }\n });\n }\n );\n\n return {\n promise,\n destroy() {\n // Don't allow consumer to pass an error into destroy.\n destroy();\n },\n };\n};\n","import { connectToOS } from \"@fn/micro-app-postmate\";\nimport { OSConfig } from \"@fn/micro-app-postmate/src/parent/type\";\nimport {\n OSMethods,\n ConnectionResult,\n AsyncMethodReturns,\n} from \"@fn/micro-app-postmate/src/types\";\nimport type { PlatformConfig, TrimAppOptions } from \"../types\";\n\nexport type OSConnection = AsyncMethodReturns<\n ConnectionResult<\n OSMethods & {\n setExitPageTips: (params?: { title?: string; content?: string }) => void;\n openFileManagerApp: (path: string) => void;\n openFile: (path: string) => void;\n getPlatformConfig: () => Promise<PlatformConfig>;\n close: () => void;\n },\n OSConfig\n >\n>;\n\nexport const initWeb = (options?: TrimAppOptions) => {\n return connectToOS({\n debug: options?.debug,\n }).promise;\n};\n","import { logger } from \"./logger\";\nimport type { PlatformConfig, TrimAppOptions } from \"./types\";\nimport type { FlutterInAppWebView } from \"./mobile/index\";\nimport { isFnApp } from \"./utils/platform\";\nimport { callHandler, initMobile } from \"./mobile/index\";\nimport { initWeb, OSConnection } from \"./web/index\";\nimport { AppMessage } from \"./mobile/types\";\nimport { ResponseData } from \"@fn/micro-app-postmate/src/child/os-type\";\nimport {\n FilePickerParams,\n QueryConfig,\n} from \"@fn/micro-app-postmate/src/child/type\";\n\n/**\n * @trim/app - NAS 应用 SDK\n * @description nas 应用 SDK\n */\n\n// 导出类型\nexport type { TrimAppOptions } from \"./types\";\n\n/**\n * Trim App 实例类\n */\nexport class TrimApp {\n private options: TrimAppOptions;\n\n private flutterInAppWebView: FlutterInAppWebView | null = null;\n private osConnector: OSConnection | null = null;\n private initPromise: Promise<void>;\n\n public isWeb: boolean = true;\n\n constructor(options: TrimAppOptions = {}) {\n this.options = options;\n\n // 设置 debug 模式\n if (options.debug) {\n logger.setDebug(true);\n logger.log(\"Trim App initialized with debug mode\");\n }\n\n logger.log(\"Options:\", options);\n\n // 保存初始化 Promise\n this.initPromise = this.init();\n }\n\n private async init(): Promise<void> {\n logger.log(\"Starting initialization...\");\n\n return new Promise((resolve) => {\n if (isFnApp()) {\n this.isWeb = false;\n logger.log(\"Initializing mobile platform...\");\n initMobile().then((flutterInAppWebView) => {\n this.flutterInAppWebView = flutterInAppWebView;\n logger.log(\"Mobile platform initialized\");\n resolve();\n });\n } else {\n this.isWeb = true;\n logger.log(\"Initializing web platform...\");\n initWeb().then((osConnector) => {\n this.osConnector = osConnector as OSConnection;\n logger.log(\"Web platform initialized\");\n resolve();\n });\n }\n });\n }\n\n public async callAppMethod<T>(\n fn: string,\n params?: string\n ): Promise<T | null> {\n if (!this.flutterInAppWebView) {\n return null;\n }\n return callHandler<T>(this.flutterInAppWebView, fn, params);\n }\n\n /**\n * 等待初始化完成\n * @returns Promise\n */\n async ready(): Promise<void> {\n return this.initPromise;\n }\n\n /**\n * 获取配置\n */\n getOptions(): TrimAppOptions {\n return this.options;\n }\n\n /**\n * 更新配置\n */\n setOptions(options: Partial<TrimAppOptions>) {\n this.options = { ...this.options, ...options };\n\n // 更新 debug 模式\n if (options.debug !== undefined) {\n logger.setDebug(options.debug);\n }\n\n logger.log(\"Options updated:\", this.options);\n }\n\n // 调用 app 的方法\n\n /**\n * 获取平台配置\n */\n async getPlatformConfig(): Promise<PlatformConfig> {\n // 等待初始化完成\n await this.initPromise;\n\n if (this.isWeb) {\n const config = await this.osConnector?.methods.getPlatformConfig();\n if (!config) {\n throw new Error(\"Failed to get platform config\");\n }\n return config;\n } else {\n const config = await this.callAppMethod<AppMessage>(\"getAppMessage\");\n if (!config) {\n throw new Error(\"Failed to get platform config\");\n }\n return {\n theme: config.nightMode as \"dark\" | \"light\",\n language: config.language,\n appVersion: config.appVersion,\n systemVersion: config.systemVersion,\n format: {\n date: config.dateFormat,\n time: config.timeFormat,\n },\n };\n }\n }\n\n /**\n * setTitle - 设置标题\n * @param title 标题文本\n */\n async setTitle(title: string) {\n // 等待初始化完成\n await this.initPromise;\n\n logger.log(\"Setting title:\", title);\n\n if (this.isWeb) {\n return this.osConnector?.methods.setTitle(title);\n } else {\n return this.callAppMethod(\"updateTitle\", title);\n }\n }\n\n /**\n * setExitPageTips - 设置退出页面提示\n * @param params 提示参数\n */\n async setExitPageTips(params?: { title?: string; content?: string }) {\n // 等待初始化完成\n await this.initPromise;\n\n if (this.isWeb) {\n return this.osConnector?.methods.setExitPageTips(params);\n } else {\n return this.callAppMethod(\n \"setExitPageTips\",\n params ? JSON.stringify(params) : \"\"\n );\n }\n }\n\n /**\n * 通过应用打开某个文件\n */\n async openFile(path: string) {\n // 等待初始化完成\n await this.initPromise;\n\n logger.log(\"Opening file:\", path);\n\n if (this.isWeb) {\n return this.osConnector?.methods.openFile(path);\n } else {\n return this.callAppMethod(\"openFile\", path);\n }\n }\n\n /**\n * 打开文件管理器\n */\n async openFileManager(path: string) {\n // 等待初始化完成\n await this.initPromise;\n\n logger.log(\"Opening file manager:\", path);\n\n if (this.isWeb) {\n return this.osConnector?.methods.openFileManagerApp(path);\n } else {\n return this.callAppMethod(\"openFileManager\", path);\n }\n }\n\n /**\n * 关闭应用\n */\n async close() {\n // 等待初始化完成\n await this.initPromise;\n if (this.isWeb) {\n return this.osConnector?.methods.close();\n } else {\n throw new Error(\"close is not supported on mobile platform\");\n }\n }\n\n /**\n * 请求接口\n */\n async query<T>(params: any, config?: QueryConfig): Promise<ResponseData<T>> {\n // 等待初始化完成\n await this.initPromise;\n if (this.isWeb) {\n const result = await this.osConnector?.methods.query<T>(params, config);\n if (!result) {\n throw new Error(\"Failed to query\");\n }\n return result;\n } else {\n throw new Error(\"query is not supported on mobile platform\");\n }\n }\n\n /**\n * 选择文件\n */\n async pickFile(params: FilePickerParams) {\n // 等待初始化完成\n await this.initPromise;\n if (this.isWeb) {\n return this.osConnector?.methods.pickFile(params);\n } else {\n return this.callAppMethod(\"openFolder\", JSON.stringify(params));\n }\n }\n}\n\n// 默认导出\nexport default TrimApp;\n"],"names":["Logger","__publicField","enabled","args","logger","fnAppUAMatch","ua","regex","matches","match","isFnApp","initMobile","res","_a","callHandler","flutterInAppWebView","fn","params","messageData","appMessage","error","fnAppMessageHandleMap","initAppMessageEvent","message","data","handle","MessageType","Resolution","ErrorCode","NativeErrorName","NativeEventType","createDestructor","localName","log","callbacks","destroyed","callback","createLogger","debug","serializeError","name","stack","deserializeError","obj","deserializedError","key","connectCallReceiver","info","serializedMethods","local","remote","originForSending","originForReceiving","handleMessageEvent","event","callMessage","methodName","id","createPromiseHandler","resolution","returnValue","err","errorReplyMessage","resolve","generateId","KEY_PATH_DELIMITER","keyPathToSegments","keyPath","segmentsToKeyPath","segments","createKeyPath","prefix","setAtKeyPath","subject","value","prevSubject","idx","serializeMethods","methods","flattenedMethods","deserializeMethods","connectCallSender","callSender","methodKeyPaths","destroyConnection","createMethodProxy","iframeRemoved","reject","replyMessage","api","startConnectionTimeout","timeout","timeoutId","handleSynAckMessageFactory","parentOrigin","config","destructor","destroy","onDestroy","ackMessage","destroyCallReceiver","destroyCallSender","warn","msg","FNAPP_ALL_EVENT","FNAPP_TIPS_NO_SUBJECT","appEventObjMap","EventBus","appName","cbs","cb","cbsLength","allCbsLength","eventObj","i","e","extendStatics","d","b","p","__extends","__","__values","o","s","m","__read","n","r","ar","__spreadArray","to","from","pack","l","isFunction","createErrorClass","createImpl","_super","instance","ctorFunc","UnsubscriptionError","errors","arrRemove","arr","item","index","Subscription","initialTeardown","e_1","e_2","_b","_parentage","_parentage_1","_parentage_1_1","parent_1","e_1_1","initialFinalizer","_finalizers","_finalizers_1","_finalizers_1_1","finalizer","execFinalizer","e_2_1","teardown","parent","empty","isSubscription","timeoutProvider","handler","_i","reportUnhandledError","noop","errorContext","Subscriber","destination","_this","EMPTY_OBSERVER","next","complete","SafeSubscriber","_bind","bind","thisArg","ConsumerObserver","partialObserver","handleUnhandledError","observerOrNext","context_1","defaultErrorHandler","observable","identity","x","pipeFromArray","fns","input","prev","Observable","subscribe","operator","subscriber","isSubscriber","source","sink","promiseCtor","getPromiseCtor","Symbol_observable","operations","isObserver","areGlobalsAccessible","connectToOS","options","sendSynMessage","synMessage","parentOriginForSyn","stopConnectionTimeout","handleMessage","bus","queryBus","proxyBus","getQueryBusEvent","reqid","genSubscribe","observer","onReqId","pkg","busFns","callSenderBus","on","once","force","proxyCallSender","initWeb","TrimApp","osConnector","title","path","result"],"mappings":"oRAIA,MAAMA,EAAO,CAAb,cACUC,EAAA,aAAiB,IAMzB,SAASC,EAAkB,CACzB,KAAK,MAAQA,CAAA,CAMf,SAAmB,CACjB,OAAO,KAAK,KAAA,CAOd,OAAOC,EAAa,CACd,KAAK,OACC,QAAA,IAAI,aAAc,GAAGA,CAAI,CACnC,CAOF,QAAQA,EAAa,CACf,KAAK,OACC,QAAA,KAAK,aAAc,GAAGA,CAAI,CACpC,CAOF,SAASA,EAAa,CAChB,KAAK,OACC,QAAA,MAAM,aAAc,GAAGA,CAAI,CACrC,CAOF,QAAQA,EAAa,CACf,KAAK,OACC,QAAA,KAAK,aAAc,GAAGA,CAAI,CACpC,CAEJ,CAGa,MAAAC,EAAS,IAAIJ,GChEnB,SAASK,GAAaC,EAAY,CACvC,MAAMC,EAAQ,sDAERC,EAAe,CAAC,EAClB,IAAAC,EACJ,MAAQA,EAAQF,EAAM,KAAKD,CAAE,KAAO,MAC9BG,EAAM,CAAC,IAAWD,EAAA,YAAcC,EAAM,CAAC,GACvCA,EAAM,CAAC,IAAWD,EAAA,UAAYC,EAAM,CAAC,GACrCA,EAAM,CAAC,IAAWD,EAAA,aAAeC,EAAM,CAAC,GAGvC,OAAAD,CACT,CAEO,MAAME,GAAU,IACdL,GAAa,UAAU,SAAS,EAAE,aCC9BM,GAAa,IAIjB,IAAI,QAA8BC,GAAQ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