UNPKG

30 kBJavaScriptView Raw
1import{Platform as e}from"react-native";import t from"promise/setimmediate/es6-extensions";import s from"promise/setimmediate/rejection-tracking";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function o(e){var t=function(e,t){if("object"!=n(e)||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var o=s.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==n(t)?t:t+""}function r(e,t,s){return(t=o(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function i(){return Math.random().toString(36).slice(2)}function a(e){return Object.prototype.toString.call(e)}function c(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function l(e){return"string"==typeof e}function u(e){return"[object BigInt]"===a(e)}function h(e){return e instanceof Array}function p(e){return"object"==typeof e&&null!==e}function d(e){return e instanceof Blob}function g(e){return e instanceof URLSearchParams}function f(e){return e instanceof FormData}function m(e){return e instanceof File}function y(e){return e instanceof Document}const v=e=>"".concat(e),b=e=>({ok:!0,value:e});function S(e){return void 0===e?b(v(e)):null===e?b(e):function(e){return"number"==typeof e}(e)&&(e===-1/0||e===1/0||Number.isNaN(e))?b(v(e)):u(e)?b("".concat(e,"n")):"symbol"==typeof e||"function"==typeof e?b(v(e.toString())):e instanceof Error?b(v(e.stack)):e===Object.prototype?{value:null,ok:!1}:e instanceof Object||"object"==typeof e?{value:e,ok:!1}:b(e)}function T(e){const{ok:t,value:s}=S(e);return t?s:JSON.stringify(e,((e,t)=>S(t).value),2)}function w(e){return void 0===e?"undefined":null===e?"null":u(e)?"bigint":e instanceof Object?e instanceof Error?"error":"function"==typeof e?"function":"object":typeof e}const E=Object.assign({},console),R=["log","info","error","warn","debug"].reduce(((e,t)=>(e[t]=function(){for(var e=arguments.length,s=new Array(e),n=0;n<e;n++)s[n]=arguments[n];console[t]("[PageSpy] [".concat(t.toLocaleUpperCase(),"] "),...s)},e.unproxy[t]=function(){for(var e=arguments.length,s=new Array(e),n=0;n<e;n++)s[n]=arguments[n];E[t]("[PageSpy] [".concat(t.toLocaleUpperCase(),"] "),...s)},e)),{unproxy:{}});const O=e=>new Promise(((t,s)=>{const n=new FileReader;n.onload=e=>{var s;t(null===(s=e.target)||void 0===s?void 0:s.result)},n.onerror=()=>{s(new Error("blob2base64Async: can not convert"))},n.readAsDataURL(e)})),I="message",C="broadcast",P="ping",q="updateRoomInfo";var k=Object.freeze({__proto__:null,BROADCAST:C,CLOSE:"close",CONNECT:"connect",ERROR:"error",JOIN:"join",LEAVE:"leave",MESSAGE:I,PING:P,PONG:"pong",UPDATE_ROOM_INFO:q});function x(e,t){let s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return{role:"client",type:e,data:Object.assign(Object.assign({},s&&{id:i()}),t)}}class j{constructor(e){this.id="",this.method="",this.url="",this.requestType="xhr",this.requestHeader=null,this.status=0,this.statusText="",this.readyState=0,this.responseReason=null,this.responseType="",this.responseHeader=null,this.startTime=0,this.endTime=0,this.costTime=0,this.postData=null,this.requestPayload=null,this.withCredentials=!1,this.id=e}}function N(e,t,s,n){return new(s||(s=Promise))((function(o,r){function i(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const H=2097152,L="Exceed maximum limit";var M;!function(e){e[e.UNSENT=0]="UNSENT",e[e.OPENED=1]="OPENED",e[e.HEADERS_RECEIVED=2]="HEADERS_RECEIVED",e[e.LOADING=3]="LOADING",e[e.DONE=4]="DONE"}(M||(M={}));const D="(file)";const A="Content-Type";function U(e,t){if(!t)return e;const s=(n=t)?f(n)?"multipart/form-data":g(n)?"application/x-www-form-urlencoded;charset=UTF-8":y(n)?"application/xml":d(n)?n.type:"text/plain;charset=UTF-8":null;var n;if(!s)return e;const o=[A,s];if(!e)return[o];for(let t=0;t<e.length;t++){const[s]=e[t];if(s.toUpperCase()===A.toUpperCase())return e}return[...e,o]}function G(e){return N(this,void 0,void 0,(function*(){if(!e)return null;if(g(e)||f(e))return function(e){const t=[];let s=e.next();for(;!s.done;){const[n,o]=s.value;let r;r=m(o)?D:String(o),t.push([n,r]),s=e.next()}return t}(e.entries());if(d(e))return"[object Blob]";if(t=e,ArrayBuffer.isView(t))return"[object TypedArray]";var t;if(y(e)){return(new XMLSerializer).serializeToString(e)}return l(e)?e:a(e)}))}class _{constructor(e){this.socketStore=e,this.reqMap=Object.create(null)}getRequestMap(){return this.reqMap}getRequest(e){return this.reqMap[e]}removeRequest(e){delete this.reqMap[e]}createRequest(e){return e?this.reqMap[e]?(R.warn("The request object has been in store, disallow duplicate create"),!1):(this.reqMap[e]=new j(e),!0):(R.warn('The "id" is required when init request object'),!1)}setRequest(e,t){return!(!e||!t)&&(this.reqMap[e]=t,!0)}sendRequestItem(e,t){var s;if(!1!==(null===(s=_.dataProcessor)||void 0===s?void 0:s.call(_,t)))try{this.reqMap[e]||(this.reqMap[e]=t);const s=x("network",Object.assign({},t),!1);this.socketStore.dispatchEvent("public-data",s),this.socketStore.broadcastMessage(s,t.readyState!==M.DONE),this.deferDeleteRequest(e)}catch(e){R.error(e.message)}}deferDeleteRequest(e){const t=this.getRequest(e);t&&t.readyState===M.DONE&&setTimeout((()=>{delete this.reqMap[e]}),3e3)}}class W{constructor(){this.store={},this.instanceStore={}}getStore(){return this.store}resetStore(){this.store={}}getInstanceStore(){return this.instanceStore}resetInstanceStore(){this.instanceStore={}}transformToAtom(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const{value:s,ok:n}=S(e),o=i();if(n)return{id:o,type:w(e),value:s};if(t)try{return{id:o,type:"json",value:JSON.stringify(e)}}catch(e){return{id:o,type:"json",value:null}}return this.add(e)}get(e){const t=this.store[e],s=this.instanceStore[e];if(!t)return null;const n={},o=Object.getOwnPropertyDescriptors(t);Object.keys(o).forEach((e=>{const t=o[e];c(t,"value")&&(t.value=this.transformToAtom(t.value)),n[e]=W.getAtomOverview({atomId:i(),instanceId:s,value:t})}));const r=this.addExtraProperty(e);return Object.assign(Object.assign({},n),r)}getOrigin(e){const t=this.store[e];return t||null}add(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";const s=i();let n=s;var o;p(o=e)&&c(o,"constructor")&&"function"==typeof o.constructor&&(n=t),this.store[s]=e,this.instanceStore[s]=n;const r=W.getSemanticValue(e);return W.getAtomOverview({atomId:s,value:r,instanceId:n})}static getAtomOverview(e){let{instanceId:t="",atomId:s,value:n}=e;return{id:i(),type:"atom",__atomId:s,instanceId:t,value:n}}static getSemanticValue(e){if(p(t=e)&&"[object Object]"===a(t))return"Object {...}";var t;if(h(e))return"Array (".concat(e.length,")");return e.constructor.name}addExtraProperty(e){const t=this.store[e],s=this.instanceStore[e],n={};if((t instanceof String||t instanceof Number||t instanceof Boolean)&&(n["[[PrimitiveValue]]"]=this.transformToAtom(t.valueOf())),t instanceof Set){const e={};let s=0;for(const n of t)e[s++]=n;e.size=t.size,n["[[Entries]]"]=this.transformToAtom(e)}if(t instanceof Map){const e={};let s=0;for(const[n,o]of t.entries())e[s++]={key:n,value:o};e.size=t.size,n["[[Entries]]"]=this.transformToAtom(e)}var o;return(h(t)||(o=t,"function"==typeof NodeList&&"NodeList"===NodeList.name&&o instanceof NodeList||"function"==typeof HTMLCollection&&"HTMLCollection"===HTMLCollection.name&&o instanceof HTMLCollection))&&(n.length=this.transformToAtom(t.length)),null!==Object.getPrototypeOf(t)?n["[[Prototype]]"]=this.add(Object.getPrototypeOf(t),s):n.___proto___=this.transformToAtom(null),n}}const V=new W;class F{static makeClientInfoMsg(){return{sdk:F.info.sdk,isDevTools:F.info.isDevTools,ua:F.getName(),plugins:F.plugins}}static getName(){if(!F._name){const{ua:e,osType:t,osVersion:s,browserType:n,browserVersion:o}=F.info;F._name=e||"".concat(t,"/").concat(s," ").concat(n,"/").concat(o)}return F._name}}F.info={osType:"unknown",osVersion:"unknown",browserType:"unknown",browserVersion:"unknown",framework:"unknown",isDevTools:!1,sdk:"browser"},F.plugins=[];class B{defaultConfig(){return{}}constructor(){this.mergeConfig=e=>{const t=Object.entries(e).reduce(((e,t)=>{let[s,n]=t;return this.privateKeys.includes(s)||(e[s]=n),e}),{});return this.value=Object.assign(Object.assign({},this.defaultConfig()),t),this.value},this.value=this.defaultConfig()}get(){return this.value}set(e,t){this.value[e]=t}}var X;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.OPEN=1]="OPEN",e[e.CLOSING=2]="CLOSING",e[e.CLOSED=3]="CLOSED"}(X||(X={}));const z=2e3,$=Math.pow(1.5,4)*z;class J{constructor(){this.events={open:[],close:[],error:[],message:[]}}emit(e,t){this.events[e].forEach((e=>{e(t)})),"close"!==e&&"error"!==e||this.clearListeners()}onOpen(e){this.events.open.push(e)}onClose(e){this.events.close.push(e)}onError(e){this.events.error.push(e)}onMessage(e){this.events.message.push(e)}clearListeners(){Object.entries(this.events).forEach((e=>{let[,t]=e;t.splice(0)}))}}class K{getSocket(){return this.socketWrapper}updateRoomInfo(){if(this.getPageSpyConfig){const{project:e,title:t}=this.getPageSpyConfig(),s=F.getName();this.send({type:q,content:{info:{name:s,group:e,tags:{title:t,name:s,group:e}}}},!0)}}constructor(){this.socketUrl="",this.socketConnection=null,this.debuggerConnection=null,this.pingTimer=null,this.pongTimer=null,this.retryTimer=null,this.isOffline=!1,this.messageCapacity=0,this.messages=[],this.events={debug:[],refresh:[],"atom-detail":[],"atom-getter":[],"debugger-online":[],"database-pagination":[],"public-data":[],"harbor-clear":[]},this.retryInterval=z,this.connectable=!0,this.getPageSpyConfig=null,this.addListener("atom-detail",K.handleResolveAtom),this.addListener("atom-getter",K.handleAtomPropertyGetter),this.addListener("debugger-online",this.handleFlushBuffer)}init(e){return N(this,void 0,void 0,(function*(){var t,s,n,o,r;try{if(!e)throw Error("WebSocket url cannot be empty");this.socketWrapper.clearListeners(),this.socketWrapper.getState()===X.OPEN&&(yield new Promise((e=>{this.socketWrapper.onClose((()=>{this.socketWrapper.clearListeners(),e()})),this.socketWrapper.close()}))),null===(t=this.socketWrapper)||void 0===t||t.onOpen((()=>{this.connectOnline()})),null===(s=this.socketWrapper)||void 0===s||s.onMessage((e=>{this.handleMessage(e)})),null===(n=this.socketWrapper)||void 0===n||n.onClose((()=>{this.connectOffline()})),null===(o=this.socketWrapper)||void 0===o||o.onError((()=>{this.connectOffline()})),this.socketUrl=e,null===(r=this.socketWrapper)||void 0===r||r.init(e)}catch(e){R.error(e.message)}}))}addListener(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}removeListener(e,t){const s=this.events[e]||[],n=s.indexOf(t);n>-1&&s.splice(n,1)}broadcastMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const s=function(e){return{type:C,content:{data:e}}}(e);this.send(s,t)}close(){var e;this.connectable=!1,this.clearPing(),null===(e=this.socketWrapper)||void 0===e||e.close(),this.messages=[],Object.entries(this.events).forEach((e=>{let[t,s]=e;["atom-detail","atom-getter","debugger-online"].includes(t)||s.splice(0)}))}connectOnline(){this.retryInterval=z,this.updateRoomInfo(),this.ping()}connectOffline(){this.socketConnection=null,this.debuggerConnection=null,this.clearPing(),this.retryTimer&&clearTimeout(this.retryTimer),this.connectable&&(this.retryTimer=setTimeout((()=>{this.retryInterval<$&&(this.retryInterval*=1.5),this.retryTimer=null,this.tryReconnect()}),this.retryInterval))}tryReconnect(){this.init(this.socketUrl)}ping(){this.pingTimer&&clearTimeout(this.pingTimer),this.pongTimer&&clearTimeout(this.pongTimer),this.pingTimer=setTimeout((()=>{this.send({type:"ping",content:null}),this.pingTimer=null,this.pongTimer=setTimeout((()=>{this.connectOffline(),this.pongTimer=null}),5e3)}),5e3)}clearPing(){this.pingTimer&&(clearTimeout(this.pingTimer),this.pingTimer=null),this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handlePong(){clearTimeout(this.pongTimer),this.pongTimer=null,this.ping()}handleMessage(e){var t;K.messageFilters.length&&K.messageFilters.forEach((t=>{e=t(e)}));const{CONNECT:s,MESSAGE:n,ERROR:o,JOIN:r,PING:i,PONG:a,LEAVE:c,CLOSE:l,BROADCAST:u}=k,h=JSON.parse(e.data),{type:p}=h;switch(p){case s:const{selfConnection:e,roomConnections:i}=h.content;this.socketConnection=e,this.debuggerConnection=i.find((e=>"Debugger"===e.userId))||null;break;case r:case c:const{connection:a}=h.content;"Debugger"===a.userId&&(p===r?(this.debuggerConnection=a,this.sendClientInfo()):this.debuggerConnection=null);break;case n:const{data:u,from:d,to:g}=h.content;g.address===(null===(t=this.socketConnection)||void 0===t?void 0:t.address)&&this.dispatchEvent(u.type,{source:u,from:d,to:g});break;case l:case o:this.connectOffline()}this.handlePong()}dispatchEvent(e,t){var s;["public-data"].includes(e)?this.events["public-data"].forEach((e=>{e(t)})):null===(s=this.events[e])||void 0===s||s.forEach((e=>{e.call(this,t,(e=>{this.unicastMessage(e,t.from)}))}))}unicastMessage(e,t){const s=function(e,t,s){return{type:I,content:{data:e,from:t,to:s}}}(e,this.socketConnection,t);this.send(s)}handleFlushBuffer(e){const{latestId:t}=e.source.data,s=this.messages.findIndex((e=>e.content.data.data.id===t));this.messages.slice(s+1).forEach((t=>{const s={type:I,content:{data:t.content.data,from:this.socketConnection,to:e.from}};this.send(s,!0)}))}static handleResolveAtom(e,t){let{source:s}=e;const{type:n,data:o}=s;if("atom-detail"===n){const e=V.get(o)||{};t(x("atom-detail-".concat(o),e,!1))}}static handleAtomPropertyGetter(e,t){let{source:s}=e;var n,o;const{type:r,data:i}=s;if("atom-getter"===r){const{id:e,parentId:s,key:r,instanceId:a}=i,c=V.getOrigin(a),l=V.getOrigin(s);let u={};u=c&&l?null===(o=null===(n=Object.getOwnPropertyDescriptor(l,r))||void 0===n?void 0:n.get)||void 0===o?void 0:o.call(c):new Error("Getter computed failed");t(x("atom-getter-".concat(e),V.transformToAtom(u)))}}send(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var s;if(this.checkIfSend(e))try{const t=e;t.createdAt=Date.now(),t.requestId=i();const n=T(t);null===(s=this.socketWrapper)||void 0===s||s.send(n)}catch(e){R.error("Incompatible: ".concat(e.message)),this.connectOffline()}this.checkIfCache(e,t)&&(0!==this.messageCapacity&&this.messages.length>=this.messageCapacity&&this.messages.shift(),this.messages.push(e))}checkIfSend(e){return this.socketWrapper.getState()===X.OPEN&&(!![q,P].includes(e.type)||!!this.debuggerConnection)}checkIfCache(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return!this.isOffline&&!t&&![I,P].includes(e.type)}sendClientInfo(){const e=F.makeClientInfoMsg();this.broadcastMessage({role:"client",type:"client-info",data:e},!0)}}K.messageFilters=[];class Q extends J{constructor(){super(...arguments),r(this,"socketInstance",null)}init(e){this.socketInstance=new WebSocket(e);["open","close","error","message"].forEach((e=>{this.socketInstance.addEventListener(e,(t=>{this.events[e].forEach((e=>{e(t)}))}))}))}send(e){var t;null===(t=this.socketInstance)||void 0===t||t.send(T(e))}close(){var e;null===(e=this.socketInstance)||void 0===e||e.close()}getState(){var e;return null===(e=this.socketInstance)||void 0===e?void 0:e.readyState}}const Y=new class extends K{onOffline(){}constructor(){super(),r(this,"socketWrapper",new Q)}};class Z{constructor(){r(this,"name","ConsolePlugin"),r(this,"console",{}),r(this,"proxyTypes",["log","info","error","warn","debug"]),r(this,"$pageSpyConfig",null)}async onInit(e){let{config:t}=e;Z.hasInitd||(Z.hasInitd=!0,Y.addListener("debug",Z.handleDebugger),this.$pageSpyConfig=t,this.init())}init(){const e=this;this.proxyTypes.forEach((t=>{this.console[t]=console[t]||console.log||(()=>{}),Object.defineProperty(console,t,{value(){for(var s=arguments.length,n=new Array(s),o=0;o<s;o++)n[o]=arguments[o];e.printLog({logType:t,logs:n,url:""})},configurable:!0,enumerable:!0,writable:!0})}))}reset(){this.proxyTypes.forEach((e=>{console[e]=this.console[e]}))}onReset(){this.reset(),Z.hasInitd=!1}static handleDebugger(e,t){let{source:s}=e;const{type:n,data:o}=s;if("debug"===n){t(x("console",{logType:"debug-origin",logs:[{id:i(),type:"debug-origin",value:o}]}));try{const e=new Function("return ".concat(o))();t(x("console",{logType:"debug-eval",logs:[V.transformToAtom(e)]}))}catch(e){t(x("console",{logType:"error",logs:[{type:"error",value:e.stack}]}))}}}printLog(e){if(e.logs&&e.logs.length){var t,s;const n=null===(t=this.$pageSpyConfig)||void 0===t||null===(t=t.dataProcessor)||void 0===t?void 0:t.console;if(n){this.reset();const t=n(e);if(this.init(),!1===t)return}this.console[e.logType](...e.logs);const o=x("console",{...e,time:Date.now(),logs:e.logs.map((e=>V.transformToAtom(e,!1)))});if(Y.broadcastMessage(o),null!==(s=this.$pageSpyConfig)&&void 0!==s&&s.serializeData){const t={...o,data:{...o.data,logs:e.logs.map((e=>V.transformToAtom(e,!0)))}};Y.dispatchEvent("public-data",t)}else Y.dispatchEvent("public-data",o)}}}r(Z,"hasInitd",!1);class ee{constructor(){r(this,"name","ErrorPlugin"),r(this,"originHandler",null),r(this,"originPromise",null),r(this,"$pageSpyConfig",null)}onInit(e){let{config:t}=e;ee.hasInitd||(ee.hasInitd=!0,this.$pageSpyConfig=t,this.onUncaughtError(),this.onUnhandledRejectionError())}onUncaughtError(){const e=ErrorUtils.getGlobalHandler();e&&(this.originHandler=e),ErrorUtils.setGlobalHandler(((t,s)=>{this.errorHandler(t),e&&e(t,s)}))}onUnhandledRejectionError(){ee.hasInitd&&(this.originPromise=global.Promise,global.Promise=t,s.enable({allRejections:!0,onUnhandled:(e,t)=>{this.errorHandler(t),console.warn("Possible Unhandled Promise Rejection (id: "+e+"):");((t&&(t.stack||t))+"").split("\n").forEach((e=>{console.warn(" "+e)}))}}))}errorHandler(e){if(ee.hasInitd)if(e.message||e.stack){const t=(e=>{if("object"!=typeof e)return null;const{name:t,message:s,stack:n}=Object(e);return!1===[t,s,n].every(Boolean)?null:{name:t,message:s,stack:n}})(e);this.sendMessage(e.stack||e.message,t)}else if("string"==typeof e)this.sendMessage(e,null);else{const t="[PageSpy] An unknown error occurred and no message or stack trace available";this.sendMessage(t,e)}}onReset(){ee.hasInitd&&(this.originHandler&&ErrorUtils.setGlobalHandler(this.originHandler),this.originPromise&&(global.Promise=this.originPromise),ee.hasInitd=!1)}sendMessage(e,t){var s,n;const o={logType:"error",logs:[e],time:Date.now(),url:"",errorDetail:t};if(!1===(null===(s=this.$pageSpyConfig)||void 0===s||null===(s=s.dataProcessor)||void 0===s||null===(n=s.console)||void 0===n?void 0:n.call(s,o)))return;o.logs=o.logs.map((e=>V.transformToAtom(e)));const r=x("console",o);Y.dispatchEvent("public-data",r),Y.broadcastMessage(r)}}r(ee,"hasInitd",!1);class te extends _{constructor(){super(Y)}}const se="page-spy-is-fetch";class ne extends te{constructor(){super(),r(this,"xhrOpen",null),r(this,"xhrSend",null),r(this,"xhrSetRequestHeader",null),this.initProxyHandler()}initProxyHandler(){const e=this,{open:t,send:s,setRequestHeader:n}=XMLHttpRequest.prototype;this.xhrOpen=t,this.xhrSend=s,this.xhrSetRequestHeader=n,XMLHttpRequest.prototype.open=function(){for(var s=arguments.length,n=new Array(s),o=0;o<s;o++)n[o]=arguments[o];const r=n[0],a=n[1],c=i();return e.createRequest(c),this.pageSpyRequestId=c,this.pageSpyRequestMethod=r,this.pageSpyRequestUrl=a,t.apply(this,n)},XMLHttpRequest.prototype.setRequestHeader=function(t,s){if(t===se)return this.isFetch=!0,void e.removeRequest(this.pageSpyRequestId);const o=e.getRequest(this.pageSpyRequestId);o?(o.requestHeader||(o.requestHeader=[]),o.requestHeader.push([t,s])):this.isFetch||R.warn("The request object is not found on XMLHttpRequest's setRequestHeader event"),n.apply(this,[t,s])},XMLHttpRequest.prototype.send=function(t){const n=this,{pageSpyRequestId:o,pageSpyRequestMethod:r="GET",pageSpyRequestUrl:i=""}=n,a=e.getRequest(o);return n.addEventListener("readystatechange",(async()=>{if(a){switch(a.readyState=n.readyState,n.readyState){case n.UNSENT:case n.OPENED:a.status=n.status,a.statusText="Pending",a.startTime||(a.startTime=Date.now());break;case n.HEADERS_RECEIVED:a.status=n.status,a.statusText="Loading";const s=(n.getAllResponseHeaders()||"").trim().split(/[\r\n]+/);a.responseHeader=s.reduce(((e,t)=>{const[s,...n]=t.split(": ");return e.push([s,n.join(": ")]),e}),[]);break;case n.LOADING:a.status=n.status,a.statusText="Loading";break;case n.DONE:a.status=n.status,a.statusText="Done",a.endTime=Date.now(),a.costTime=a.endTime-(a.startTime||a.endTime);let{responseType:o}=n;if(!o||n.isFetch&&"blob"===o){const e=n.getResponseHeader("content-type");e&&(e.includes("application/json")&&(o="json"),(e.includes("text/html")||e.includes("text/plain"))&&(o="text"))}o||(o="blob"),a.responseType=o;const r=await e.formatResponse(n,o);(t=r,Object.keys(t)).forEach((e=>{a[e]=r[e]}));break;default:a.status=n.status,a.statusText="Unknown"}e.sendRequestItem(n.pageSpyRequestId,a)}else this.isFetch||R.warn("The request object is not found on XMLHttpRequest's readystatechange event");var t})),a?(a.url=new URL(i).toString(),a.method=r.toUpperCase(),a.requestType="xhr",a.withCredentials=n.withCredentials,"GET"!==a.method&&(a.requestHeader=U(a.requestHeader,t),G(t).then((t=>{a.requestPayload=t,e.sendRequestItem(n.pageSpyRequestId,a)})))):this.isFetch||R.warn("The request object is not found on XMLHttpRequest's send event"),s.apply(n,[t])}}reset(){this.xhrOpen&&(XMLHttpRequest.prototype.open=this.xhrOpen),this.xhrSend&&(XMLHttpRequest.prototype.send=this.xhrSend),this.xhrSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.xhrSetRequestHeader)}async formatResponse(e,t){const s={response:"",responseReason:null};switch(t){case"":case"text":if(l(e.response))try{s.response=JSON.parse(e.response)}catch(t){s.response=e.response}else void 0!==e.response&&(s.response=a(e.response));break;case"json":void 0!==e.response&&(s.response=e.response);break;case"blob":case"arraybuffer":if(e.response){let t=e.response;if(t instanceof ArrayBuffer){const s=e.getResponseHeader("content-type");s&&(t=new Blob([t],{type:s}))}if(d(t))if(t.size<=H)try{s.response=await O(t)}catch(e){s.response=await t.text(),R.error(e.message)}else s.response="[object Blob]",s.responseReason=L}break;default:void 0!==e.response&&(s.response=Object.prototype.toString.call(e.response))}return s}}class oe extends te{constructor(){super(),r(this,"fetch",null),this.initProxyHandler()}reset(){this.fetch&&(globalThis.fetch=this.fetch)}initProxyHandler(){const e=this,t=globalThis.fetch;t&&(this.fetch=t,globalThis.fetch=function(s){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=t(s,{...n,headers:{[se]:"true",...n.headers}}),r=i();e.createRequest(r);const a=e.getRequest(r);if(a){let t,i="GET",c=null;l(s)||s instanceof URL?(i=n.method||"GET",t=s,c=n.headers||null):(i=s.method,t=s.url,c=s.headers),a.url=new URL(t).toString(),a.method=i.toUpperCase(),a.requestType="fetch",a.status=0,a.statusText="Pending",a.startTime=Date.now(),a.readyState=XMLHttpRequest.UNSENT,n.credentials&&"omit"!==n.credentials&&(a.withCredentials=!0),!function(e){return e instanceof Headers}(c)?p(c)?a.requestHeader=Object.entries(c):a.requestHeader=c:a.requestHeader=[...c.entries()],"GET"!==a.method&&(a.requestHeader=U(a.requestHeader,n.body),G(n.body).then((t=>{a.requestPayload=t,e.sendRequestItem(r,a)}))),e.sendRequestItem(r,a),o.then((t=>{a.endTime=Date.now(),a.costTime=a.endTime-(a.startTime||a.endTime),a.status=t.status||200,a.statusText=t.statusText||"Done",a.responseHeader=[...t.headers.entries()],a.readyState=XMLHttpRequest.HEADERS_RECEIVED,e.sendRequestItem(r,a);const s=t.headers.get("content-type");if(s){if(s.includes("application/json"))return a.responseType="json",t.clone().text();if(s.includes("text/html")||s.includes("text/plain"))return a.responseType="text",t.clone().text()}return a.responseType="blob",t.clone().blob()})).then((async t=>{switch(a.responseType){case"text":case"json":try{a.response=JSON.parse(t)}catch(e){a.response=t,a.responseType="text"}break;case"blob":const e=t;if(e.size<=H)try{a.response=await O(e)}catch(t){a.response=await e.text(),R.error(t.message)}else a.response="[object Blob]",a.responseReason=L}a.readyState=XMLHttpRequest.DONE,e.sendRequestItem(r,a)}))}else R.warn("The request object is not found on global.fetch event");return o})}}class re{constructor(){r(this,"name","NetworkPlugin"),r(this,"xhrProxy",null),r(this,"fetchProxy",null)}onInit(e){let{config:t}=e;re.hasInitd||(re.hasInitd=!0,_.dataProcessor=t.dataProcessor.network,this.fetchProxy=new oe,this.xhrProxy=new ne)}onReset(){var e,t;null===(e=this.fetchProxy)||void 0===e||e.reset(),null===(t=this.xhrProxy)||void 0===t||t.reset(),re.hasInitd=!1}}r(re,"hasInitd",!1);class ie{constructor(){r(this,"name","SystemPlugin"),r(this,"$pageSpyConfig",null)}onInit(e){let{config:t}=e;ie.hasInitd||(ie.hasInitd=!0,this.$pageSpyConfig=t,this.onceInitPublicData(),Y.addListener("refresh",((e,t)=>{let{source:s}=e;const{data:n}=s;if("system"===n){const e=this.getSystemInfo();if(null===e)return;t(e)}})))}onceInitPublicData(){const e=this.getSystemInfo();null!==e&&Y.dispatchEvent("public-data",e)}onReset(){ie.hasInitd=!1}getSystemInfo(){var e,t;const s={system:{ua:F.getName()},features:{}};return!1===(null===(e=this.$pageSpyConfig)||void 0===e||null===(e=e.dataProcessor)||void 0===e||null===(t=e.system)||void 0===t?void 0:t.call(e,s))?null:x("system",s)}}r(ie,"hasInitd",!1);const ae=e=>{const t=[];return Object.entries(e).forEach((e=>{let[s,n]=e;t.push("".concat(s,"=").concat(n))})),t.join("&")};class ce{constructor(e){if(this.config=e,!e.get().api)throw Error("The api base url cannot be empty")}get base(){return this.config.get().api}getScheme(){return this.config.get().enableSSL?["https://","wss://"]:["http://","ws://"]}createRoom(){const e=this.config.get(),t=!1===e.enableSSL?["http://","ws://"]:["https://","wss://"];const s=F.getName(),n=ae({name:encodeURIComponent(s),group:e.project,title:e.title});return fetch("".concat(t[0]).concat(this.base,"/api/v1/room/create?").concat(n),{method:"POST"}).then((e=>e.json())).then((e=>{const{name:t,address:s}=e.data||{};return{roomUrl:this.getRoomUrl(s),address:s,name:t}})).catch((e=>{throw Error("Request create room failed: ".concat(e.message))}))}getRoomUrl(e){const t=this.getScheme(),{useSecret:s,secret:n}=this.config.get();return"".concat(t[1]).concat(this.base,"/api/v1/ws/room/join?").concat(ae({address:e,name:"client:".concat(i()),userId:"Client",forceCreate:!0,useSecret:s,secret:n}))}}class le extends B{constructor(){super(...arguments),r(this,"privateKeys",["secret"])}defaultConfig(){return{api:"",project:"default",title:"",enableSSL:!0,disabledPlugins:[],useSecret:!1,secret:"",messageCapacity:0,serializeData:!1,dataProcessor:{}}}}const ue=e.constants.reactNativeVersion;F.info.osType={android:"android",ios:"ios",windows:"windows",macos:"mac",web:"unknown"}[e.OS]||"unknown",F.info.osVersion=String(e.Version),F.info.browserType="react-native",F.info.browserVersion="".concat(ue.major,".").concat(ue.minor,".").concat(ue.patch).concat(ue.prerelease?"-"+ue.prerelease:""),F.info.framework="react-native",F.info.sdk="rn";class he{static get pluginsWithOrder(){return[...he.plugins.pre,...he.plugins.normal,...he.plugins.post]}static registerPlugin(e){if(!e)return;if("function"==typeof(t=e)&&void 0!==t.prototype)return void R.error("PageSpy.registerPlugin() expect to pass an instance, not a class");var t;if(!e.name)return void R.error("The ".concat(e.constructor.name,' plugin should provide a "name" property'));if(he.pluginsWithOrder.some((t=>t.name===e.name)))return void R.error("The ".concat(e.name,' has registered. Consider the following reasons:\n - Duplicate register one same plugin;\n - Plugin\'s "name" conflict with others, you can print all registered plugins by "PageSpy.plugins";'));he.plugins[e.enforce||"normal"].push(e)}constructor(e){if(r(this,"version","1.9.8"),r(this,"request",null),r(this,"name",""),r(this,"address",""),r(this,"roomUrl",""),r(this,"socketStore",Y),r(this,"config",new le),he.instance)return R.warn("Cannot initialize PageSpy multiple times"),he.instance;const t=this.config.mergeConfig(e);this.request=new ce(this.config),this.updateConfiguration(),he.instance=this,this.triggerPlugins("onInit",{socketStore:Y,config:t}),this.init()}updateConfiguration(){const{messageCapacity:e,useSecret:t}=this.config.get();if(!0===t){const e=function(){const e=Math.floor(1e6*Math.random());return String(e).padStart(6,"0")}();this.config.set("secret",e),R.log("Room Secret: ".concat(e))}Y.connectable=!0,Y.getPageSpyConfig=()=>this.config.get(),Y.messageCapacity=e}triggerPlugins(e){for(var t=arguments.length,s=new Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];const{disabledPlugins:o}=this.config.get();he.pluginsWithOrder.forEach((t=>{var n;h(o)&&o.length&&o.includes(t.name)||null===(n=t[e])||void 0===n||n.apply(t,s)}))}async init(){await this.createNewConnection(),R.log("Plugins inited")}abort(){this.triggerPlugins("onReset"),Y.close(),he.instance=null}async createNewConnection(){if(!this.request)return void R.error("Cannot get the Request");const e=await this.request.createRoom();this.name=e.name,this.address=e.address,this.roomUrl=e.roomUrl,Y.init(e.roomUrl)}updateRoomInfo(e){if(!e)return;const{project:t,title:s}=e;t&&this.config.set("project",String(t)),s&&this.config.set("title",String(s)),Y.updateRoomInfo()}}r(he,"plugins",{pre:[],normal:[],post:[]}),r(he,"instance",null);[new Z,new ee,new re,new ie].forEach((e=>{he.registerPlugin(e)}));export{he as default};
2//# sourceMappingURL=index.min.js.map