@jolibox/sdk 1.1.4-beta.10 → 1.1.4-beta.11
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/.rush/temp/package-deps_build.json +5 -3
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/dist/utils/env.d.ts +1 -0
- package/dist/utils/event-tracker.d.ts +5 -0
- package/package.json +3 -3
- package/sdk.build.log +4 -4
- package/src/events.ts +28 -2
- package/src/loader/h5.ts +7 -6
- package/src/utils/env.ts +1 -0
- package/src/utils/event-tracker.ts +126 -0
|
@@ -4,15 +4,15 @@
|
|
|
4
4
|
"packages/sdk/.eslintrc.js": "c11c589d14fe58bf4d37d259d8323b193bab6092",
|
|
5
5
|
"packages/sdk/README.md": "5660cd88848b7a5428394cc34d881a35dd402188",
|
|
6
6
|
"packages/sdk/esbuild.config.js": "7eacca35e51bf3e2face4112b3cfa76777e7c0d5",
|
|
7
|
-
"packages/sdk/package.json": "
|
|
7
|
+
"packages/sdk/package.json": "3cc2f6c061510653e789c1aebd19bfe4de00657a",
|
|
8
8
|
"packages/sdk/src/api/__tests__/canIUse.test.ts": "300e4de3768f9510e956050d326d4977bc621f34",
|
|
9
9
|
"packages/sdk/src/api/can-i-use.ts": "4fd7efe21419d39e535584d7ab8e6a3c4e186877",
|
|
10
10
|
"packages/sdk/src/api/get-system-info.ts": "c73be9f62c7055093effadaf6c48c54d6f383542",
|
|
11
11
|
"packages/sdk/src/api/index.ts": "3b4493aba6d4d842031040be7ce72607009e0665",
|
|
12
12
|
"packages/sdk/src/api/login.ts": "747c923c87175b467c17e303a14210bf0ab7a1cb",
|
|
13
|
-
"packages/sdk/src/events.ts": "
|
|
13
|
+
"packages/sdk/src/events.ts": "37cd254da847a1ebd6de894813379b4378a694b9",
|
|
14
14
|
"packages/sdk/src/index.ts": "a772c24e370f183dba0c5346004f41dac6cb6807",
|
|
15
|
-
"packages/sdk/src/loader/h5.ts": "
|
|
15
|
+
"packages/sdk/src/loader/h5.ts": "d28b611500754d30e2fcf4aaa55389a80dc02bd9",
|
|
16
16
|
"packages/sdk/src/loader/index.ts": "2fd698718dd7bad9fda8fa5a5f54d4d7bd209cb3",
|
|
17
17
|
"packages/sdk/src/loader/native.ts": "b250d460509f67b4544e5ca4d5f35f8dd20373c4",
|
|
18
18
|
"packages/sdk/src/loader/version.ts": "8b584cf9c97198b6b6d1f728cc49f56260d7c02e",
|
|
@@ -24,6 +24,8 @@
|
|
|
24
24
|
"packages/sdk/src/sdks/storage.ts": "e04fca273b640f2e1dfcc70f23eaa537145c3f36",
|
|
25
25
|
"packages/sdk/src/sdks/task.ts": "07f5296dd999470d8d378487fd6f2a39a3f3d8ed",
|
|
26
26
|
"packages/sdk/src/utils/can-i-use.ts": "10993f013cf26c07b60fe60fb7b458bbd6847244",
|
|
27
|
+
"packages/sdk/src/utils/env.ts": "d2e3db934d24a3b687de1f2df04fed7a5467e161",
|
|
28
|
+
"packages/sdk/src/utils/event-tracker.ts": "fde5019dad1331b0131225e613457b4cf4a227df",
|
|
27
29
|
"packages/sdk/src/utils/report.ts": "d928d7456a5ba829216c41ea5b66afff6627c6be",
|
|
28
30
|
"packages/sdk/tsconfig.json": "0ecd9cf2b93d09e0376a098b5b662820bafcf7eb"
|
|
29
31
|
},
|
package/dist/index.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var P=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var Oe=(e,t)=>{for(var r in t)P(e,r,{get:t[r],enumerable:!0})},Ke=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ce(t))!ke.call(e,s)&&s!==r&&P(e,s,{get:()=>t[s],enumerable:!(n=De(t,s))||n.enumerable});return e};var Me=e=>Ke(P({},"__esModule",{value:!0}),e);var ct={};Oe(ct,{JoliboxSDK:()=>N});module.exports=Me(ct);var X=Object.defineProperty,Ne=Object.getOwnPropertyDescriptor,Pe=(e,t)=>{for(var r in t)X(e,r,{get:t[r],enumerable:!0})},q=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ne(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&X(t,r,s),s};function je(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function V(e){return typeof e=="string"}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function Je(e){return typeof e>"u"}function Fe(e){return Je(e)||e===null}function Be(e){return typeof e=="function"}function ee(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Ve=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Ve||{}),$e=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},te=class extends $e{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var re=class extends te{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},R=class extends te{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function S(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var He={log:S("log"),warn:S("warn"),info:S("info"),error:S("error"),debug:S("debug")};Object.assign(globalThis,{logger:He});var ne=Symbol.for("Jolibox.canIUseMap"),Ge={};globalThis[ne]=Ge;var se={get config(){return globalThis[ne]}};function $(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let l=0;l<i;l++){let g=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(g>c){n=1;break}else if(g<c){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var a=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},ze=class{constructor(){this._first=a.Undefined,this._last=a.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===a.Undefined}clear(){let e=this._first;for(;e!==a.Undefined;){let t=e.next;e.prev=a.Undefined,e.next=a.Undefined,e=t}this._first=a.Undefined,this._last=a.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new a(e);if(this._first===a.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==a.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==a.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==a.Undefined&&e.next!==a.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===a.Undefined&&e.next===a.Undefined?(this._first=a.Undefined,this._last=a.Undefined):e.next===a.Undefined?(this._last=this._last.prev,this._last.next=a.Undefined):e.prev===a.Undefined&&(this._first=this._first.next,this._first.prev=a.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==a.Undefined;)yield e.element,e=e.next}},We=0,w=class{constructor(e){this.value=e,this.id=We++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},H=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new ze,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},F={};Pe(F,{None:()=>Qe,filter:()=>Xe,once:()=>oe,toPromise:()=>Ye});var Qe=()=>{console.log("[Jolibox SDK] None Event")};function Ye(e){return new Promise(t=>oe(e)(t))}function oe(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function Xe(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var j=Symbol.for("Jolibox.hostEmitter"),qe=()=>{let e=new H;return globalThis[j]||(globalThis[j]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[j]},ie=qe();function Ze(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)et(e[n],t[n])}function et(e,t){if(V(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Be(t)){try{if(e instanceof t)return}catch{}if(!Fe(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Ze(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=q([ee],L);var B=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=je(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),F.toPromise(F.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};B=q([ee],B);var J=Symbol.for("Jolibox.commands");function p(){if(globalThis[J])return globalThis[J];let e=new L,t=new B,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[J]=r,r}document.addEventListener("DOMContentLoaded",()=>ie.emit("onDocumentReady",b.startTime));var tt=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=tt(),ae=p(),G=e=>{ae.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},E=G;window.addEventListener("unhandledrejection",G.bind(void 0));window.addEventListener("error",G.bind(void 0));window.onerror=(e,t,r,n,s)=>{ae.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{console.error(`Fallback report: ${o} ${JSON.stringify(e)}`)})};var z=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},x=e=>parseInt(z(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=z(e),{major:o,minor:i,patch:l}=z(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var ce=p(),A=(e,t)=>{ce.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ce.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var de="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(de)??"{}"),W=Date.now(),me=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,le=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function rt(){let e="https://stg-api.jolibox.com/api/fe-configs/js-sdk/version_metadata";try{let t=await fetch(e,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:r,bootstrap_version:n}=await t.json(),s={...T,timestamp:W};if(n){let{bootstrap_version:o}=T;if(!(o&&I(o,n))){let i=await(await fetch(Q(n))).text();le(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=T;if(!(o&&I(o,r))){let i=await(await fetch(Y(r))).text();le(i)&&(s={...s,implement_version:r,implement_script:i})}}localStorage.setItem(de,JSON.stringify(s))}catch(t){console.warn("Failed to fetch loader metadata: ",t)}}var ue=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:c,bootstrap_script:f,timestamp:u}=T;if(c&&f&&u&&!me(W,u)&&x(c)==t&&I(c,r)>0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new re(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();A("jsSdkBegin",{t:c}),b.startTime=c;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-c,{type:u})}}function l(c){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Ae=await import(h);return URL.revokeObjectURL(h),Ae}catch(m){E(new R(`implement module evaluate error in h5:${m} `))}})(c)}function g(){let c=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!me(W,m)&&x(u)==t&&I(u,r)>0){l(f),_("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),rt()}catch(c){E(new R(`module evaluate error: ${c}`))}}};var pe=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let l=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(l),c=await import(g);return URL.revokeObjectURL(g),c}catch(l){E(new R(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();A("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new R(`module load failed ${s}`))}}};var nt="1.1.4-beta.10",D=nt,ge=x(D),Ee=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,st=typeof Ee<"u",Q=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,Y=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,ot=e=>/^\d+\.\d+\.\d+$/.test(e),_e=ot(D)?ge:D,fe=Q(_e),he=Y(_e);function it(){st?pe(Ee,{bootstrapUrl:fe,implementUrl:he})():ue({bootstrapUrl:fe,implementUrl:he,currentMajorVersion:ge,currentVersion:D})()}it();var ye=p();function Re(){return ye.excuteCommandSync("API.getSystemInfoSync")}function Se(){return ye.excuteCommandSync("API.env")}function ve(e,t){return se.config[e]?.[t]}function be(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var Ie="1.1.4-beta.10";function y(e){let r=Se().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=ve(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||$(Ie,i,"<")?!1:s.length===0?!0:xe(o,s)||xe(o.properties,s)}function xe(e,t){if(!e)return!1;let r=be(e,t);return r?Z(r)?!0:V(r)?$(Ie,r,">="):!1:!1}var Te=p();async function we(){return y("login")?await Te.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function Ue(){return y("checkSession")?await Te.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Le=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new H}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var at="LifecycleSDK.onReady",C=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(at,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var k=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var O=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var K=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var M=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var N=class{constructor(){this.jssdkVersion="1.1.4-beta.10";this.runtime=new Le;this.ads=new O;this.lifecycle=new C;this.storage=new k;this.keyboard=new K;this.task=new M;this.getSystemInfoSync=Re.bind(this);this.canIUse=y.bind(this);this.login=we.bind(this);this.checkSession=Ue.bind(this)}};window.JoliboxSDK=N;
|
|
1
|
+
"use strict";var B=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var He=(e,t)=>{for(var r in t)B(e,r,{get:t[r],enumerable:!0})},We=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of $e(t))!Ge.call(e,s)&&s!==r&&B(e,s,{get:()=>t[s],enumerable:!(n=Ve(t,s))||n.enumerable});return e};var ze=e=>We(B({},"__esModule",{value:!0}),e);var jt={};He(jt,{JoliboxSDK:()=>F});module.exports=ze(jt);var se=Object.defineProperty,Ye=Object.getOwnPropertyDescriptor,Qe=(e,t)=>{for(var r in t)se(e,r,{get:t[r],enumerable:!0})},oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ye(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&se(t,r,s),s};function Xe(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function W(e){return typeof e=="string"}function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function qe(e){return typeof e>"u"}function Ze(e){return qe(e)||e===null}function et(e){return typeof e=="function"}function ae(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var tt=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(tt||{}),rt=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ce=class extends rt{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var le=class extends ce{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},S=class extends ce{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function x(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var nt={log:x("log"),warn:x("warn"),info:x("info"),error:x("error"),debug:x("debug")};Object.assign(globalThis,{logger:nt});var me=Symbol.for("Jolibox.canIUseMap"),st={};globalThis[me]=st;var de={get config(){return globalThis[me]}};function z(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let a=0;a<i;a++){let g=parseInt(s[a],10)||0,l=parseInt(o[a],10)||0;if(g>l){n=1;break}else if(g<l){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var Y=(e=>(e[e.System=1e3]="System",e[e.ErrorTrace=1001]="ErrorTrace",e[e.UserDefined=1002]="UserDefined",e))(Y||{}),k=(e=>(e.MiniGame="mini-game",e.MiniDrama="mini-drama",e.App="app",e.WebSDK="web-sdk",e.AppSDK="app-sdk",e))(k||{}),ot=(e=>(e[e.App=0]="App",e[e.H5=1]="H5",e[e.Weapp=2]="Weapp",e[e.Alipay=3]="Alipay",e[e.Gcash=4]="Gcash",e[e.Dana=5]="Dana",e[e.Umma=6]="Umma",e[e.WebSDK=1e3]="WebSDK",e[e.AppSDK=1001]="AppSDK",e[e.Other=9999]="Other",e))(ot||{}),ne=["name","params"],it=["name","type","location","target","extra","timestamp","userId"],at=["platform","os","appVersion","appId","model","brand","uuid","jsSdkVersion","extra"];function U(e,t){return t.map(r=>{if(r==="params"&&e[r]){let n=e[r];return Object.keys(n).reduce((s,o)=>(s[o]=String(n[o]),s),{})}return e[r]})}function ct(e){let t=e.location?U(e.location,ne):null,r=e.target?U(e.target,ne):null;return U({...e,location:t,target:r},it)}function ue(e){let t=e.events.map(n=>ct(n)),r=U(e.device,at);return[e.protocolVersion,t,r,e.project]}var lt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});var w={isiOS:navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPod")||navigator.userAgent.includes("iPad")||navigator.userAgent.includes("iPhone OS"),iosVersion:()=>{let e=navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);return[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3]||"0",10)]},isAndroid:navigator.userAgent.includes("Android"),isMac:navigator.userAgent.includes("Mac"),isFacebook:navigator.userAgent.includes("FB_IAB"),isPC:!navigator.userAgent.includes("iPhone")&&!navigator.userAgent.includes("Android")},mt=()=>w.isiOS?"iOS":w.isAndroid?"Android":w.isMac?"Mac":w.isFacebook?"Facebook":"PC",dt="device_id",ut="advertising_id",pe=e=>(localStorage.getItem(e)||localStorage.setItem(e,lt()),localStorage.getItem(e)),pt=()=>pe(dt),ft=()=>pe(ut),ht=e=>e.charAt(0).toUpperCase()+e.slice(1),gt=()=>{let e=new URLSearchParams(window.location.search);return ht(e.get("utm_source")??"")||"JoliboxSDK"},fe=e=>{let t="JoliboxWebSDK",r=mt(),n=navigator.language,s=pt(),o=ft();return`${t} (${gt()}${r}; UnknownModel; UnknownSystemVersion; ${n}) uuid/${s} adid/${o} version/${e||""}`},c=class D{static{this.Undefined=new D(void 0)}constructor(t){this.element=t,this.next=D.Undefined,this.prev=D.Undefined}},Et=class{constructor(){this._first=c.Undefined,this._last=c.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===c.Undefined}clear(){let e=this._first;for(;e!==c.Undefined;){let t=e.next;e.prev=c.Undefined,e.next=c.Undefined,e=t}this._first=c.Undefined,this._last=c.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new c(e);if(this._first===c.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==c.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==c.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==c.Undefined&&e.next!==c.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===c.Undefined&&e.next===c.Undefined?(this._first=c.Undefined,this._last=c.Undefined):e.next===c.Undefined?(this._last=this._last.prev,this._last.next=c.Undefined):e.prev===c.Undefined&&(this._first=this._first.next,this._first.prev=c.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==c.Undefined;)yield e.element,e=e.next}},_t=0,A=class{constructor(e){this.value=e,this.id=_t++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof A&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new A(e);this._listeners?this._listeners instanceof A?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof A?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},Q=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new Et,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},G={};Qe(G,{None:()=>yt,filter:()=>xt,once:()=>he,toPromise:()=>St});var yt=()=>{console.log("[Jolibox SDK] None Event")};function St(e){return new Promise(t=>he(e)(t))}function he(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function xt(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var V=Symbol.for("Jolibox.hostEmitter"),vt=()=>{let e=new Q;return globalThis[V]||(globalThis[V]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[V]},ge=vt();function bt(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)Rt(e[n],t[n])}function Rt(e,t){if(W(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(et(t)){try{if(e instanceof t)return}catch{}if(!Ze(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return bt(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=oe([ae],L);var H=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Xe(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),G.toPromise(G.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};H=oe([ae],H);var $=Symbol.for("Jolibox.commands");function p(){if(globalThis[$])return globalThis[$];let e=new L,t=new H,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[$]=r,r}var C=new URLSearchParams(window.location.search).get("joliboxEnv")==="staging";function It(){let e=new URLSearchParams(window.location.search),t={};return e.forEach((r,n)=>{t[n]=r}),{name:"GamePage",params:t}}function Tt(){return{platform:1e3,os:"h5",appVersion:"1.1.4-beta.11",appId:"1",model:"UnknownModel",brand:"UnknownBrand",uuid:"1",jsSdkVersion:"1.1.4-beta.11",extra:{}}}var Ee={default:{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.jolibox.com":{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.pico-game.com":{test:"https://stg-collect.pico-game.com",prod:"https://collect.pico-game.com"}},wt=()=>{let e=Ee[window.location.host]??Ee.default;return C?e.test:e.prod},At=wt(),_e=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};AbortSignal.timeout??=_e;var Ut=()=>new URLSearchParams(window.location.search).get("joliSource")??null,Dt=Ut(),Lt=async e=>{let r=`${At}/report`,n=fe("1.1.4-beta.11"),s=Dt,o={"Content-Type":"application/json"};return n&&(o["x-user-agent"]=n),s&&(o["x-joli-source"]=s),await fetch(r,{method:"POST",headers:o,body:JSON.stringify(e),signal:_e(5e3)})};async function X(e,t,r){let n={name:e,type:Y.ErrorTrace,location:It(),target:null,extra:t,timestamp:Date.now(),userId:null},s=Tt(),a=ue({protocolVersion:"1.0.0",events:[n],device:s,project:r});Lt(a)}document.addEventListener("DOMContentLoaded",()=>ge.emit("onDocumentReady",b.startTime));var kt=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=kt(),ye=p(),q=e=>{ye.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`),X("globalJsError",{err:JSON.stringify({message:t.message,source:t.source,lineno:t.lineno,colno:t.colno,error:t.error})},k.WebSDK)})},E=q;window.addEventListener("unhandledrejection",q.bind(void 0));window.addEventListener("error",q.bind(void 0));window.onerror=(e,t,r,n,s)=>{ye.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{X("globalJsError",{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})},k.WebSDK)})};var Z=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},R=e=>parseInt(Z(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=Z(e),{major:o,minor:i,patch:a}=Z(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==a?s>a?1:-1:0};var Se=p(),P=(e,t)=>{Se.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{Se.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var be="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(be)??"{}"),ee=Date.now(),xe=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,ve=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Ct(){let t=`${C?"https://stg-api.jolibox.com":"https://api.jolibox.com"}/api/fe-configs/js-sdk/version_metadata`;try{let r=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:n,bootstrap_version:s}=await r.json(),o={...T,timestamp:ee};if(s){let{bootstrap_version:i}=T;if(!(i&&I(i,s)>=0)){let a=await(await fetch(te(s))).text();ve(a)&&(o={...o,bootstrap_version:s,bootstrap_script:a})}}if(n){let{implement_version:i}=T;if(!(i&&I(i,n)>=0)){let a=await(await fetch(re(n))).text();ve(a)&&(o={...o,implement_version:n,implement_script:a})}}localStorage.setItem(be,JSON.stringify(o))}catch(r){console.warn("Failed to fetch loader metadata: ",r)}}var Re=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:l,bootstrap_script:f,timestamp:u}=T;if(l&&f&&u&&!xe(ee,u)&&R(l)==t&&I(l,r)>=0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new le(`Bootstrap module faile to fetch ${m}`))}}function i(){let l=Date.now();P("jsSdkBegin",{t:l}),b.startTime=l;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-l,{type:u})}}function a(l){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Be=await import(h);return URL.revokeObjectURL(h),Be}catch(m){E(new S(`implement module evaluate error in h5:${m} `))}})(l)}function g(){let l=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!xe(ee,m)&&R(u)==t&&I(u,r)>=0){a(f),_("implementModuleLoaded",Date.now()-l,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-l,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),Ct()}catch(l){E(new S(`module evaluate error: ${l}`))}}};var Ie=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let a=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(a),l=await import(g);return URL.revokeObjectURL(g),l}catch(a){E(new S(`implement module evaluate error in native:${a} `))}})(s)}return()=>{try{let s=Date.now();P("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let a=r(t.implementUrl);n(a),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new S(`module load failed ${s}`))}}};var Pt="1.1.4-beta.11",O=Pt,Ae=R(O),Ue=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,Ot=typeof Ue<"u",te=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,re=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,Kt=e=>/^\d+\.\d+\.\d+$/.test(e),De=Kt(O)?Ae:O,Te=te(De),we=re(De);function Mt(){Ot?Ie(Ue,{bootstrapUrl:Te,implementUrl:we})():Re({bootstrapUrl:Te,implementUrl:we,currentMajorVersion:Ae,currentVersion:O})()}Mt();var Le=p();function ke(){return Le.excuteCommandSync("API.getSystemInfoSync")}function Ce(){return Le.excuteCommandSync("API.env")}function Pe(e,t){return de.config[e]?.[t]}function Oe(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var Me="1.1.4-beta.11";function y(e){let r=Ce().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Pe(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||z(Me,i,"<")?!1:s.length===0?!0:Ke(o,s)||Ke(o.properties,s)}function Ke(e,t){if(!e)return!1;let r=Oe(e,t);return r?ie(r)?!0:W(r)?z(Me,r,">="):!1:!1}var Ne=p();async function je(){return y("login")?await Ne.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function Je(){return y("checkSession")?await Ne.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Fe=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new Q}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var Nt="LifecycleSDK.onReady",K=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(Nt,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var M=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var N=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var j=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var J=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var F=class{constructor(){this.jssdkVersion="1.1.4-beta.11";this.runtime=new Fe;this.ads=new N;this.lifecycle=new K;this.storage=new M;this.keyboard=new j;this.task=new J;this.getSystemInfoSync=ke.bind(this);this.canIUse=y.bind(this);this.login=je.bind(this);this.checkSession=Je.bind(this)}};window.JoliboxSDK=F;
|
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Y=Object.defineProperty,Ae=Object.getOwnPropertyDescriptor,De=(e,t)=>{for(var r in t)Y(e,r,{get:t[r],enumerable:!0})},X=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&Y(t,r,s),s};function Ce(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function F(e){return typeof e=="string"}function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function ke(e){return typeof e>"u"}function Oe(e){return ke(e)||e===null}function Ke(e){return typeof e=="function"}function Z(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Me=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Me||{}),Ne=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ee=class extends Ne{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var te=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},R=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function S(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Pe={log:S("log"),warn:S("warn"),info:S("info"),error:S("error"),debug:S("debug")};Object.assign(globalThis,{logger:Pe});var re=Symbol.for("Jolibox.canIUseMap"),je={};globalThis[re]=je;var ne={get config(){return globalThis[re]}};function B(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let l=0;l<i;l++){let g=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(g>c){n=1;break}else if(g<c){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var a=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},Je=class{constructor(){this._first=a.Undefined,this._last=a.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===a.Undefined}clear(){let e=this._first;for(;e!==a.Undefined;){let t=e.next;e.prev=a.Undefined,e.next=a.Undefined,e=t}this._first=a.Undefined,this._last=a.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new a(e);if(this._first===a.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==a.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==a.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==a.Undefined&&e.next!==a.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===a.Undefined&&e.next===a.Undefined?(this._first=a.Undefined,this._last=a.Undefined):e.next===a.Undefined?(this._last=this._last.prev,this._last.next=a.Undefined):e.prev===a.Undefined&&(this._first=this._first.next,this._first.prev=a.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==a.Undefined;)yield e.element,e=e.next}},Fe=0,w=class{constructor(e){this.value=e,this.id=Fe++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},V=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new Je,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},j={};De(j,{None:()=>Be,filter:()=>$e,once:()=>se,toPromise:()=>Ve});var Be=()=>{console.log("[Jolibox SDK] None Event")};function Ve(e){return new Promise(t=>se(e)(t))}function se(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function $e(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var N=Symbol.for("Jolibox.hostEmitter"),He=()=>{let e=new V;return globalThis[N]||(globalThis[N]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[N]},oe=He();function Ge(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)ze(e[n],t[n])}function ze(e,t){if(F(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Ke(t)){try{if(e instanceof t)return}catch{}if(!Oe(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Ge(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=X([Z],L);var J=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ce(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),j.toPromise(j.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};J=X([Z],J);var P=Symbol.for("Jolibox.commands");function p(){if(globalThis[P])return globalThis[P];let e=new L,t=new J,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[P]=r,r}document.addEventListener("DOMContentLoaded",()=>oe.emit("onDocumentReady",b.startTime));var We=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=We(),ie=p(),$=e=>{ie.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},E=$;window.addEventListener("unhandledrejection",$.bind(void 0));window.addEventListener("error",$.bind(void 0));window.onerror=(e,t,r,n,s)=>{ie.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{console.error(`Fallback report: ${o} ${JSON.stringify(e)}`)})};var H=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},x=e=>parseInt(H(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=H(e),{major:o,minor:i,patch:l}=H(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var ae=p(),A=(e,t)=>{ae.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ae.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var le="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(le)??"{}"),G=Date.now(),ce=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,me=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Qe(){let e="https://stg-api.jolibox.com/api/fe-configs/js-sdk/version_metadata";try{let t=await fetch(e,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:r,bootstrap_version:n}=await t.json(),s={...T,timestamp:G};if(n){let{bootstrap_version:o}=T;if(!(o&&I(o,n))){let i=await(await fetch(z(n))).text();me(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=T;if(!(o&&I(o,r))){let i=await(await fetch(W(r))).text();me(i)&&(s={...s,implement_version:r,implement_script:i})}}localStorage.setItem(le,JSON.stringify(s))}catch(t){console.warn("Failed to fetch loader metadata: ",t)}}var de=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:c,bootstrap_script:f,timestamp:u}=T;if(c&&f&&u&&!ce(G,u)&&x(c)==t&&I(c,r)>0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new te(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();A("jsSdkBegin",{t:c}),b.startTime=c;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-c,{type:u})}}function l(c){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Le=await import(h);return URL.revokeObjectURL(h),Le}catch(m){E(new R(`implement module evaluate error in h5:${m} `))}})(c)}function g(){let c=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!ce(G,m)&&x(u)==t&&I(u,r)>0){l(f),_("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),Qe()}catch(c){E(new R(`module evaluate error: ${c}`))}}};var ue=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let l=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(l),c=await import(g);return URL.revokeObjectURL(g),c}catch(l){E(new R(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();A("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new R(`module load failed ${s}`))}}};var Ye="1.1.4-beta.10",D=Ye,he=x(D),ge=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,Xe=typeof ge<"u",z=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,W=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,qe=e=>/^\d+\.\d+\.\d+$/.test(e),Ee=qe(D)?he:D,pe=z(Ee),fe=W(Ee);function Ze(){Xe?ue(ge,{bootstrapUrl:pe,implementUrl:fe})():de({bootstrapUrl:pe,implementUrl:fe,currentMajorVersion:he,currentVersion:D})()}Ze();var _e=p();function ye(){return _e.excuteCommandSync("API.getSystemInfoSync")}function Re(){return _e.excuteCommandSync("API.env")}function Se(e,t){return ne.config[e]?.[t]}function ve(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var xe="1.1.4-beta.10";function y(e){let r=Re().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Se(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||B(xe,i,"<")?!1:s.length===0?!0:be(o,s)||be(o.properties,s)}function be(e,t){if(!e)return!1;let r=ve(e,t);return r?q(r)?!0:F(r)?B(xe,r,">="):!1:!1}var Ie=p();async function Te(){return y("login")?await Ie.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function we(){return y("checkSession")?await Ie.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Ue=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new V}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var et="LifecycleSDK.onReady",C=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(et,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var k=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var O=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var K=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var M=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var Q=class{constructor(){this.jssdkVersion="1.1.4-beta.10";this.runtime=new Ue;this.ads=new O;this.lifecycle=new C;this.storage=new k;this.keyboard=new K;this.task=new M;this.getSystemInfoSync=ye.bind(this);this.canIUse=y.bind(this);this.login=Te.bind(this);this.checkSession=we.bind(this)}};window.JoliboxSDK=Q;export{Q as JoliboxSDK};
|
|
1
|
+
var ne=Object.defineProperty,Be=Object.getOwnPropertyDescriptor,Ve=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},se=(e,t,r,n)=>{for(var s=n>1?void 0:n?Be(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ne(t,r,s),s};function $e(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function G(e){return typeof e=="string"}function oe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function Ge(e){return typeof e>"u"}function He(e){return Ge(e)||e===null}function We(e){return typeof e=="function"}function ie(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var ze=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(ze||{}),Ye=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ae=class extends Ye{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var ce=class extends ae{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},S=class extends ae{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function x(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Qe={log:x("log"),warn:x("warn"),info:x("info"),error:x("error"),debug:x("debug")};Object.assign(globalThis,{logger:Qe});var le=Symbol.for("Jolibox.canIUseMap"),Xe={};globalThis[le]=Xe;var me={get config(){return globalThis[le]}};function H(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let a=0;a<i;a++){let g=parseInt(s[a],10)||0,l=parseInt(o[a],10)||0;if(g>l){n=1;break}else if(g<l){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var W=(e=>(e[e.System=1e3]="System",e[e.ErrorTrace=1001]="ErrorTrace",e[e.UserDefined=1002]="UserDefined",e))(W||{}),k=(e=>(e.MiniGame="mini-game",e.MiniDrama="mini-drama",e.App="app",e.WebSDK="web-sdk",e.AppSDK="app-sdk",e))(k||{}),qe=(e=>(e[e.App=0]="App",e[e.H5=1]="H5",e[e.Weapp=2]="Weapp",e[e.Alipay=3]="Alipay",e[e.Gcash=4]="Gcash",e[e.Dana=5]="Dana",e[e.Umma=6]="Umma",e[e.WebSDK=1e3]="WebSDK",e[e.AppSDK=1001]="AppSDK",e[e.Other=9999]="Other",e))(qe||{}),re=["name","params"],Ze=["name","type","location","target","extra","timestamp","userId"],et=["platform","os","appVersion","appId","model","brand","uuid","jsSdkVersion","extra"];function U(e,t){return t.map(r=>{if(r==="params"&&e[r]){let n=e[r];return Object.keys(n).reduce((s,o)=>(s[o]=String(n[o]),s),{})}return e[r]})}function tt(e){let t=e.location?U(e.location,re):null,r=e.target?U(e.target,re):null;return U({...e,location:t,target:r},Ze)}function de(e){let t=e.events.map(n=>tt(n)),r=U(e.device,et);return[e.protocolVersion,t,r,e.project]}var rt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});var w={isiOS:navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPod")||navigator.userAgent.includes("iPad")||navigator.userAgent.includes("iPhone OS"),iosVersion:()=>{let e=navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);return[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3]||"0",10)]},isAndroid:navigator.userAgent.includes("Android"),isMac:navigator.userAgent.includes("Mac"),isFacebook:navigator.userAgent.includes("FB_IAB"),isPC:!navigator.userAgent.includes("iPhone")&&!navigator.userAgent.includes("Android")},nt=()=>w.isiOS?"iOS":w.isAndroid?"Android":w.isMac?"Mac":w.isFacebook?"Facebook":"PC",st="device_id",ot="advertising_id",ue=e=>(localStorage.getItem(e)||localStorage.setItem(e,rt()),localStorage.getItem(e)),it=()=>ue(st),at=()=>ue(ot),ct=e=>e.charAt(0).toUpperCase()+e.slice(1),lt=()=>{let e=new URLSearchParams(window.location.search);return ct(e.get("utm_source")??"")||"JoliboxSDK"},pe=e=>{let t="JoliboxWebSDK",r=nt(),n=navigator.language,s=it(),o=at();return`${t} (${lt()}${r}; UnknownModel; UnknownSystemVersion; ${n}) uuid/${s} adid/${o} version/${e||""}`},c=class D{static{this.Undefined=new D(void 0)}constructor(t){this.element=t,this.next=D.Undefined,this.prev=D.Undefined}},mt=class{constructor(){this._first=c.Undefined,this._last=c.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===c.Undefined}clear(){let e=this._first;for(;e!==c.Undefined;){let t=e.next;e.prev=c.Undefined,e.next=c.Undefined,e=t}this._first=c.Undefined,this._last=c.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new c(e);if(this._first===c.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==c.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==c.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==c.Undefined&&e.next!==c.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===c.Undefined&&e.next===c.Undefined?(this._first=c.Undefined,this._last=c.Undefined):e.next===c.Undefined?(this._last=this._last.prev,this._last.next=c.Undefined):e.prev===c.Undefined&&(this._first=this._first.next,this._first.prev=c.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==c.Undefined;)yield e.element,e=e.next}},dt=0,A=class{constructor(e){this.value=e,this.id=dt++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof A&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new A(e);this._listeners?this._listeners instanceof A?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof A?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},z=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new mt,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},V={};Ve(V,{None:()=>ut,filter:()=>ft,once:()=>fe,toPromise:()=>pt});var ut=()=>{console.log("[Jolibox SDK] None Event")};function pt(e){return new Promise(t=>fe(e)(t))}function fe(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function ft(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var F=Symbol.for("Jolibox.hostEmitter"),ht=()=>{let e=new z;return globalThis[F]||(globalThis[F]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[F]},he=ht();function gt(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)Et(e[n],t[n])}function Et(e,t){if(G(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(We(t)){try{if(e instanceof t)return}catch{}if(!He(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return gt(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=se([ie],L);var $=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=$e(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),V.toPromise(V.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};$=se([ie],$);var B=Symbol.for("Jolibox.commands");function p(){if(globalThis[B])return globalThis[B];let e=new L,t=new $,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[B]=r,r}var C=new URLSearchParams(window.location.search).get("joliboxEnv")==="staging";function _t(){let e=new URLSearchParams(window.location.search),t={};return e.forEach((r,n)=>{t[n]=r}),{name:"GamePage",params:t}}function yt(){return{platform:1e3,os:"h5",appVersion:"1.1.4-beta.11",appId:"1",model:"UnknownModel",brand:"UnknownBrand",uuid:"1",jsSdkVersion:"1.1.4-beta.11",extra:{}}}var ge={default:{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.jolibox.com":{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.pico-game.com":{test:"https://stg-collect.pico-game.com",prod:"https://collect.pico-game.com"}},St=()=>{let e=ge[window.location.host]??ge.default;return C?e.test:e.prod},xt=St(),Ee=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};AbortSignal.timeout??=Ee;var vt=()=>new URLSearchParams(window.location.search).get("joliSource")??null,bt=vt(),Rt=async e=>{let r=`${xt}/report`,n=pe("1.1.4-beta.11"),s=bt,o={"Content-Type":"application/json"};return n&&(o["x-user-agent"]=n),s&&(o["x-joli-source"]=s),await fetch(r,{method:"POST",headers:o,body:JSON.stringify(e),signal:Ee(5e3)})};async function Y(e,t,r){let n={name:e,type:W.ErrorTrace,location:_t(),target:null,extra:t,timestamp:Date.now(),userId:null},s=yt(),a=de({protocolVersion:"1.0.0",events:[n],device:s,project:r});Rt(a)}document.addEventListener("DOMContentLoaded",()=>he.emit("onDocumentReady",b.startTime));var It=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=It(),_e=p(),Q=e=>{_e.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`),Y("globalJsError",{err:JSON.stringify({message:t.message,source:t.source,lineno:t.lineno,colno:t.colno,error:t.error})},k.WebSDK)})},E=Q;window.addEventListener("unhandledrejection",Q.bind(void 0));window.addEventListener("error",Q.bind(void 0));window.onerror=(e,t,r,n,s)=>{_e.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{Y("globalJsError",{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})},k.WebSDK)})};var X=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},R=e=>parseInt(X(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=X(e),{major:o,minor:i,patch:a}=X(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==a?s>a?1:-1:0};var ye=p(),P=(e,t)=>{ye.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ye.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var ve="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(ve)??"{}"),q=Date.now(),Se=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,xe=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Tt(){let t=`${C?"https://stg-api.jolibox.com":"https://api.jolibox.com"}/api/fe-configs/js-sdk/version_metadata`;try{let r=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:n,bootstrap_version:s}=await r.json(),o={...T,timestamp:q};if(s){let{bootstrap_version:i}=T;if(!(i&&I(i,s)>=0)){let a=await(await fetch(Z(s))).text();xe(a)&&(o={...o,bootstrap_version:s,bootstrap_script:a})}}if(n){let{implement_version:i}=T;if(!(i&&I(i,n)>=0)){let a=await(await fetch(ee(n))).text();xe(a)&&(o={...o,implement_version:n,implement_script:a})}}localStorage.setItem(ve,JSON.stringify(o))}catch(r){console.warn("Failed to fetch loader metadata: ",r)}}var be=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:l,bootstrap_script:f,timestamp:u}=T;if(l&&f&&u&&!Se(q,u)&&R(l)==t&&I(l,r)>=0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new ce(`Bootstrap module faile to fetch ${m}`))}}function i(){let l=Date.now();P("jsSdkBegin",{t:l}),b.startTime=l;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-l,{type:u})}}function a(l){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Fe=await import(h);return URL.revokeObjectURL(h),Fe}catch(m){E(new S(`implement module evaluate error in h5:${m} `))}})(l)}function g(){let l=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!Se(q,m)&&R(u)==t&&I(u,r)>=0){a(f),_("implementModuleLoaded",Date.now()-l,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-l,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),Tt()}catch(l){E(new S(`module evaluate error: ${l}`))}}};var Re=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let a=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(a),l=await import(g);return URL.revokeObjectURL(g),l}catch(a){E(new S(`implement module evaluate error in native:${a} `))}})(s)}return()=>{try{let s=Date.now();P("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let a=r(t.implementUrl);n(a),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new S(`module load failed ${s}`))}}};var wt="1.1.4-beta.11",O=wt,we=R(O),Ae=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,At=typeof Ae<"u",Z=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,ee=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,Ut=e=>/^\d+\.\d+\.\d+$/.test(e),Ue=Ut(O)?we:O,Ie=Z(Ue),Te=ee(Ue);function Dt(){At?Re(Ae,{bootstrapUrl:Ie,implementUrl:Te})():be({bootstrapUrl:Ie,implementUrl:Te,currentMajorVersion:we,currentVersion:O})()}Dt();var De=p();function Le(){return De.excuteCommandSync("API.getSystemInfoSync")}function ke(){return De.excuteCommandSync("API.env")}function Ce(e,t){return me.config[e]?.[t]}function Pe(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var Ke="1.1.4-beta.11";function y(e){let r=ke().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Ce(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||H(Ke,i,"<")?!1:s.length===0?!0:Oe(o,s)||Oe(o.properties,s)}function Oe(e,t){if(!e)return!1;let r=Pe(e,t);return r?oe(r)?!0:G(r)?H(Ke,r,">="):!1:!1}var Me=p();async function Ne(){return y("login")?await Me.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function je(){return y("checkSession")?await Me.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Je=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new z}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var Lt="LifecycleSDK.onReady",K=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(Lt,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var M=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var N=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var j=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var J=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var te=class{constructor(){this.jssdkVersion="1.1.4-beta.11";this.runtime=new Je;this.ads=new N;this.lifecycle=new K;this.storage=new M;this.keyboard=new j;this.task=new J;this.getSystemInfoSync=Le.bind(this);this.canIUse=y.bind(this);this.login=Ne.bind(this);this.checkSession=je.bind(this)}};window.JoliboxSDK=te;export{te as JoliboxSDK};
|
package/dist/index.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var Y=Object.defineProperty,Ae=Object.getOwnPropertyDescriptor,De=(e,t)=>{for(var r in t)Y(e,r,{get:t[r],enumerable:!0})},X=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&Y(t,r,s),s};function Ce(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function F(e){return typeof e=="string"}function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function ke(e){return typeof e>"u"}function Oe(e){return ke(e)||e===null}function Ke(e){return typeof e=="function"}function Z(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Me=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Me||{}),Ne=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ee=class extends Ne{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var te=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},R=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function S(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Pe={log:S("log"),warn:S("warn"),info:S("info"),error:S("error"),debug:S("debug")};Object.assign(globalThis,{logger:Pe});var re=Symbol.for("Jolibox.canIUseMap"),je={};globalThis[re]=je;var ne={get config(){return globalThis[re]}};function B(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let l=0;l<i;l++){let g=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(g>c){n=1;break}else if(g<c){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var a=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},Je=class{constructor(){this._first=a.Undefined,this._last=a.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===a.Undefined}clear(){let e=this._first;for(;e!==a.Undefined;){let t=e.next;e.prev=a.Undefined,e.next=a.Undefined,e=t}this._first=a.Undefined,this._last=a.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new a(e);if(this._first===a.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==a.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==a.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==a.Undefined&&e.next!==a.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===a.Undefined&&e.next===a.Undefined?(this._first=a.Undefined,this._last=a.Undefined):e.next===a.Undefined?(this._last=this._last.prev,this._last.next=a.Undefined):e.prev===a.Undefined&&(this._first=this._first.next,this._first.prev=a.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==a.Undefined;)yield e.element,e=e.next}},Fe=0,w=class{constructor(e){this.value=e,this.id=Fe++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},V=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new Je,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},j={};De(j,{None:()=>Be,filter:()=>$e,once:()=>se,toPromise:()=>Ve});var Be=()=>{console.log("[Jolibox SDK] None Event")};function Ve(e){return new Promise(t=>se(e)(t))}function se(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function $e(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var N=Symbol.for("Jolibox.hostEmitter"),He=()=>{let e=new V;return globalThis[N]||(globalThis[N]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[N]},oe=He();function Ge(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)ze(e[n],t[n])}function ze(e,t){if(F(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Ke(t)){try{if(e instanceof t)return}catch{}if(!Oe(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Ge(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=X([Z],L);var J=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ce(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),j.toPromise(j.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};J=X([Z],J);var P=Symbol.for("Jolibox.commands");function p(){if(globalThis[P])return globalThis[P];let e=new L,t=new J,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[P]=r,r}document.addEventListener("DOMContentLoaded",()=>oe.emit("onDocumentReady",b.startTime));var We=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=We(),ie=p(),$=e=>{ie.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},E=$;window.addEventListener("unhandledrejection",$.bind(void 0));window.addEventListener("error",$.bind(void 0));window.onerror=(e,t,r,n,s)=>{ie.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{console.error(`Fallback report: ${o} ${JSON.stringify(e)}`)})};var H=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},x=e=>parseInt(H(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=H(e),{major:o,minor:i,patch:l}=H(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var ae=p(),A=(e,t)=>{ae.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ae.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var le="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(le)??"{}"),G=Date.now(),ce=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,me=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Qe(){let e="https://stg-api.jolibox.com/api/fe-configs/js-sdk/version_metadata";try{let t=await fetch(e,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:r,bootstrap_version:n}=await t.json(),s={...T,timestamp:G};if(n){let{bootstrap_version:o}=T;if(!(o&&I(o,n))){let i=await(await fetch(z(n))).text();me(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=T;if(!(o&&I(o,r))){let i=await(await fetch(W(r))).text();me(i)&&(s={...s,implement_version:r,implement_script:i})}}localStorage.setItem(le,JSON.stringify(s))}catch(t){console.warn("Failed to fetch loader metadata: ",t)}}var de=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:c,bootstrap_script:f,timestamp:u}=T;if(c&&f&&u&&!ce(G,u)&&x(c)==t&&I(c,r)>0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new te(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();A("jsSdkBegin",{t:c}),b.startTime=c;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-c,{type:u})}}function l(c){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Le=await import(h);return URL.revokeObjectURL(h),Le}catch(m){E(new R(`implement module evaluate error in h5:${m} `))}})(c)}function g(){let c=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!ce(G,m)&&x(u)==t&&I(u,r)>0){l(f),_("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),Qe()}catch(c){E(new R(`module evaluate error: ${c}`))}}};var ue=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let l=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(l),c=await import(g);return URL.revokeObjectURL(g),c}catch(l){E(new R(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();A("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new R(`module load failed ${s}`))}}};var Ye="1.1.4-beta.10",D=Ye,he=x(D),ge=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,Xe=typeof ge<"u",z=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,W=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,qe=e=>/^\d+\.\d+\.\d+$/.test(e),Ee=qe(D)?he:D,pe=z(Ee),fe=W(Ee);function Ze(){Xe?ue(ge,{bootstrapUrl:pe,implementUrl:fe})():de({bootstrapUrl:pe,implementUrl:fe,currentMajorVersion:he,currentVersion:D})()}Ze();var _e=p();function ye(){return _e.excuteCommandSync("API.getSystemInfoSync")}function Re(){return _e.excuteCommandSync("API.env")}function Se(e,t){return ne.config[e]?.[t]}function ve(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var xe="1.1.4-beta.10";function y(e){let r=Re().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Se(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||B(xe,i,"<")?!1:s.length===0?!0:be(o,s)||be(o.properties,s)}function be(e,t){if(!e)return!1;let r=ve(e,t);return r?q(r)?!0:F(r)?B(xe,r,">="):!1:!1}var Ie=p();async function Te(){return y("login")?await Ie.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function we(){return y("checkSession")?await Ie.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Ue=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new V}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var et="LifecycleSDK.onReady",C=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(et,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var k=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var O=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var K=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var M=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var Q=class{constructor(){this.jssdkVersion="1.1.4-beta.10";this.runtime=new Ue;this.ads=new O;this.lifecycle=new C;this.storage=new k;this.keyboard=new K;this.task=new M;this.getSystemInfoSync=ye.bind(this);this.canIUse=y.bind(this);this.login=Te.bind(this);this.checkSession=we.bind(this)}};window.JoliboxSDK=Q;})();
|
|
1
|
+
"use strict";(()=>{var ne=Object.defineProperty,Be=Object.getOwnPropertyDescriptor,Ve=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},se=(e,t,r,n)=>{for(var s=n>1?void 0:n?Be(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ne(t,r,s),s};function $e(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function G(e){return typeof e=="string"}function oe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function Ge(e){return typeof e>"u"}function He(e){return Ge(e)||e===null}function We(e){return typeof e=="function"}function ie(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var ze=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(ze||{}),Ye=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ae=class extends Ye{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var ce=class extends ae{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},S=class extends ae{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function x(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Qe={log:x("log"),warn:x("warn"),info:x("info"),error:x("error"),debug:x("debug")};Object.assign(globalThis,{logger:Qe});var le=Symbol.for("Jolibox.canIUseMap"),Xe={};globalThis[le]=Xe;var me={get config(){return globalThis[le]}};function H(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let a=0;a<i;a++){let g=parseInt(s[a],10)||0,l=parseInt(o[a],10)||0;if(g>l){n=1;break}else if(g<l){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var W=(e=>(e[e.System=1e3]="System",e[e.ErrorTrace=1001]="ErrorTrace",e[e.UserDefined=1002]="UserDefined",e))(W||{}),k=(e=>(e.MiniGame="mini-game",e.MiniDrama="mini-drama",e.App="app",e.WebSDK="web-sdk",e.AppSDK="app-sdk",e))(k||{}),qe=(e=>(e[e.App=0]="App",e[e.H5=1]="H5",e[e.Weapp=2]="Weapp",e[e.Alipay=3]="Alipay",e[e.Gcash=4]="Gcash",e[e.Dana=5]="Dana",e[e.Umma=6]="Umma",e[e.WebSDK=1e3]="WebSDK",e[e.AppSDK=1001]="AppSDK",e[e.Other=9999]="Other",e))(qe||{}),re=["name","params"],Ze=["name","type","location","target","extra","timestamp","userId"],et=["platform","os","appVersion","appId","model","brand","uuid","jsSdkVersion","extra"];function U(e,t){return t.map(r=>{if(r==="params"&&e[r]){let n=e[r];return Object.keys(n).reduce((s,o)=>(s[o]=String(n[o]),s),{})}return e[r]})}function tt(e){let t=e.location?U(e.location,re):null,r=e.target?U(e.target,re):null;return U({...e,location:t,target:r},Ze)}function de(e){let t=e.events.map(n=>tt(n)),r=U(e.device,et);return[e.protocolVersion,t,r,e.project]}var rt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});var w={isiOS:navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPod")||navigator.userAgent.includes("iPad")||navigator.userAgent.includes("iPhone OS"),iosVersion:()=>{let e=navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);return[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3]||"0",10)]},isAndroid:navigator.userAgent.includes("Android"),isMac:navigator.userAgent.includes("Mac"),isFacebook:navigator.userAgent.includes("FB_IAB"),isPC:!navigator.userAgent.includes("iPhone")&&!navigator.userAgent.includes("Android")},nt=()=>w.isiOS?"iOS":w.isAndroid?"Android":w.isMac?"Mac":w.isFacebook?"Facebook":"PC",st="device_id",ot="advertising_id",ue=e=>(localStorage.getItem(e)||localStorage.setItem(e,rt()),localStorage.getItem(e)),it=()=>ue(st),at=()=>ue(ot),ct=e=>e.charAt(0).toUpperCase()+e.slice(1),lt=()=>{let e=new URLSearchParams(window.location.search);return ct(e.get("utm_source")??"")||"JoliboxSDK"},pe=e=>{let t="JoliboxWebSDK",r=nt(),n=navigator.language,s=it(),o=at();return`${t} (${lt()}${r}; UnknownModel; UnknownSystemVersion; ${n}) uuid/${s} adid/${o} version/${e||""}`},c=class D{static{this.Undefined=new D(void 0)}constructor(t){this.element=t,this.next=D.Undefined,this.prev=D.Undefined}},mt=class{constructor(){this._first=c.Undefined,this._last=c.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===c.Undefined}clear(){let e=this._first;for(;e!==c.Undefined;){let t=e.next;e.prev=c.Undefined,e.next=c.Undefined,e=t}this._first=c.Undefined,this._last=c.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new c(e);if(this._first===c.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==c.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==c.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==c.Undefined&&e.next!==c.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===c.Undefined&&e.next===c.Undefined?(this._first=c.Undefined,this._last=c.Undefined):e.next===c.Undefined?(this._last=this._last.prev,this._last.next=c.Undefined):e.prev===c.Undefined&&(this._first=this._first.next,this._first.prev=c.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==c.Undefined;)yield e.element,e=e.next}},dt=0,A=class{constructor(e){this.value=e,this.id=dt++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof A&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new A(e);this._listeners?this._listeners instanceof A?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof A?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},z=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new mt,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},V={};Ve(V,{None:()=>ut,filter:()=>ft,once:()=>fe,toPromise:()=>pt});var ut=()=>{console.log("[Jolibox SDK] None Event")};function pt(e){return new Promise(t=>fe(e)(t))}function fe(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function ft(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var F=Symbol.for("Jolibox.hostEmitter"),ht=()=>{let e=new z;return globalThis[F]||(globalThis[F]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[F]},he=ht();function gt(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)Et(e[n],t[n])}function Et(e,t){if(G(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(We(t)){try{if(e instanceof t)return}catch{}if(!He(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return gt(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=se([ie],L);var $=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=$e(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),V.toPromise(V.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};$=se([ie],$);var B=Symbol.for("Jolibox.commands");function p(){if(globalThis[B])return globalThis[B];let e=new L,t=new $,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[B]=r,r}var C=new URLSearchParams(window.location.search).get("joliboxEnv")==="staging";function _t(){let e=new URLSearchParams(window.location.search),t={};return e.forEach((r,n)=>{t[n]=r}),{name:"GamePage",params:t}}function yt(){return{platform:1e3,os:"h5",appVersion:"1.1.4-beta.11",appId:"1",model:"UnknownModel",brand:"UnknownBrand",uuid:"1",jsSdkVersion:"1.1.4-beta.11",extra:{}}}var ge={default:{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.jolibox.com":{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.pico-game.com":{test:"https://stg-collect.pico-game.com",prod:"https://collect.pico-game.com"}},St=()=>{let e=ge[window.location.host]??ge.default;return C?e.test:e.prod},xt=St(),Ee=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};AbortSignal.timeout??=Ee;var vt=()=>new URLSearchParams(window.location.search).get("joliSource")??null,bt=vt(),Rt=async e=>{let r=`${xt}/report`,n=pe("1.1.4-beta.11"),s=bt,o={"Content-Type":"application/json"};return n&&(o["x-user-agent"]=n),s&&(o["x-joli-source"]=s),await fetch(r,{method:"POST",headers:o,body:JSON.stringify(e),signal:Ee(5e3)})};async function Y(e,t,r){let n={name:e,type:W.ErrorTrace,location:_t(),target:null,extra:t,timestamp:Date.now(),userId:null},s=yt(),a=de({protocolVersion:"1.0.0",events:[n],device:s,project:r});Rt(a)}document.addEventListener("DOMContentLoaded",()=>he.emit("onDocumentReady",b.startTime));var It=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=It(),_e=p(),Q=e=>{_e.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`),Y("globalJsError",{err:JSON.stringify({message:t.message,source:t.source,lineno:t.lineno,colno:t.colno,error:t.error})},k.WebSDK)})},E=Q;window.addEventListener("unhandledrejection",Q.bind(void 0));window.addEventListener("error",Q.bind(void 0));window.onerror=(e,t,r,n,s)=>{_e.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{Y("globalJsError",{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})},k.WebSDK)})};var X=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},R=e=>parseInt(X(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=X(e),{major:o,minor:i,patch:a}=X(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==a?s>a?1:-1:0};var ye=p(),P=(e,t)=>{ye.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ye.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var ve="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(ve)??"{}"),q=Date.now(),Se=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,xe=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Tt(){let t=`${C?"https://stg-api.jolibox.com":"https://api.jolibox.com"}/api/fe-configs/js-sdk/version_metadata`;try{let r=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:n,bootstrap_version:s}=await r.json(),o={...T,timestamp:q};if(s){let{bootstrap_version:i}=T;if(!(i&&I(i,s)>=0)){let a=await(await fetch(Z(s))).text();xe(a)&&(o={...o,bootstrap_version:s,bootstrap_script:a})}}if(n){let{implement_version:i}=T;if(!(i&&I(i,n)>=0)){let a=await(await fetch(ee(n))).text();xe(a)&&(o={...o,implement_version:n,implement_script:a})}}localStorage.setItem(ve,JSON.stringify(o))}catch(r){console.warn("Failed to fetch loader metadata: ",r)}}var be=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:l,bootstrap_script:f,timestamp:u}=T;if(l&&f&&u&&!Se(q,u)&&R(l)==t&&I(l,r)>=0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new ce(`Bootstrap module faile to fetch ${m}`))}}function i(){let l=Date.now();P("jsSdkBegin",{t:l}),b.startTime=l;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-l,{type:u})}}function a(l){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Fe=await import(h);return URL.revokeObjectURL(h),Fe}catch(m){E(new S(`implement module evaluate error in h5:${m} `))}})(l)}function g(){let l=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!Se(q,m)&&R(u)==t&&I(u,r)>=0){a(f),_("implementModuleLoaded",Date.now()-l,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-l,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),Tt()}catch(l){E(new S(`module evaluate error: ${l}`))}}};var Re=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let a=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(a),l=await import(g);return URL.revokeObjectURL(g),l}catch(a){E(new S(`implement module evaluate error in native:${a} `))}})(s)}return()=>{try{let s=Date.now();P("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let a=r(t.implementUrl);n(a),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new S(`module load failed ${s}`))}}};var wt="1.1.4-beta.11",O=wt,we=R(O),Ae=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,At=typeof Ae<"u",Z=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,ee=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,Ut=e=>/^\d+\.\d+\.\d+$/.test(e),Ue=Ut(O)?we:O,Ie=Z(Ue),Te=ee(Ue);function Dt(){At?Re(Ae,{bootstrapUrl:Ie,implementUrl:Te})():be({bootstrapUrl:Ie,implementUrl:Te,currentMajorVersion:we,currentVersion:O})()}Dt();var De=p();function Le(){return De.excuteCommandSync("API.getSystemInfoSync")}function ke(){return De.excuteCommandSync("API.env")}function Ce(e,t){return me.config[e]?.[t]}function Pe(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var Ke="1.1.4-beta.11";function y(e){let r=ke().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Ce(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||H(Ke,i,"<")?!1:s.length===0?!0:Oe(o,s)||Oe(o.properties,s)}function Oe(e,t){if(!e)return!1;let r=Pe(e,t);return r?oe(r)?!0:G(r)?H(Ke,r,">="):!1:!1}var Me=p();async function Ne(){return y("login")?await Me.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function je(){return y("checkSession")?await Me.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Je=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new z}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var Lt="LifecycleSDK.onReady",K=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(Lt,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var M=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var N=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var j=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var J=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var te=class{constructor(){this.jssdkVersion="1.1.4-beta.11";this.runtime=new Je;this.ads=new N;this.lifecycle=new K;this.storage=new M;this.keyboard=new j;this.task=new J;this.getSystemInfoSync=Le.bind(this);this.canIUse=y.bind(this);this.login=Ne.bind(this);this.checkSession=je.bind(this)}};window.JoliboxSDK=te;})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const testMode: boolean;
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jolibox/sdk",
|
|
3
3
|
"description": "This project is common Jolibox JS-SDk interfere",
|
|
4
|
-
"version": "1.1.4-beta.
|
|
4
|
+
"version": "1.1.4-beta.11",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"module": "dist/index.esm.js",
|
|
7
7
|
"typings": "dist/index.d.ts",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"dependencies": {
|
|
10
|
-
"@jolibox/common": "1.1.4-beta.
|
|
11
|
-
"@jolibox/types": "1.1.4-beta.
|
|
10
|
+
"@jolibox/common": "1.1.4-beta.11",
|
|
11
|
+
"@jolibox/types": "1.1.4-beta.11"
|
|
12
12
|
},
|
|
13
13
|
"devDependencies": {
|
|
14
14
|
"typescript": "5.7.3",
|
package/sdk.build.log
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
Invoking: npm run clean && npm run build:cjs && npm run build:esm && npm run build:iife && tsc
|
|
2
2
|
|
|
3
|
-
> @jolibox/sdk@1.1.4-beta.
|
|
3
|
+
> @jolibox/sdk@1.1.4-beta.11 clean
|
|
4
4
|
> rimraf ./dist
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
> @jolibox/sdk@1.1.4-beta.
|
|
7
|
+
> @jolibox/sdk@1.1.4-beta.11 build:cjs
|
|
8
8
|
> BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=cjs
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
> @jolibox/sdk@1.1.4-beta.
|
|
11
|
+
> @jolibox/sdk@1.1.4-beta.11 build:esm
|
|
12
12
|
> BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=esm
|
|
13
13
|
|
|
14
14
|
|
|
15
|
-
> @jolibox/sdk@1.1.4-beta.
|
|
15
|
+
> @jolibox/sdk@1.1.4-beta.11 build:iife
|
|
16
16
|
> BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=iife
|
|
17
17
|
|
package/src/events.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { hostEmitter, createCommands, BaseError } from '@jolibox/common';
|
|
1
|
+
import { hostEmitter, createCommands, BaseError, EProject } from '@jolibox/common';
|
|
2
|
+
import { trackError } from './utils/event-tracker';
|
|
2
3
|
document.addEventListener('DOMContentLoaded', () => hostEmitter.emit('onDocumentReady', timeline.startTime));
|
|
3
4
|
|
|
4
5
|
const timelineFactory = () => {
|
|
@@ -28,6 +29,19 @@ const rejectHandler = (event: PromiseRejectionEvent | ErrorEvent | BaseError) =>
|
|
|
28
29
|
.catch((e) => {
|
|
29
30
|
// 兜底上报
|
|
30
31
|
console.error(`Fallback report: ${e} ${JSON.stringify(event)}`);
|
|
32
|
+
trackError(
|
|
33
|
+
'globalJsError',
|
|
34
|
+
{
|
|
35
|
+
err: JSON.stringify({
|
|
36
|
+
message: e.message,
|
|
37
|
+
source: e.source,
|
|
38
|
+
lineno: e.lineno,
|
|
39
|
+
colno: e.colno,
|
|
40
|
+
error: e.error
|
|
41
|
+
})
|
|
42
|
+
},
|
|
43
|
+
EProject.WebSDK
|
|
44
|
+
);
|
|
31
45
|
});
|
|
32
46
|
};
|
|
33
47
|
|
|
@@ -51,6 +65,18 @@ window.onerror = (message, source, lineno, colno, error) => {
|
|
|
51
65
|
})
|
|
52
66
|
.catch((e) => {
|
|
53
67
|
// 兜底上报
|
|
54
|
-
|
|
68
|
+
trackError(
|
|
69
|
+
'globalJsError',
|
|
70
|
+
{
|
|
71
|
+
err: JSON.stringify({
|
|
72
|
+
message,
|
|
73
|
+
source,
|
|
74
|
+
lineno,
|
|
75
|
+
colno,
|
|
76
|
+
error
|
|
77
|
+
})
|
|
78
|
+
},
|
|
79
|
+
EProject.WebSDK
|
|
80
|
+
);
|
|
55
81
|
});
|
|
56
82
|
};
|
package/src/loader/h5.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { track, trackPerformance } from '../utils/report';
|
|
|
3
3
|
import { InternalJSModuleEvalError, InternalJSModuleFetchError } from '@jolibox/common';
|
|
4
4
|
import { getBoostrapModuleUrl, getImplementModuleUrl } from './index';
|
|
5
5
|
import { reportError, timeline } from '../events';
|
|
6
|
+
import { testMode } from '@/utils/env';
|
|
6
7
|
|
|
7
8
|
const LOCAL_STORE_KEY = 'jolibox-sdk-loadermeta';
|
|
8
9
|
interface LocalStoreMeta {
|
|
@@ -23,8 +24,8 @@ const expired = (now: number, prev: number) =>
|
|
|
23
24
|
const isLegalScript = (str: string) =>
|
|
24
25
|
!/^(Failed to fetch version|Couldn't find the requested file)/.test(str);
|
|
25
26
|
async function fetchCurrentRemoteScript() {
|
|
26
|
-
|
|
27
|
-
const path =
|
|
27
|
+
const host = testMode ? 'https://stg-api.jolibox.com' : 'https://api.jolibox.com';
|
|
28
|
+
const path = `${host}/api/fe-configs/js-sdk/version_metadata`;
|
|
28
29
|
try {
|
|
29
30
|
const response = await fetch(path, {
|
|
30
31
|
method: 'GET',
|
|
@@ -36,7 +37,7 @@ async function fetchCurrentRemoteScript() {
|
|
|
36
37
|
let currentStore: LocalStoreMeta = { ...CURRENT_VERSION_STORE, timestamp: now };
|
|
37
38
|
if (bootstrap_version) {
|
|
38
39
|
const { bootstrap_version: currentLocalBootstrapVersion } = CURRENT_VERSION_STORE;
|
|
39
|
-
if (currentLocalBootstrapVersion && compare(currentLocalBootstrapVersion, bootstrap_version)) {
|
|
40
|
+
if (currentLocalBootstrapVersion && compare(currentLocalBootstrapVersion, bootstrap_version) >= 0) {
|
|
40
41
|
// no-op
|
|
41
42
|
} else {
|
|
42
43
|
const currentBootstrapModuleStr = await (await fetch(getBoostrapModuleUrl(bootstrap_version))).text();
|
|
@@ -50,7 +51,7 @@ async function fetchCurrentRemoteScript() {
|
|
|
50
51
|
}
|
|
51
52
|
if (implement_version) {
|
|
52
53
|
const { implement_version: currentLocalImpelementVersion } = CURRENT_VERSION_STORE;
|
|
53
|
-
if (currentLocalImpelementVersion && compare(currentLocalImpelementVersion, implement_version)) {
|
|
54
|
+
if (currentLocalImpelementVersion && compare(currentLocalImpelementVersion, implement_version) >= 0) {
|
|
54
55
|
// no-op
|
|
55
56
|
} else {
|
|
56
57
|
const currentImplementModuleStr = await (
|
|
@@ -89,7 +90,7 @@ export const createLoadImplement = (params: {
|
|
|
89
90
|
if (
|
|
90
91
|
!expired(now, timestamp) &&
|
|
91
92
|
major(bootstrap_version) == currentMajorVersion &&
|
|
92
|
-
compare(bootstrap_version, currentVersion)
|
|
93
|
+
compare(bootstrap_version, currentVersion) >= 0
|
|
93
94
|
) {
|
|
94
95
|
return { script: bootstrap_script, type: 'localscript' };
|
|
95
96
|
}
|
|
@@ -147,7 +148,7 @@ export const createLoadImplement = (params: {
|
|
|
147
148
|
if (
|
|
148
149
|
!expired(now, timestamp) &&
|
|
149
150
|
major(implement_version) == currentMajorVersion &&
|
|
150
|
-
compare(implement_version, currentVersion)
|
|
151
|
+
compare(implement_version, currentVersion) >= 0
|
|
151
152
|
) {
|
|
152
153
|
evalLocalJSModule(implement_script);
|
|
153
154
|
trackPerformance('implementModuleLoaded', Date.now() - implStartLoad, { type: 'loadscript' });
|
package/src/utils/env.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const testMode = new URLSearchParams(window.location.search).get('joliboxEnv') === 'staging';
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 兜底上报
|
|
3
|
+
*/
|
|
4
|
+
import {
|
|
5
|
+
serializeEventPackage,
|
|
6
|
+
IEvent,
|
|
7
|
+
EProject,
|
|
8
|
+
IEventPackage,
|
|
9
|
+
IPage,
|
|
10
|
+
IDevice,
|
|
11
|
+
EPlatform,
|
|
12
|
+
EventType,
|
|
13
|
+
timeout,
|
|
14
|
+
xUserAgent
|
|
15
|
+
} from '@jolibox/common';
|
|
16
|
+
import { testMode } from './env';
|
|
17
|
+
|
|
18
|
+
function getLocation(): IPage {
|
|
19
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
20
|
+
const params: Record<string, any> = {};
|
|
21
|
+
urlParams.forEach((value, key) => {
|
|
22
|
+
params[key] = value;
|
|
23
|
+
});
|
|
24
|
+
return {
|
|
25
|
+
name: 'GamePage',
|
|
26
|
+
params
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function getDevice(): IDevice {
|
|
31
|
+
return {
|
|
32
|
+
platform: 1000,
|
|
33
|
+
os: 'h5',
|
|
34
|
+
appVersion: '__JOLIBOX_LOCAL_SDK_VERSION__', // mock
|
|
35
|
+
appId: '1',
|
|
36
|
+
model: 'UnknownModel',
|
|
37
|
+
brand: 'UnknownBrand',
|
|
38
|
+
uuid: '1',
|
|
39
|
+
jsSdkVersion: '__JOLIBOX_LOCAL_SDK_VERSION__', // mock
|
|
40
|
+
extra: {}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const hostToApiMap: Record<string | 'default', { test: string; prod: string }> = {
|
|
45
|
+
default: {
|
|
46
|
+
test: 'https://stg-collect.jolibox.com',
|
|
47
|
+
prod: 'https://collect.jolibox.com'
|
|
48
|
+
},
|
|
49
|
+
'oss.jolibox.com': {
|
|
50
|
+
test: 'https://stg-collect.jolibox.com',
|
|
51
|
+
prod: 'https://collect.jolibox.com'
|
|
52
|
+
},
|
|
53
|
+
'oss.pico-game.com': {
|
|
54
|
+
test: 'https://stg-collect.pico-game.com',
|
|
55
|
+
prod: 'https://collect.pico-game.com'
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const apiBaseURL = () => {
|
|
60
|
+
const api = hostToApiMap[window.location.host] ?? hostToApiMap.default;
|
|
61
|
+
return testMode ? api.test : api.prod;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const API_BASE_URL = apiBaseURL();
|
|
65
|
+
|
|
66
|
+
const timeoutFn = (ms: number) => {
|
|
67
|
+
const ctrl = new AbortController();
|
|
68
|
+
setTimeout(() => ctrl.abort(), ms);
|
|
69
|
+
return ctrl.signal;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
(AbortSignal as any).timeout ??= timeoutFn;
|
|
73
|
+
|
|
74
|
+
const getJoliSource = () => {
|
|
75
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
76
|
+
return urlParams.get('joliSource') ?? null;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const JOLI_SOURCE = getJoliSource();
|
|
80
|
+
|
|
81
|
+
const postToReporter = async (data: unknown) => {
|
|
82
|
+
const reporterHost = API_BASE_URL;
|
|
83
|
+
const url = `${reporterHost}/report`;
|
|
84
|
+
const xua = xUserAgent('__JOLIBOX_LOCAL_SDK_VERSION__');
|
|
85
|
+
const joliSource = JOLI_SOURCE;
|
|
86
|
+
const headers: Record<string, string> = {
|
|
87
|
+
'Content-Type': 'application/json'
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
if (xua) headers['x-user-agent'] = xua;
|
|
91
|
+
if (joliSource) headers['x-joli-source'] = joliSource;
|
|
92
|
+
|
|
93
|
+
const response = await fetch(url, {
|
|
94
|
+
method: 'POST',
|
|
95
|
+
headers,
|
|
96
|
+
body: JSON.stringify(data),
|
|
97
|
+
signal: timeoutFn(5000)
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// return text
|
|
101
|
+
return response;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
export async function trackError(eventName: string, errorData: Record<string, string>, project: EProject) {
|
|
105
|
+
const errEvent: IEvent = {
|
|
106
|
+
name: eventName,
|
|
107
|
+
type: EventType.ErrorTrace,
|
|
108
|
+
location: getLocation(),
|
|
109
|
+
target: null,
|
|
110
|
+
extra: errorData,
|
|
111
|
+
timestamp: Date.now(),
|
|
112
|
+
userId: null
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const device = getDevice();
|
|
116
|
+
const events: IEvent[] = [errEvent];
|
|
117
|
+
const eventPackage: IEventPackage = {
|
|
118
|
+
protocolVersion: '1.0.0',
|
|
119
|
+
events,
|
|
120
|
+
device,
|
|
121
|
+
project
|
|
122
|
+
};
|
|
123
|
+
const serializedEventPackage = serializeEventPackage(eventPackage);
|
|
124
|
+
|
|
125
|
+
postToReporter(serializedEventPackage);
|
|
126
|
+
}
|