@jolibox/sdk 1.1.4-beta.0 → 1.1.4-beta.10
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 +16 -13
- package/dist/api/get-system-info.d.ts +0 -1
- package/dist/api/index.d.ts +1 -0
- package/dist/api/login.d.ts +7 -0
- package/dist/{errors.d.ts → events.d.ts} +3 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +12 -3
- package/dist/index.esm.js +1 -0
- package/dist/index.iife.js +1 -1
- package/dist/loader/index.d.ts +1 -0
- package/dist/sdks/lifecycle.d.ts +7 -4
- package/dist/sdks/sdk.d.ts +5 -0
- package/dist/sdks/task.d.ts +25 -0
- package/esbuild.config.js +65 -0
- package/package.json +7 -7
- package/sdk.build.log +7 -7
- package/src/api/__tests__/canIUse.test.ts +6 -6
- package/src/api/can-i-use.ts +1 -1
- package/src/api/get-system-info.ts +0 -3
- package/src/api/index.ts +1 -0
- package/src/api/login.ts +24 -0
- package/src/{errors.ts → events.ts} +17 -3
- package/src/index.ts +15 -3
- package/src/loader/h5.ts +5 -4
- package/src/loader/index.ts +30 -16
- package/src/loader/native.ts +3 -2
- package/src/sdks/keyboard.ts +10 -20
- package/src/sdks/lifecycle.ts +10 -6
- package/src/sdks/sdk.ts +10 -0
- package/src/sdks/task.ts +65 -0
- package/dist/index.es.js +0 -1
|
@@ -3,23 +3,26 @@
|
|
|
3
3
|
"packages/sdk/.rush/temp/shrinkwrap-deps.json": "2dae37e4e0434d977846f6598de8fbcb9919efc5",
|
|
4
4
|
"packages/sdk/.eslintrc.js": "c11c589d14fe58bf4d37d259d8323b193bab6092",
|
|
5
5
|
"packages/sdk/README.md": "5660cd88848b7a5428394cc34d881a35dd402188",
|
|
6
|
-
"packages/sdk/
|
|
7
|
-
"packages/sdk/
|
|
8
|
-
"packages/sdk/src/api/
|
|
9
|
-
"packages/sdk/src/api/
|
|
10
|
-
"packages/sdk/src/api/
|
|
11
|
-
"packages/sdk/src/
|
|
12
|
-
"packages/sdk/src/
|
|
13
|
-
"packages/sdk/src/
|
|
14
|
-
"packages/sdk/src/
|
|
15
|
-
"packages/sdk/src/loader/
|
|
6
|
+
"packages/sdk/esbuild.config.js": "7eacca35e51bf3e2face4112b3cfa76777e7c0d5",
|
|
7
|
+
"packages/sdk/package.json": "a2bfc5a043a19024688c680bf97cc2aa3073b00f",
|
|
8
|
+
"packages/sdk/src/api/__tests__/canIUse.test.ts": "300e4de3768f9510e956050d326d4977bc621f34",
|
|
9
|
+
"packages/sdk/src/api/can-i-use.ts": "4fd7efe21419d39e535584d7ab8e6a3c4e186877",
|
|
10
|
+
"packages/sdk/src/api/get-system-info.ts": "c73be9f62c7055093effadaf6c48c54d6f383542",
|
|
11
|
+
"packages/sdk/src/api/index.ts": "3b4493aba6d4d842031040be7ce72607009e0665",
|
|
12
|
+
"packages/sdk/src/api/login.ts": "747c923c87175b467c17e303a14210bf0ab7a1cb",
|
|
13
|
+
"packages/sdk/src/events.ts": "e7c5994804cc627eb5ad225c161c48a37a7b3bdb",
|
|
14
|
+
"packages/sdk/src/index.ts": "a772c24e370f183dba0c5346004f41dac6cb6807",
|
|
15
|
+
"packages/sdk/src/loader/h5.ts": "9ca7acc4996893f683b9adc8cffb2456928e5875",
|
|
16
|
+
"packages/sdk/src/loader/index.ts": "2fd698718dd7bad9fda8fa5a5f54d4d7bd209cb3",
|
|
17
|
+
"packages/sdk/src/loader/native.ts": "b250d460509f67b4544e5ca4d5f35f8dd20373c4",
|
|
16
18
|
"packages/sdk/src/loader/version.ts": "8b584cf9c97198b6b6d1f728cc49f56260d7c02e",
|
|
17
19
|
"packages/sdk/src/sdks/ads.ts": "d12ffe12be857f216a59a742f54395e31888adb5",
|
|
18
|
-
"packages/sdk/src/sdks/keyboard.ts": "
|
|
19
|
-
"packages/sdk/src/sdks/lifecycle.ts": "
|
|
20
|
+
"packages/sdk/src/sdks/keyboard.ts": "65301960c4d8f59d5944ae4c55cb45133ad40277",
|
|
21
|
+
"packages/sdk/src/sdks/lifecycle.ts": "8dad9d986cb43da7aeadf6f8af3cce37d6c37e6d",
|
|
20
22
|
"packages/sdk/src/sdks/runtime.ts": "de05c8f898b3f5848c83e5c088fb720bd8217d99",
|
|
21
|
-
"packages/sdk/src/sdks/sdk.ts": "
|
|
23
|
+
"packages/sdk/src/sdks/sdk.ts": "7ced43ddee5f0208ceaec5f8311f586d3ca5a13d",
|
|
22
24
|
"packages/sdk/src/sdks/storage.ts": "e04fca273b640f2e1dfcc70f23eaa537145c3f36",
|
|
25
|
+
"packages/sdk/src/sdks/task.ts": "07f5296dd999470d8d378487fd6f2a39a3f3d8ed",
|
|
23
26
|
"packages/sdk/src/utils/can-i-use.ts": "10993f013cf26c07b60fe60fb7b458bbd6847244",
|
|
24
27
|
"packages/sdk/src/utils/report.ts": "d928d7456a5ba829216c41ea5b66afff6627c6be",
|
|
25
28
|
"packages/sdk/tsconfig.json": "0ecd9cf2b93d09e0376a098b5b662820bafcf7eb"
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export declare function getSystemInfo(): Promise<import("@jolibox/types").StandardResponse<import("@jolibox/types").ISystemInfo>>;
|
|
2
1
|
export declare function getSystemInfoSync(): import("@jolibox/types").StandardResponse<import("@jolibox/types").ISystemInfo>;
|
|
3
2
|
export declare function env(): import("@jolibox/types").StandardResponse<Omit<Omit<import("@jolibox/types").Env, "hostUserInfo">, "schema">>;
|
package/dist/api/index.d.ts
CHANGED
package/dist/index.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var N=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Le=Object.prototype.hasOwnProperty;var we=(e,t)=>{for(var r in t)N(e,r,{get:t[r],enumerable:!0})},Ce=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ae(t))!Le.call(e,s)&&s!==r&&N(e,s,{get:()=>t[s],enumerable:!(n=Ue(t,s))||n.enumerable});return e};var Te=e=>Ce(N({},"__esModule",{value:!0}),e);var tt={};we(tt,{JoliboxSDK:()=>Q});module.exports=Te(tt);var Y=Object.defineProperty,De=Object.getOwnPropertyDescriptor,Oe=(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?De(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 Ne(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function j(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 Pe(e){return Ke(e)||e===null}function Me(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 ke=(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))(ke||{}),je=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 je{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"}},y=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function R(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Je={log:R("log"),warn:R("warn"),info:R("info"),error:R("error"),debug:R("debug")};Object.assign(globalThis,{logger:Je});var re=Symbol.for("Jolibox.canIUseMap"),Fe={};globalThis[re]=Fe;var ne={get config(){return globalThis[re]}};function J(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 _=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(_>c){n=1;break}else if(_<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}},Be=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}},Ve=0,I=class{constructor(e){this.value=e,this.id=Ve++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof I&&(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 I(e);this._listeners?this._listeners instanceof I?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 I?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},F=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 Be,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},M={};Oe(M,{None:()=>Ge,filter:()=>He,once:()=>se,toPromise:()=>$e});var Ge=()=>{console.log("[Jolibox SDK] None Event")};function $e(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 He(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 K=Symbol.for("Jolibox.hostEmitter"),ze=()=>{let e=new F;return globalThis[K]||(globalThis[K]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[K]},oe=ze();function We(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)Qe(e[n],t[n])}function Qe(e,t){if(j(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Me(t)){try{if(e instanceof t)return}catch{}if(!Pe(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 A=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 We(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}};A=X([Z],A);var k=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new A,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ne(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),M.toPromise(M.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}}};k=X([Z],k);var P=Symbol.for("Jolibox.commands");function h(){if(globalThis[P])return globalThis[P];let e=new A,t=new k,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"));var ie=h(),B=e=>{ie.executeCommand("ReportSDK.traceSystem",{event:"global_js_error",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},g=B;window.addEventListener("unhandledrejection",B.bind(void 0));window.addEventListener("error",B.bind(void 0));window.onerror=(e,t,r,n,s)=>{ie.executeCommand("ReportSDK.traceSystem",{event:"global_js_error",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 V=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}},S=e=>parseInt(V(e).major,10),b=(e,t)=>{let{major:r,minor:n,patch:s}=V(e),{major:o,minor:i,patch:l}=V(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var ae=h(),L=(e,t)=>{ae.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},E=(e,t,r)=>{ae.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var le="jolibox-sdk-loadermeta",x=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 Ye(){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={...x,timestamp:G};if(n){let{bootstrap_version:o}=x;if(!(o&&b(o,n))){let i=await(await fetch($(n))).text();me(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=x;if(!(o&&b(o,r))){let i=await(await fetch(H(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:p,timestamp:d}=x;if(c&&p&&d&&!ce(G,d)&&S(c)==t&&b(c,r)>0)return{script:p,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){g(new te(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();L("js_sdk_begin",{t:c});let{script:p,type:d}=o()??{};if(p){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=p,document.head.appendChild(m),E("bootstrapModuleLoaded",Date.now()-c,{type:d})}}function l(c){(async d=>{try{let m=new Blob([d],{type:"application/javascript"}),f=URL.createObjectURL(m),Ie=await import(f);return URL.revokeObjectURL(f),Ie}catch(m){g(new y(`implement module evaluate error in h5:${m} `))}})(c)}function _(){let c=Date.now(),{implement_script:p,implement_version:d,timestamp:m}=x;if(p&&d&&m&&!ce(G,m)&&S(d)==t&&b(d,r)>0){l(p),E("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let f=document.createElement("script");f.type="module",f.crossOrigin="anonymous",f.src=s,f.onload=()=>{E("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(f)}return()=>{try{i(),_(),Ye()}catch(c){g(new y(`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"}),_=URL.createObjectURL(l),c=await import(_);return URL.revokeObjectURL(_),c}catch(l){g(new y(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();L("js_sdk_begin",{t:s});let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),E("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),E("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),g(new y(`module load failed ${s}`))}}};var Xe="1.0.0",he=Xe,z=S(he),_e=window.webkit?e=>window.prompt("loadScript",JSON.stringify(e)):void 0,qe=typeof _e<"u",$=e=>`http://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,H=e=>`http://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,pe=$(z),fe=H(z);function Ze(){qe?ue(_e,{bootstrapUrl:pe,implementUrl:fe})():de({bootstrapUrl:pe,implementUrl:fe,currentMajorVersion:z,currentVersion:he})()}Ze();var W=h();async function ge(){return await W.executeCommand("API.getSystemInfo")}function Ee(){return W.excuteCommandSync("API.getSystemInfoSync")}function ye(){return W.excuteCommandSync("API.env")}function Re(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 be="1.0.0";function w(e){let r=ye().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Re(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||J(be,i,"<")?!1:s.length===0?!0:Se(o,s)||Se(o.properties,s)}function Se(e,t){if(!e)return!1;let r=ve(e,t);return r?q(r)?!0:j(r)?J(be,r,">="):!1:!1}var xe=window.JoliboxRuntime;var u=class{constructor(){this.commands=h();this._emitter=new F}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return w(t)}};var et="LifecycleSDK.onReady",C=class extends u{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(et,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exitGame(t){this.commands.executeCommand("LifecycleSDK.exitGame",t.onBeforeExit)}onGameHide(t){this.commands.executeCommand("LifecycleSDK.onGameHide",t.bind(this))}onGameShow(t){this.commands.executeCommand("LifecycleSDK.onGameShow",t.bind(this))}};var T=class extends u{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 D=class extends u{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 O=class extends u{showKeyboard(t){if(!this.canUse("keyboard.showKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.showKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){if(!this.canUse("keyboard.updateKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.updateKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.updateKeyboard",t)}hideKeyboard(){if(!this.canUse("keyboard.hideKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.hideKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var Q=class{constructor(){this.runtime=new xe;this.ads=new D;this.lifecycle=new C;this.storage=new T;this.keyboard=new O;this.getSystemInfo=ge.bind(this);this.getSystemInfoSync=Ee.bind(this);this.canIUse=w.bind(this)}};
|
|
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;
|
package/dist/index.d.ts
CHANGED
|
@@ -2,23 +2,32 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* global error catch
|
|
4
4
|
*/
|
|
5
|
-
import './
|
|
5
|
+
import './events';
|
|
6
6
|
import './loader';
|
|
7
7
|
/**
|
|
8
8
|
* @public Jolibox JS SDK Entry
|
|
9
9
|
*/
|
|
10
|
-
import {
|
|
10
|
+
import { getSystemInfoSync, canIUse, login, checkSession } from './api';
|
|
11
11
|
import { LifecycleSDK } from './sdks/lifecycle';
|
|
12
12
|
import { StorageSDK } from './sdks/storage';
|
|
13
13
|
import { JoliboxAds } from './sdks/ads';
|
|
14
14
|
import { KeyboardSDK } from './sdks/keyboard';
|
|
15
|
+
import { TaskTrackerSDK } from './sdks/task';
|
|
16
|
+
declare global {
|
|
17
|
+
interface Window {
|
|
18
|
+
JoliboxSDK: typeof JoliboxSDK;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
15
21
|
export declare class JoliboxSDK {
|
|
22
|
+
readonly jssdkVersion = "__JOLIBOX_LOCAL_SDK_VERSION__";
|
|
16
23
|
readonly runtime: any;
|
|
17
24
|
readonly ads: JoliboxAds;
|
|
18
25
|
readonly lifecycle: LifecycleSDK;
|
|
19
26
|
readonly storage: StorageSDK;
|
|
20
27
|
readonly keyboard: KeyboardSDK;
|
|
21
|
-
|
|
28
|
+
readonly task: TaskTrackerSDK;
|
|
22
29
|
getSystemInfoSync: typeof getSystemInfoSync;
|
|
23
30
|
canIUse: typeof canIUse;
|
|
31
|
+
login: typeof login;
|
|
32
|
+
checkSession: typeof checkSession;
|
|
24
33
|
}
|
|
@@ -0,0 +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};
|
package/dist/index.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var W=Object.defineProperty,Ie=Object.getOwnPropertyDescriptor,Ue=(e,t)=>{for(var r in t)W(e,r,{get:t[r],enumerable:!0})},Q=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ie(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&&W(t,r,s),s};function Ae(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function k(e){return typeof e=="string"}function Y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function Le(e){return typeof e>"u"}function we(e){return Le(e)||e===null}function Ce(e){return typeof e=="function"}function X(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Te=(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))(Te||{}),De=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}},q=class extends De{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var Z=class extends q{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},y=class extends q{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function R(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Oe={log:R("log"),warn:R("warn"),info:R("info"),error:R("error"),debug:R("debug")};Object.assign(globalThis,{logger:Oe});var ee=Symbol.for("Jolibox.canIUseMap"),Ne={};globalThis[ee]=Ne;var te={get config(){return globalThis[ee]}};function j(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 _=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(_>c){n=1;break}else if(_<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}},Ke=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}},Pe=0,I=class{constructor(e){this.value=e,this.id=Pe++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof I&&(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 I(e);this._listeners?this._listeners instanceof I?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 I?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},J=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 Ke,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},P={};Ue(P,{None:()=>Me,filter:()=>je,once:()=>re,toPromise:()=>ke});var Me=()=>{console.log("[Jolibox SDK] None Event")};function ke(e){return new Promise(t=>re(e)(t))}function re(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function je(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"),Je=()=>{let e=new J;return globalThis[N]||(globalThis[N]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[N]},ne=Je();function Fe(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)Be(e[n],t[n])}function Be(e,t){if(k(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Ce(t)){try{if(e instanceof t)return}catch{}if(!we(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 A=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 Fe(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}};A=Q([X],A);var M=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new A,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ae(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),P.toPromise(P.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}}};M=Q([X],M);var K=Symbol.for("Jolibox.commands");function h(){if(globalThis[K])return globalThis[K];let e=new A,t=new M,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[K]=r,r}document.addEventListener("DOMContentLoaded",()=>ne.emit("onDocumentReady"));var se=h(),F=e=>{se.executeCommand("ReportSDK.traceSystem",{event:"global_js_error",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},g=F;window.addEventListener("unhandledrejection",F.bind(void 0));window.addEventListener("error",F.bind(void 0));window.onerror=(e,t,r,n,s)=>{se.executeCommand("ReportSDK.traceSystem",{event:"global_js_error",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 B=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}},S=e=>parseInt(B(e).major,10),b=(e,t)=>{let{major:r,minor:n,patch:s}=B(e),{major:o,minor:i,patch:l}=B(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var oe=h(),L=(e,t)=>{oe.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},E=(e,t,r)=>{oe.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var ce="jolibox-sdk-loadermeta",x=JSON.parse(localStorage.getItem(ce)??"{}"),V=Date.now(),ie=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,ae=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Ve(){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={...x,timestamp:V};if(n){let{bootstrap_version:o}=x;if(!(o&&b(o,n))){let i=await(await fetch(G(n))).text();ae(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=x;if(!(o&&b(o,r))){let i=await(await fetch($(r))).text();ae(i)&&(s={...s,implement_version:r,implement_script:i})}}localStorage.setItem(ce,JSON.stringify(s))}catch(t){console.warn("Failed to fetch loader metadata: ",t)}}var me=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:c,bootstrap_script:p,timestamp:d}=x;if(c&&p&&d&&!ie(V,d)&&S(c)==t&&b(c,r)>0)return{script:p,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){g(new Z(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();L("js_sdk_begin",{t:c});let{script:p,type:d}=o()??{};if(p){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=p,document.head.appendChild(m),E("bootstrapModuleLoaded",Date.now()-c,{type:d})}}function l(c){(async d=>{try{let m=new Blob([d],{type:"application/javascript"}),f=URL.createObjectURL(m),xe=await import(f);return URL.revokeObjectURL(f),xe}catch(m){g(new y(`implement module evaluate error in h5:${m} `))}})(c)}function _(){let c=Date.now(),{implement_script:p,implement_version:d,timestamp:m}=x;if(p&&d&&m&&!ie(V,m)&&S(d)==t&&b(d,r)>0){l(p),E("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let f=document.createElement("script");f.type="module",f.crossOrigin="anonymous",f.src=s,f.onload=()=>{E("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(f)}return()=>{try{i(),_(),Ve()}catch(c){g(new y(`module evaluate error: ${c}`))}}};var le=(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"}),_=URL.createObjectURL(l),c=await import(_);return URL.revokeObjectURL(_),c}catch(l){g(new y(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();L("js_sdk_begin",{t:s});let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),E("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),E("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),g(new y(`module load failed ${s}`))}}};var Ge="1.0.0",pe=Ge,H=S(pe),fe=window.webkit?e=>window.prompt("loadScript",JSON.stringify(e)):void 0,$e=typeof fe<"u",G=e=>`http://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,$=e=>`http://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,de=G(H),ue=$(H);function He(){$e?le(fe,{bootstrapUrl:de,implementUrl:ue})():me({bootstrapUrl:de,implementUrl:ue,currentMajorVersion:H,currentVersion:pe})()}He();var z=h();async function he(){return await z.executeCommand("API.getSystemInfo")}function _e(){return z.excuteCommandSync("API.getSystemInfoSync")}function ge(){return z.excuteCommandSync("API.env")}function Ee(e,t){return te.config[e]?.[t]}function ye(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 ve="1.0.0";function w(e){let r=ge().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Ee(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||j(ve,i,"<")?!1:s.length===0?!0:Re(o,s)||Re(o.properties,s)}function Re(e,t){if(!e)return!1;let r=ye(e,t);return r?Y(r)?!0:k(r)?j(ve,r,">="):!1:!1}var Se=window.JoliboxRuntime;var u=class{constructor(){this.commands=h();this._emitter=new J}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return w(t)}};var ze="LifecycleSDK.onReady",C=class extends u{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(ze,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exitGame(t){this.commands.executeCommand("LifecycleSDK.exitGame",t.onBeforeExit)}onGameHide(t){this.commands.executeCommand("LifecycleSDK.onGameHide",t.bind(this))}onGameShow(t){this.commands.executeCommand("LifecycleSDK.onGameShow",t.bind(this))}};var T=class extends u{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 D=class extends u{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 O=class extends u{showKeyboard(t){if(!this.canUse("keyboard.showKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.showKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){if(!this.canUse("keyboard.updateKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.updateKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.updateKeyboard",t)}hideKeyboard(){if(!this.canUse("keyboard.hideKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.hideKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var be=class{constructor(){this.runtime=new Se;this.ads=new D;this.lifecycle=new C;this.storage=new T;this.keyboard=new O;this.getSystemInfo=he.bind(this);this.getSystemInfoSync=_e.bind(this);this.canIUse=w.bind(this)}};})();
|
|
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;})();
|
package/dist/loader/index.d.ts
CHANGED
package/dist/sdks/lifecycle.d.ts
CHANGED
|
@@ -7,10 +7,13 @@ interface LifecycleSDKEventMap extends BaseSDKEventMap {
|
|
|
7
7
|
export declare class LifecycleSDK extends BaseSDK<LifecycleSDKEventMap> implements Lifecycle {
|
|
8
8
|
constructor();
|
|
9
9
|
onReady(callback: (info?: Env['hostUserInfo']) => void): void;
|
|
10
|
-
|
|
10
|
+
exit(params: {
|
|
11
11
|
onBeforeExit: () => void;
|
|
12
|
-
}):
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
}): {
|
|
13
|
+
code: import("@jolibox/types").ResponseType;
|
|
14
|
+
message: string;
|
|
15
|
+
} | undefined;
|
|
16
|
+
onJoliboxHide(params: () => void): void;
|
|
17
|
+
onJoliboxShow(params: () => void): void;
|
|
15
18
|
}
|
|
16
19
|
export {};
|
package/dist/sdks/sdk.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from '@jolibox/common';
|
|
2
|
+
import { ResponseType } from '@jolibox/types';
|
|
2
3
|
export interface BaseSDKEventMap {
|
|
3
4
|
_baseSDKMarker?: never;
|
|
4
5
|
}
|
|
@@ -8,4 +9,8 @@ export declare abstract class BaseSDK<T = BaseSDKEventMap> {
|
|
|
8
9
|
addEventListener<K extends keyof T & string>(event: K, callback: (data: T[K]) => void): void;
|
|
9
10
|
triggerEvent<K extends keyof T & string>(event: K, params: T[K]): void;
|
|
10
11
|
canUse(command: string): boolean;
|
|
12
|
+
canIUseIfThrow(command: string): {
|
|
13
|
+
code: ResponseType;
|
|
14
|
+
message: string;
|
|
15
|
+
} | undefined;
|
|
11
16
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { BaseSDK } from './sdk';
|
|
2
|
+
import { TaskTracker, TaskResponse } from '@jolibox/types';
|
|
3
|
+
export declare class TaskTrackerSDK extends BaseSDK implements TaskTracker {
|
|
4
|
+
onLevelFinished(levelId: string | number, result: boolean, duration: number): Promise<TaskResponse>;
|
|
5
|
+
onTaskFinished(taskId: string | number, duration: number): Promise<TaskResponse>;
|
|
6
|
+
onTaskEvent(taskId: string | number, params: {
|
|
7
|
+
tools?: {
|
|
8
|
+
id: string | number;
|
|
9
|
+
name: string;
|
|
10
|
+
count?: number;
|
|
11
|
+
description?: string;
|
|
12
|
+
price?: {
|
|
13
|
+
amount: number;
|
|
14
|
+
unit: string;
|
|
15
|
+
};
|
|
16
|
+
}[];
|
|
17
|
+
awards?: {
|
|
18
|
+
id: string | number;
|
|
19
|
+
name: string;
|
|
20
|
+
}[];
|
|
21
|
+
}): Promise<TaskResponse>;
|
|
22
|
+
onLevelUpgrade(levelId: string | number, name: string): Promise<TaskResponse>;
|
|
23
|
+
onHistoryUserLevel(level: number): Promise<TaskResponse>;
|
|
24
|
+
onHistoryUserScore(score: number): Promise<TaskResponse>;
|
|
25
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
const esbuild = require('esbuild');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
|
|
4
|
+
function versionPlugin(version) {
|
|
5
|
+
return {
|
|
6
|
+
name: 'version',
|
|
7
|
+
setup(build) {
|
|
8
|
+
build.onLoad({ filter: /\.[jt]sx?$/ }, async (args) => {
|
|
9
|
+
const contents = await fs.promises.readFile(args.path, 'utf8');
|
|
10
|
+
return {
|
|
11
|
+
contents: contents.replace(/__JOLIBOX_LOCAL_SDK_VERSION__/g, version),
|
|
12
|
+
loader: args.path.endsWith('tsx') ? 'tsx' : 'ts'
|
|
13
|
+
};
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function parseArgs() {
|
|
20
|
+
const args = process.argv.slice(2);
|
|
21
|
+
const options = {
|
|
22
|
+
format: 'iife', // 默认值
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
for (let i = 0; i < args.length; i++) {
|
|
26
|
+
const arg = args[i];
|
|
27
|
+
const [argKey, argVal] = arg.split('=');
|
|
28
|
+
if (argKey === '--format' || argKey === '-f') {
|
|
29
|
+
if (['esm', 'cjs', 'iife'].includes(argVal)) {
|
|
30
|
+
options.format = argVal;
|
|
31
|
+
}
|
|
32
|
+
i++;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return options;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const options = parseArgs();
|
|
40
|
+
|
|
41
|
+
function build(format) {
|
|
42
|
+
return esbuild.build({
|
|
43
|
+
entryPoints: ['src/index.ts'],
|
|
44
|
+
bundle: true,
|
|
45
|
+
outfile: `dist/index.${format}.js`,
|
|
46
|
+
format: format,
|
|
47
|
+
minify: true,
|
|
48
|
+
loader: {
|
|
49
|
+
'.ts': 'ts',
|
|
50
|
+
'.tsx': 'tsx',
|
|
51
|
+
'.js': 'jsx'
|
|
52
|
+
},
|
|
53
|
+
plugins: [versionPlugin(process.env.BUILD_VERSION || '1.0.0')],
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
(async ()=>{
|
|
58
|
+
try{
|
|
59
|
+
await build(options.format);
|
|
60
|
+
}catch(e) {
|
|
61
|
+
console.error(e);
|
|
62
|
+
process.exit(1);
|
|
63
|
+
}
|
|
64
|
+
})()
|
|
65
|
+
|
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.10",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
|
-
"module": "dist/index.
|
|
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.10",
|
|
11
|
+
"@jolibox/types": "1.1.4-beta.10"
|
|
12
12
|
},
|
|
13
13
|
"devDependencies": {
|
|
14
14
|
"typescript": "5.7.3",
|
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
"scripts": {
|
|
21
21
|
"clean": "rimraf ./dist",
|
|
22
22
|
"build": "npm run clean && npm run build:cjs && npm run build:esm && npm run build:iife && tsc",
|
|
23
|
-
"build:cjs": "
|
|
24
|
-
"build:esm": "
|
|
25
|
-
"build:iife": "
|
|
23
|
+
"build:cjs": "BUILD_VERSION=$(node -p \"require('./package.json').version\") node esbuild.config.js --format=cjs",
|
|
24
|
+
"build:esm": "BUILD_VERSION=$(node -p \"require('./package.json').version\") node esbuild.config.js --format=esm",
|
|
25
|
+
"build:iife": "BUILD_VERSION=$(node -p \"require('./package.json').version\") node esbuild.config.js --format=iife",
|
|
26
26
|
"dev": "tsc --watch",
|
|
27
27
|
"test": "jest"
|
|
28
28
|
},
|
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.
|
|
3
|
+
> @jolibox/sdk@1.1.4-beta.10 clean
|
|
4
4
|
> rimraf ./dist
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
> @jolibox/sdk@1.
|
|
8
|
-
>
|
|
7
|
+
> @jolibox/sdk@1.1.4-beta.10 build:cjs
|
|
8
|
+
> BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=cjs
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
> @jolibox/sdk@1.
|
|
12
|
-
>
|
|
11
|
+
> @jolibox/sdk@1.1.4-beta.10 build:esm
|
|
12
|
+
> BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=esm
|
|
13
13
|
|
|
14
14
|
|
|
15
|
-
> @jolibox/sdk@1.
|
|
16
|
-
>
|
|
15
|
+
> @jolibox/sdk@1.1.4-beta.10 build:iife
|
|
16
|
+
> BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=iife
|
|
17
17
|
|
|
@@ -39,29 +39,29 @@ describe('canIUse', () => {
|
|
|
39
39
|
|
|
40
40
|
it('should return true for supported API without properties', () => {
|
|
41
41
|
mockGetCanIUseConfig.mockReturnValue({ version: '0.9.0' });
|
|
42
|
-
expect(canIUse('supportedApi')).toBe(
|
|
42
|
+
expect(canIUse('supportedApi')).toBe(false);
|
|
43
43
|
});
|
|
44
44
|
|
|
45
45
|
it('should check H5 platform configuration', () => {
|
|
46
46
|
//eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
47
47
|
//@ts-ignore
|
|
48
48
|
mockEnv.mockReturnValue({ data: { deviceInfo: { platform: 'h5' } } });
|
|
49
|
-
mockGetCanIUseConfig.mockReturnValue({ version: '0.
|
|
50
|
-
expect(canIUse('webApi')).toBe(
|
|
49
|
+
mockGetCanIUseConfig.mockReturnValue({ version: '1.0.0' });
|
|
50
|
+
expect(canIUse('webApi')).toBe(false);
|
|
51
51
|
expect(mockGetCanIUseConfig).toHaveBeenCalledWith('h5', 'webApi');
|
|
52
52
|
});
|
|
53
53
|
|
|
54
54
|
it('should handle nested property checks', () => {
|
|
55
55
|
mockGetCanIUseConfig.mockReturnValue({
|
|
56
|
-
version: '0.
|
|
56
|
+
version: '1.0.0',
|
|
57
57
|
properties: {
|
|
58
58
|
feature: {
|
|
59
|
-
subFeature: '0.
|
|
59
|
+
subFeature: '1.0.0'
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
});
|
|
63
63
|
|
|
64
|
-
expect(canIUse('api:feature:subFeature')).toBe(
|
|
64
|
+
expect(canIUse('api:feature:subFeature')).toBe(false);
|
|
65
65
|
});
|
|
66
66
|
|
|
67
67
|
it('should return false for unsupported property version', () => {
|
package/src/api/can-i-use.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { env as getEnv } from './get-system-info';
|
|
|
2
2
|
import { isObject, isString, compareVersion } from '@jolibox/common';
|
|
3
3
|
import { getCanIUseConfig, get } from '../utils/can-i-use';
|
|
4
4
|
|
|
5
|
-
const __VERSION__ = '
|
|
5
|
+
const __VERSION__ = '__JOLIBOX_LOCAL_SDK_VERSION__'; // mock
|
|
6
6
|
|
|
7
7
|
export function canIUse(schema: string): boolean {
|
|
8
8
|
const env = getEnv();
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import { createCommands } from '@jolibox/common';
|
|
2
2
|
|
|
3
3
|
const commands = createCommands();
|
|
4
|
-
export async function getSystemInfo() {
|
|
5
|
-
return await commands.executeCommand('API.getSystemInfo');
|
|
6
|
-
}
|
|
7
4
|
|
|
8
5
|
export function getSystemInfoSync() {
|
|
9
6
|
return commands.excuteCommandSync('API.getSystemInfoSync');
|
package/src/api/index.ts
CHANGED
package/src/api/login.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { createCommands } from '@jolibox/common';
|
|
2
|
+
import { canIUse } from './can-i-use';
|
|
3
|
+
import { ResponseType } from '@jolibox/types';
|
|
4
|
+
|
|
5
|
+
const commands = createCommands();
|
|
6
|
+
export async function login() {
|
|
7
|
+
if (!canIUse('login')) {
|
|
8
|
+
return {
|
|
9
|
+
code: 'FAILURE' as ResponseType,
|
|
10
|
+
message: '[Jolibox SDK]login is not supported in this platform'
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
return await commands.executeCommand('API.login');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function checkSession() {
|
|
17
|
+
if (!canIUse('checkSession')) {
|
|
18
|
+
return {
|
|
19
|
+
code: 'FAILURE' as ResponseType,
|
|
20
|
+
message: '[Jolibox SDK]checkSession is not supported in this platform'
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
return await commands.executeCommand('API.checkSession');
|
|
24
|
+
}
|
|
@@ -1,12 +1,26 @@
|
|
|
1
1
|
import { hostEmitter, createCommands, BaseError } from '@jolibox/common';
|
|
2
|
-
document.addEventListener('DOMContentLoaded', () => hostEmitter.emit('onDocumentReady'));
|
|
2
|
+
document.addEventListener('DOMContentLoaded', () => hostEmitter.emit('onDocumentReady', timeline.startTime));
|
|
3
|
+
|
|
4
|
+
const timelineFactory = () => {
|
|
5
|
+
let _beginLoad = 0;
|
|
6
|
+
return {
|
|
7
|
+
set startTime(time: number) {
|
|
8
|
+
_beginLoad = time;
|
|
9
|
+
},
|
|
10
|
+
get startTime(): number {
|
|
11
|
+
return _beginLoad;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const timeline = timelineFactory();
|
|
3
17
|
|
|
4
18
|
const commands = createCommands();
|
|
5
19
|
|
|
6
20
|
const rejectHandler = (event: PromiseRejectionEvent | ErrorEvent | BaseError) => {
|
|
7
21
|
commands
|
|
8
22
|
.executeCommand('ReportSDK.traceSystem', {
|
|
9
|
-
event: '
|
|
23
|
+
event: 'globalJsError',
|
|
10
24
|
info: {
|
|
11
25
|
err: JSON.stringify(event)
|
|
12
26
|
}
|
|
@@ -24,7 +38,7 @@ window.addEventListener('error', rejectHandler.bind(this));
|
|
|
24
38
|
window.onerror = (message, source, lineno, colno, error) => {
|
|
25
39
|
commands
|
|
26
40
|
.executeCommand('ReportSDK.traceSystem', {
|
|
27
|
-
event: '
|
|
41
|
+
event: 'globalJsError',
|
|
28
42
|
info: {
|
|
29
43
|
err: JSON.stringify({
|
|
30
44
|
message,
|
package/src/index.ts
CHANGED
|
@@ -2,28 +2,40 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* global error catch
|
|
4
4
|
*/
|
|
5
|
-
import './
|
|
5
|
+
import './events';
|
|
6
6
|
import './loader';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* @public Jolibox JS SDK Entry
|
|
10
10
|
*/
|
|
11
|
-
import {
|
|
11
|
+
import { getSystemInfoSync, canIUse, login, checkSession } from './api';
|
|
12
12
|
import { RuntimeSDK } from './sdks/runtime';
|
|
13
13
|
import { LifecycleSDK } from './sdks/lifecycle';
|
|
14
14
|
import { StorageSDK } from './sdks/storage';
|
|
15
15
|
import { JoliboxAds } from './sdks/ads';
|
|
16
16
|
import { KeyboardSDK } from './sdks/keyboard';
|
|
17
|
+
import { TaskTrackerSDK } from './sdks/task';
|
|
18
|
+
|
|
19
|
+
declare global {
|
|
20
|
+
interface Window {
|
|
21
|
+
JoliboxSDK: typeof JoliboxSDK; // TODO: code review this @Dengxue
|
|
22
|
+
}
|
|
23
|
+
}
|
|
17
24
|
|
|
18
25
|
export class JoliboxSDK {
|
|
26
|
+
readonly jssdkVersion = '__JOLIBOX_LOCAL_SDK_VERSION__';
|
|
19
27
|
readonly runtime = new RuntimeSDK();
|
|
20
28
|
readonly ads = new JoliboxAds();
|
|
21
29
|
readonly lifecycle = new LifecycleSDK();
|
|
22
30
|
readonly storage = new StorageSDK();
|
|
23
31
|
readonly keyboard = new KeyboardSDK();
|
|
32
|
+
readonly task = new TaskTrackerSDK();
|
|
24
33
|
|
|
25
34
|
//global API
|
|
26
|
-
getSystemInfo = getSystemInfo.bind(this);
|
|
27
35
|
getSystemInfoSync = getSystemInfoSync.bind(this);
|
|
28
36
|
canIUse = canIUse.bind(this);
|
|
37
|
+
login = login.bind(this);
|
|
38
|
+
checkSession = checkSession.bind(this);
|
|
29
39
|
}
|
|
40
|
+
|
|
41
|
+
window.JoliboxSDK = JoliboxSDK; // TODO: code review this @Dengxue
|
package/src/loader/h5.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { compare, major } from './version';
|
|
|
2
2
|
import { track, trackPerformance } from '../utils/report';
|
|
3
3
|
import { InternalJSModuleEvalError, InternalJSModuleFetchError } from '@jolibox/common';
|
|
4
4
|
import { getBoostrapModuleUrl, getImplementModuleUrl } from './index';
|
|
5
|
-
import { reportError } from '../
|
|
5
|
+
import { reportError, timeline } from '../events';
|
|
6
6
|
|
|
7
7
|
const LOCAL_STORE_KEY = 'jolibox-sdk-loadermeta';
|
|
8
8
|
interface LocalStoreMeta {
|
|
@@ -106,9 +106,10 @@ export const createLoadImplement = (params: {
|
|
|
106
106
|
|
|
107
107
|
function loadBootstrapModule() {
|
|
108
108
|
const startToLoad = Date.now();
|
|
109
|
-
track('
|
|
109
|
+
track('jsSdkBegin', {
|
|
110
110
|
t: startToLoad
|
|
111
111
|
});
|
|
112
|
+
timeline.startTime = startToLoad;
|
|
112
113
|
|
|
113
114
|
const { script: currentBootstrapModule, type } = fetchCurrentBootstrapModule() ?? {};
|
|
114
115
|
if (currentBootstrapModule) {
|
|
@@ -136,7 +137,7 @@ export const createLoadImplement = (params: {
|
|
|
136
137
|
}
|
|
137
138
|
|
|
138
139
|
// load remote impletation
|
|
139
|
-
function
|
|
140
|
+
function loadRemoteImplement() {
|
|
140
141
|
const implStartLoad = Date.now();
|
|
141
142
|
const { implement_script, implement_version, timestamp } = CURRENT_VERSION_STORE;
|
|
142
143
|
if (implement_script && implement_version && timestamp) {
|
|
@@ -166,7 +167,7 @@ export const createLoadImplement = (params: {
|
|
|
166
167
|
return () => {
|
|
167
168
|
try {
|
|
168
169
|
loadBootstrapModule();
|
|
169
|
-
|
|
170
|
+
loadRemoteImplement();
|
|
170
171
|
fetchCurrentRemoteScript();
|
|
171
172
|
} catch (e) {
|
|
172
173
|
reportError(new InternalJSModuleEvalError(`module evaluate error: ${e}`));
|
package/src/loader/index.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { major } from './version';
|
|
|
3
3
|
import { createLoadImplement as createH5LoadImplement } from './h5';
|
|
4
4
|
import { createLoadImplement as createNativeLoadImplement } from './native';
|
|
5
5
|
//TODO: temp
|
|
6
|
-
const BUILD_VERSION = '
|
|
6
|
+
const BUILD_VERSION = '__JOLIBOX_LOCAL_SDK_VERSION__';
|
|
7
7
|
const currentVersion = BUILD_VERSION;
|
|
8
8
|
const currentMajorVersion = major(currentVersion);
|
|
9
9
|
|
|
@@ -15,15 +15,27 @@ const currentMajorVersion = major(currentVersion);
|
|
|
15
15
|
|
|
16
16
|
declare global {
|
|
17
17
|
interface Window {
|
|
18
|
-
|
|
18
|
+
JoliAndroidSDKBridge?: unknown;
|
|
19
19
|
webkit?: unknown;
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
|
-
const loadScript =
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
22
|
+
const loadScript =
|
|
23
|
+
window.webkit || window.JoliAndroidSDKBridge
|
|
24
|
+
? (params: { path: string }) => {
|
|
25
|
+
const res = window.prompt(
|
|
26
|
+
'invoke',
|
|
27
|
+
JSON.stringify({
|
|
28
|
+
event: 'loadScriptSync',
|
|
29
|
+
paramsString: JSON.stringify(params)
|
|
30
|
+
})
|
|
31
|
+
);
|
|
32
|
+
if (res) {
|
|
33
|
+
const { data } = JSON.parse(res);
|
|
34
|
+
return data;
|
|
35
|
+
}
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
: undefined;
|
|
27
39
|
|
|
28
40
|
const isNative = typeof loadScript !== 'undefined';
|
|
29
41
|
|
|
@@ -32,16 +44,18 @@ const isNative = typeof loadScript !== 'undefined';
|
|
|
32
44
|
* as this logic needs to remain self-contained within the SDK.
|
|
33
45
|
*/
|
|
34
46
|
export const getBoostrapModuleUrl = (version: string | number) =>
|
|
35
|
-
`
|
|
47
|
+
`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${version}/dist/index.js`;
|
|
36
48
|
export const getImplementModuleUrl = (version: string | number) =>
|
|
37
|
-
`
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const
|
|
49
|
+
`https://cdn.jsdelivr.net/npm/@jolibox/implement@${version}/dist/index.js`;
|
|
50
|
+
|
|
51
|
+
const checkReleaseVersion = (version: string): boolean => {
|
|
52
|
+
const semverRegex = /^\d+\.\d+\.\d+$/;
|
|
53
|
+
return semverRegex.test(version);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const fetchVersion = !checkReleaseVersion(currentVersion) ? currentVersion : currentMajorVersion;
|
|
57
|
+
const IMMEDIATE_SCRIPT_URL = getBoostrapModuleUrl(fetchVersion);
|
|
58
|
+
const REMOTE_IMPLEMENT_URL = getImplementModuleUrl(fetchVersion);
|
|
45
59
|
|
|
46
60
|
/**
|
|
47
61
|
* load entry
|
package/src/loader/native.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { track, trackPerformance } from '@/utils/report';
|
|
2
2
|
import { InternalJSModuleEvalError } from '@jolibox/common';
|
|
3
|
-
import { reportError } from '../
|
|
3
|
+
import { reportError, timeline } from '../events';
|
|
4
4
|
|
|
5
5
|
export const createLoadImplement = (
|
|
6
6
|
loadScript: (params: { path: string }) => string | null,
|
|
@@ -34,9 +34,10 @@ export const createLoadImplement = (
|
|
|
34
34
|
return () => {
|
|
35
35
|
try {
|
|
36
36
|
const startToLoad = Date.now();
|
|
37
|
-
track('
|
|
37
|
+
track('jsSdkBegin', {
|
|
38
38
|
t: startToLoad
|
|
39
39
|
});
|
|
40
|
+
timeline.startTime = startToLoad;
|
|
40
41
|
/**
|
|
41
42
|
* bootstrap module
|
|
42
43
|
*/
|
package/src/sdks/keyboard.ts
CHANGED
|
@@ -8,14 +8,10 @@ export class KeyboardSDK extends BaseSDK implements Keyboard {
|
|
|
8
8
|
* @returns
|
|
9
9
|
*/
|
|
10
10
|
showKeyboard(params: { defaultValue?: string; maxLength?: number; multiple?: boolean }) {
|
|
11
|
-
const
|
|
12
|
-
if (
|
|
13
|
-
return
|
|
14
|
-
code: 'FAILURE' as ResponseType,
|
|
15
|
-
message: `[Jolibox SDK] keyboard.showKeyboard is not supported in this platform`
|
|
16
|
-
};
|
|
11
|
+
const errMsg = this.canIUseIfThrow('keyboard.showKeyboard');
|
|
12
|
+
if (errMsg) {
|
|
13
|
+
return errMsg;
|
|
17
14
|
}
|
|
18
|
-
|
|
19
15
|
this.commands.executeCommand('KeyboardSDK.showKeyboard', params);
|
|
20
16
|
}
|
|
21
17
|
/**
|
|
@@ -24,26 +20,20 @@ export class KeyboardSDK extends BaseSDK implements Keyboard {
|
|
|
24
20
|
* @returns
|
|
25
21
|
*/
|
|
26
22
|
updateKeyboard(value: string) {
|
|
27
|
-
const
|
|
28
|
-
if (
|
|
29
|
-
return
|
|
30
|
-
code: 'FAILURE' as ResponseType,
|
|
31
|
-
message: `[Jolibox SDK] keyboard.updateKeyboard is not supported in this platform`
|
|
32
|
-
};
|
|
23
|
+
const errMsg = this.canIUseIfThrow('keyboard.updateKeyboard');
|
|
24
|
+
if (errMsg) {
|
|
25
|
+
return errMsg;
|
|
33
26
|
}
|
|
34
|
-
this.commands.executeCommand('KeyboardSDK.updateKeyboard', value);
|
|
27
|
+
this.commands.executeCommand('KeyboardSDK.updateKeyboard', { value });
|
|
35
28
|
}
|
|
36
29
|
/**
|
|
37
30
|
* 隐藏键盘
|
|
38
31
|
* @returns
|
|
39
32
|
*/
|
|
40
33
|
hideKeyboard() {
|
|
41
|
-
const
|
|
42
|
-
if (
|
|
43
|
-
return
|
|
44
|
-
code: 'FAILURE' as ResponseType,
|
|
45
|
-
message: `[Jolibox SDK] keyboard.hideKeyboard is not supported in this platform`
|
|
46
|
-
};
|
|
34
|
+
const errMsg = this.canIUseIfThrow('keyboard.hideKeyboard');
|
|
35
|
+
if (errMsg) {
|
|
36
|
+
return errMsg;
|
|
47
37
|
}
|
|
48
38
|
this.commands.executeCommand('KeyboardSDK.hideKeyboard');
|
|
49
39
|
}
|
package/src/sdks/lifecycle.ts
CHANGED
|
@@ -19,14 +19,18 @@ export class LifecycleSDK extends BaseSDK<LifecycleSDKEventMap> implements Lifec
|
|
|
19
19
|
this.commands.executeCommand('LifecycleSDK.onReady', wrappedOnReady.bind(this));
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
|
|
23
|
-
this.
|
|
22
|
+
exit(params: { onBeforeExit: () => void }) {
|
|
23
|
+
const errMsg = this.canIUseIfThrow('lifeCycle.exit');
|
|
24
|
+
if (errMsg) {
|
|
25
|
+
return errMsg;
|
|
26
|
+
}
|
|
27
|
+
this.commands.executeCommand('LifecycleSDK.exit', params.onBeforeExit);
|
|
24
28
|
}
|
|
25
29
|
|
|
26
|
-
|
|
27
|
-
this.commands.executeCommand('LifecycleSDK.
|
|
30
|
+
onJoliboxHide(params: () => void) {
|
|
31
|
+
this.commands.executeCommand('LifecycleSDK.onJoliboxHide', params.bind(this));
|
|
28
32
|
}
|
|
29
|
-
|
|
30
|
-
this.commands.executeCommand('LifecycleSDK.
|
|
33
|
+
onJoliboxShow(params: () => void) {
|
|
34
|
+
this.commands.executeCommand('LifecycleSDK.onJoliboxShow', params.bind(this));
|
|
31
35
|
}
|
|
32
36
|
}
|
package/src/sdks/sdk.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { canIUse } from '@/api';
|
|
2
2
|
import { createCommands, EventEmitter } from '@jolibox/common';
|
|
3
|
+
import { ResponseType } from '@jolibox/types';
|
|
3
4
|
export interface BaseSDKEventMap {
|
|
4
5
|
_baseSDKMarker?: never;
|
|
5
6
|
}
|
|
@@ -19,4 +20,13 @@ export abstract class BaseSDK<T = BaseSDKEventMap> {
|
|
|
19
20
|
canUse(command: string) {
|
|
20
21
|
return canIUse(command);
|
|
21
22
|
}
|
|
23
|
+
|
|
24
|
+
canIUseIfThrow(command: string) {
|
|
25
|
+
if (!this.canUse(command)) {
|
|
26
|
+
return {
|
|
27
|
+
code: 'FAILURE' as ResponseType,
|
|
28
|
+
message: `[Jolibox SDK] ${command} is not supported in this platform`
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
22
32
|
}
|
package/src/sdks/task.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { BaseSDK } from './sdk';
|
|
2
|
+
import { TaskTracker, TaskResponse } from '@jolibox/types';
|
|
3
|
+
|
|
4
|
+
export class TaskTrackerSDK extends BaseSDK implements TaskTracker {
|
|
5
|
+
async onLevelFinished(levelId: string | number, result: boolean, duration: number): Promise<TaskResponse> {
|
|
6
|
+
const errMsg = this.canIUseIfThrow('TaskTrackerSDK.onLevelFinished');
|
|
7
|
+
if (errMsg) {
|
|
8
|
+
return Promise.resolve(errMsg);
|
|
9
|
+
}
|
|
10
|
+
return await this.commands.executeCommand('TaskTrackerSDK.levelFinished', levelId, { result, duration });
|
|
11
|
+
}
|
|
12
|
+
async onTaskFinished(taskId: string | number, duration: number): Promise<TaskResponse> {
|
|
13
|
+
const errMsg = this.canIUseIfThrow('TaskTrackerSDK.onTaskFinished');
|
|
14
|
+
if (errMsg) {
|
|
15
|
+
return errMsg;
|
|
16
|
+
}
|
|
17
|
+
return await this.commands.executeCommand('TaskTrackerSDK.taskFinished', taskId, { duration });
|
|
18
|
+
}
|
|
19
|
+
async onTaskEvent(
|
|
20
|
+
taskId: string | number,
|
|
21
|
+
params: {
|
|
22
|
+
tools?: {
|
|
23
|
+
id: string | number;
|
|
24
|
+
name: string;
|
|
25
|
+
count?: number;
|
|
26
|
+
description?: string;
|
|
27
|
+
price?: {
|
|
28
|
+
amount: number;
|
|
29
|
+
unit: string;
|
|
30
|
+
};
|
|
31
|
+
}[];
|
|
32
|
+
awards?: {
|
|
33
|
+
id: string | number;
|
|
34
|
+
name: string;
|
|
35
|
+
}[];
|
|
36
|
+
}
|
|
37
|
+
): Promise<TaskResponse> {
|
|
38
|
+
const errMsg = this.canIUseIfThrow('TaskTrackerSDK.onTaskEvent');
|
|
39
|
+
if (errMsg) {
|
|
40
|
+
return errMsg;
|
|
41
|
+
}
|
|
42
|
+
return await this.commands.executeCommand('TaskTrackerSDK.taskEvent', taskId, params);
|
|
43
|
+
}
|
|
44
|
+
async onLevelUpgrade(levelId: string | number, name: string): Promise<TaskResponse> {
|
|
45
|
+
const errMsg = this.canIUseIfThrow('TaskTrackerSDK.onLevelUpgrade');
|
|
46
|
+
if (errMsg) {
|
|
47
|
+
return errMsg;
|
|
48
|
+
}
|
|
49
|
+
return await this.commands.executeCommand('TaskTrackerSDK.levelUpgrade', levelId, name);
|
|
50
|
+
}
|
|
51
|
+
async onHistoryUserLevel(level: number): Promise<TaskResponse> {
|
|
52
|
+
const errMsg = this.canIUseIfThrow('TaskTrackerSDK.onHistoryUserLevel');
|
|
53
|
+
if (errMsg) {
|
|
54
|
+
return errMsg;
|
|
55
|
+
}
|
|
56
|
+
return await this.commands.executeCommand('TaskTrackerSDK.historyUserLevel', level);
|
|
57
|
+
}
|
|
58
|
+
async onHistoryUserScore(score: number): Promise<TaskResponse> {
|
|
59
|
+
const errMsg = this.canIUseIfThrow('TaskTrackerSDK.onHistoryUserScore');
|
|
60
|
+
if (errMsg) {
|
|
61
|
+
return errMsg;
|
|
62
|
+
}
|
|
63
|
+
return await this.commands.executeCommand('TaskTrackerSDK.historyUserScore', score);
|
|
64
|
+
}
|
|
65
|
+
}
|
package/dist/index.es.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var W=Object.defineProperty,Ie=Object.getOwnPropertyDescriptor,Ue=(e,t)=>{for(var r in t)W(e,r,{get:t[r],enumerable:!0})},Q=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ie(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&&W(t,r,s),s};function Ae(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function k(e){return typeof e=="string"}function Y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function Le(e){return typeof e>"u"}function we(e){return Le(e)||e===null}function Ce(e){return typeof e=="function"}function X(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Te=(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))(Te||{}),De=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}},q=class extends De{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var Z=class extends q{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},y=class extends q{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function R(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Oe={log:R("log"),warn:R("warn"),info:R("info"),error:R("error"),debug:R("debug")};Object.assign(globalThis,{logger:Oe});var ee=Symbol.for("Jolibox.canIUseMap"),Ne={};globalThis[ee]=Ne;var te={get config(){return globalThis[ee]}};function j(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 _=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(_>c){n=1;break}else if(_<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}},Ke=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}},Pe=0,I=class{constructor(e){this.value=e,this.id=Pe++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof I&&(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 I(e);this._listeners?this._listeners instanceof I?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 I?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},J=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 Ke,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},P={};Ue(P,{None:()=>Me,filter:()=>je,once:()=>re,toPromise:()=>ke});var Me=()=>{console.log("[Jolibox SDK] None Event")};function ke(e){return new Promise(t=>re(e)(t))}function re(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function je(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"),Je=()=>{let e=new J;return globalThis[N]||(globalThis[N]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[N]},ne=Je();function Fe(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)Be(e[n],t[n])}function Be(e,t){if(k(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Ce(t)){try{if(e instanceof t)return}catch{}if(!we(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 A=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 Fe(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}};A=Q([X],A);var M=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new A,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ae(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),P.toPromise(P.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}}};M=Q([X],M);var K=Symbol.for("Jolibox.commands");function h(){if(globalThis[K])return globalThis[K];let e=new A,t=new M,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[K]=r,r}document.addEventListener("DOMContentLoaded",()=>ne.emit("onDocumentReady"));var se=h(),F=e=>{se.executeCommand("ReportSDK.traceSystem",{event:"global_js_error",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},g=F;window.addEventListener("unhandledrejection",F.bind(void 0));window.addEventListener("error",F.bind(void 0));window.onerror=(e,t,r,n,s)=>{se.executeCommand("ReportSDK.traceSystem",{event:"global_js_error",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 B=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}},S=e=>parseInt(B(e).major,10),b=(e,t)=>{let{major:r,minor:n,patch:s}=B(e),{major:o,minor:i,patch:l}=B(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var oe=h(),L=(e,t)=>{oe.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},E=(e,t,r)=>{oe.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var ce="jolibox-sdk-loadermeta",x=JSON.parse(localStorage.getItem(ce)??"{}"),V=Date.now(),ie=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,ae=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Ve(){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={...x,timestamp:V};if(n){let{bootstrap_version:o}=x;if(!(o&&b(o,n))){let i=await(await fetch(G(n))).text();ae(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=x;if(!(o&&b(o,r))){let i=await(await fetch($(r))).text();ae(i)&&(s={...s,implement_version:r,implement_script:i})}}localStorage.setItem(ce,JSON.stringify(s))}catch(t){console.warn("Failed to fetch loader metadata: ",t)}}var me=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:c,bootstrap_script:p,timestamp:d}=x;if(c&&p&&d&&!ie(V,d)&&S(c)==t&&b(c,r)>0)return{script:p,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){g(new Z(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();L("js_sdk_begin",{t:c});let{script:p,type:d}=o()??{};if(p){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=p,document.head.appendChild(m),E("bootstrapModuleLoaded",Date.now()-c,{type:d})}}function l(c){(async d=>{try{let m=new Blob([d],{type:"application/javascript"}),f=URL.createObjectURL(m),xe=await import(f);return URL.revokeObjectURL(f),xe}catch(m){g(new y(`implement module evaluate error in h5:${m} `))}})(c)}function _(){let c=Date.now(),{implement_script:p,implement_version:d,timestamp:m}=x;if(p&&d&&m&&!ie(V,m)&&S(d)==t&&b(d,r)>0){l(p),E("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let f=document.createElement("script");f.type="module",f.crossOrigin="anonymous",f.src=s,f.onload=()=>{E("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(f)}return()=>{try{i(),_(),Ve()}catch(c){g(new y(`module evaluate error: ${c}`))}}};var le=(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"}),_=URL.createObjectURL(l),c=await import(_);return URL.revokeObjectURL(_),c}catch(l){g(new y(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();L("js_sdk_begin",{t:s});let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),E("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),E("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),g(new y(`module load failed ${s}`))}}};var Ge="1.0.0",pe=Ge,H=S(pe),fe=window.webkit?e=>window.prompt("loadScript",JSON.stringify(e)):void 0,$e=typeof fe<"u",G=e=>`http://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,$=e=>`http://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,de=G(H),ue=$(H);function He(){$e?le(fe,{bootstrapUrl:de,implementUrl:ue})():me({bootstrapUrl:de,implementUrl:ue,currentMajorVersion:H,currentVersion:pe})()}He();var z=h();async function he(){return await z.executeCommand("API.getSystemInfo")}function _e(){return z.excuteCommandSync("API.getSystemInfoSync")}function ge(){return z.excuteCommandSync("API.env")}function Ee(e,t){return te.config[e]?.[t]}function ye(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 ve="1.0.0";function w(e){let r=ge().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Ee(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||j(ve,i,"<")?!1:s.length===0?!0:Re(o,s)||Re(o.properties,s)}function Re(e,t){if(!e)return!1;let r=ye(e,t);return r?Y(r)?!0:k(r)?j(ve,r,">="):!1:!1}var Se=window.JoliboxRuntime;var u=class{constructor(){this.commands=h();this._emitter=new J}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return w(t)}};var ze="LifecycleSDK.onReady",C=class extends u{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(ze,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exitGame(t){this.commands.executeCommand("LifecycleSDK.exitGame",t.onBeforeExit)}onGameHide(t){this.commands.executeCommand("LifecycleSDK.onGameHide",t.bind(this))}onGameShow(t){this.commands.executeCommand("LifecycleSDK.onGameShow",t.bind(this))}};var T=class extends u{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 D=class extends u{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 O=class extends u{showKeyboard(t){if(!this.canUse("keyboard.showKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.showKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){if(!this.canUse("keyboard.updateKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.updateKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.updateKeyboard",t)}hideKeyboard(){if(!this.canUse("keyboard.hideKeyboard"))return{code:"FAILURE",message:"[Jolibox SDK] keyboard.hideKeyboard is not supported in this platform"};this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var be=class{constructor(){this.runtime=new Se;this.ads=new D;this.lifecycle=new C;this.storage=new T;this.keyboard=new O;this.getSystemInfo=he.bind(this);this.getSystemInfoSync=_e.bind(this);this.canIUse=w.bind(this)}};export{be as JoliboxSDK};
|