@singcl/ad-execute-manager 1.17.4 → 1.17.6
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/LICENSE +20 -20
- package/dist/ad-reward/src/RewardAdNovel.d.ts +13 -0
- package/dist/analytics/src/AdAnalyticsJS.d.ts +3 -2
- package/dist/index.cjs +2 -2
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025-present, singcl
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-present, singcl
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
21
|
SOFTWARE.
|
|
@@ -213,6 +213,19 @@ declare class RewardAdNovel extends RewardAdFather {
|
|
|
213
213
|
* @param {boolean} [args.preserved] 是否在超时情况下保留广告实例 - 自用参数,非tt API要求的参数
|
|
214
214
|
*/
|
|
215
215
|
private _setAdTimeout;
|
|
216
|
+
/**
|
|
217
|
+
* @protected
|
|
218
|
+
* 广告展示超时设置
|
|
219
|
+
* @param {object} _args
|
|
220
|
+
* @param {string} _args.scene 广告执行场景 必填
|
|
221
|
+
* @param {number} [_args.timeout] 广告超时时间 单位ms
|
|
222
|
+
* @param {Function} _args.end 结束当前广告任务的回调函数 必填
|
|
223
|
+
*/
|
|
224
|
+
protected customExecuteAfterTimeout(_args: {
|
|
225
|
+
scene: string;
|
|
226
|
+
timeout?: number;
|
|
227
|
+
end: Function;
|
|
228
|
+
}): void;
|
|
216
229
|
/**
|
|
217
230
|
* 子类可以选择覆盖此方法
|
|
218
231
|
* 添加超时情况下结束任务前的回调
|
|
@@ -89,9 +89,10 @@ declare class AdAnalyticsJS {
|
|
|
89
89
|
/**
|
|
90
90
|
* 获取公共用户信息
|
|
91
91
|
* @public
|
|
92
|
-
* @
|
|
92
|
+
* @param {string|number} v - key
|
|
93
|
+
* @returns {unknown}
|
|
93
94
|
*/
|
|
94
|
-
public getCommonInfo():
|
|
95
|
+
public getCommonInfo(v: string | number): unknown;
|
|
95
96
|
/**
|
|
96
97
|
* 获取埋点公共用户信息
|
|
97
98
|
* @protected
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";const __rslib_import_meta_url__="u"<typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{Storage:()=>src_Storage,CountRecorder:()=>CountRecorder,RewardAdFather:()=>src_RewardAdFather,InterstitialAdFather:()=>src_InterstitialAdFather,InterstitialAdDrama:()=>src_InterstitialAdNovel,default:()=>packages_0,EventEmitter:()=>EventEmitter,InterstitialAdNovel:()=>src_InterstitialAdNovel,PubSub:()=>PubSub,RewardAdNovel:()=>src_RewardAdNovel,AdAnalyticsJS:()=>src_AdAnalyticsJS,Logger:()=>Logger,SerializableError:()=>SerializableError,AdExecuteManager:()=>src_AdExecuteManager,RewardAdDrama:()=>src_RewardAdNovel});class Logger{constructor(e={}){const{prefix:t="Logger",level:r="log",enabled:i=!0}=e;this.prefix=t,this.enabled=i,this.levels={error:0,warn:1,info:2,log:3,debug:4},this.currentLevel=this.levels[r]||this.levels.log}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}setLevel(e){Object.prototype.hasOwnProperty.call(this.levels,e)&&(this.currentLevel=this.levels[e])}formatMessage(e,t){let r=new Date,i=`${r.getFullYear()}/${r.getMonth()+1}/${r.getDate()} ${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}`;return`[${i}] [${e.toUpperCase()}] [${this.prefix}] ${t}`}_log(e,t,...r){if(!this.enabled)return;let i=this.levels[e];if(void 0!==i&&this.currentLevel>=i){let i=this.formatMessage(e,t);switch(e){case"error":console.error(i,...r);break;case"warn":console.warn(i,...r);break;case"info":console.info(i,...r);break;case"log":default:console.log(i,...r);break;case"debug":console.debug(i,...r)}}}error(e,...t){this._log("error",e,...t)}warn(e,...t){this._log("warn",e,...t)}info(e,...t){this._log("info",e,...t)}log(e,...t){this._log("log",e,...t)}debug(e,...t){this._log("debug",e,...t)}}function isTimeoutError(e,t){return e?.errMsg&&"string"==typeof e.errMsg&&e.errMsg.startsWith("ad_show_timeout: normal")&&e?.timeout==t}function isBackgroundError(e){return e?.errMsg&&"string"==typeof e.errMsg&&(e.errMsg.startsWith("app in background is not support show ad")||e.errMsg.startsWith("other controller is presented"))}function needRetryAdError({apiError:e,configuredAdTimeout:t,errorRetryStrategy:r}){return!!(r?.timeout&&isTimeoutError(e,t)||r?.background&&isBackgroundError(e))}const compose=e=>e.map(e=>(t,r)=>async i=>await e(Object.assign({},t,i),r)).reduce((e,t)=>(r,i)=>e(r,t(r,i))),src_compose=compose;class AdExecuteManager{static _instance=null;_taskStack=[];_currentBatchTasks=[];_isRunning=!1;_currentTask=null;_isForeground=!0;_appShowListener=null;_appHideListener=null;_enableVisibilityListener=!1;_maxRetryCount=1;_retryQueue=[];_errorRetryStrategy={timeout:!0,background:!0};constructor(e){this.logger=new Logger({prefix:"AdExecuteManager",enabled:!!e?.log}),e?.errorRetryStrategy&&(this._errorRetryStrategy=Object.assign({},this._errorRetryStrategy,e?.errorRetryStrategy)),this._enableVisibilityListener=e?.enableVisibilityListener,this._maxRetryCount=e?.maxRetryCount??1,this._enableVisibilityListener&&this._initVisibilityListener()}initialize(e){return this}static getInstance(e){return AdExecuteManager._instance||(AdExecuteManager._instance=new AdExecuteManager(e)),AdExecuteManager._instance}static build(e){return AdExecuteManager._instance||(AdExecuteManager._instance=new AdExecuteManager(e)),AdExecuteManager._instance}static new(e){return new AdExecuteManager(e)}static getSafeInstance(){return AdExecuteManager._instance?AdExecuteManager._instance:(this.logger.error("AdExecuteManager实例不存在"),null)}_initVisibilityListener(){!("u"<typeof tt)&&tt.onAppShow&&tt.onAppHide?(this._appShowListener=()=>{this._isForeground=!0,this._handleAppShow()},this._appHideListener=()=>{this._isForeground=!1,this._handleAppHide()},tt.onAppShow(this._appShowListener),tt.onAppHide(this._appHideListener),this.logger.info("前后台监听器已初始化")):this.logger.warn("tt API不可用,无法监听前后台状态")}_handleAppHide(){if(this._isRunning&&this._currentBatchTasks.length>0){let e=this._currentBatchTasks.filter(e=>e.id!==this._currentTask?.id&&!e._isResolved&&!e._isRejected);e.length>0&&(this.logger.info(`将 ${e.length} 个未执行的任务放回任务栈,任务ID: ${e.map(e=>e.id).join(",")}`),this._taskStack=[...e,...this._taskStack],this._currentBatchTasks=this._currentBatchTasks.filter(t=>!e.some(e=>e.id===t.id)))}}_handleAppShow(){this._retryQueue.length>0&&(this.logger.info(`应用进入前台:优先执行重试队列,任务数: ${this._retryQueue.length}, 任务ID: ${this._retryQueue.map(e=>e.id).join(",")}`),this._taskStack=[...this._retryQueue,...this._taskStack],this._retryQueue=[]),this._taskStack.length>0&&!this._isRunning&&(this.logger.info(`应用进入前台:恢复待执行任务数: ${this._taskStack.length}, 任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._compose())}destroyVisibilityListener(){this._appShowListener&&"u">typeof tt&&tt.offAppShow&&(tt.offAppShow(this._appShowListener),this._appShowListener=null),this._appHideListener&&"u">typeof tt&&tt.offAppHide&&(tt.offAppHide(this._appHideListener),this._appHideListener=null),this.logger.info("前后台监听器已销毁")}enableVisibilityListener(){this._enableVisibilityListener||(this._enableVisibilityListener=!0,this._initVisibilityListener()),this.logger.info("前后台监听器已启用")}disableVisibilityListener(){this._enableVisibilityListener&&(this._enableVisibilityListener=!1,this.destroyVisibilityListener()),this.logger.info("前后台监听器已禁用")}isVisibilityListenerEnabled(){return this._enableVisibilityListener}addTask(e,t){return e&&"function"==typeof e.ad?new Promise((r,i)=>{let s={adInstance:e,options:t.options??{},callbackCollection:t.collection??{},resolve:r,reject:i,id:`ad_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_isResolved:!1,_isRejected:!1,_retryCount:0,_retryMsg:"ok"};this._taskStack.push(s),this._isRunning||this._compose()}):(this.logger.error("无效的广告实例 请正确实现.ad方法"),Promise.reject(Error("无效的广告实例")))}_compose(){if(0===this._taskStack.length){this._isRunning=!1,this._currentTask=null;return}if(!this._isForeground){this.logger.info(`应用处于后台,暂停任务执行,任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._isRunning=!1;return}this._isRunning=!0;let e=[...this._taskStack];this._taskStack=[],this._currentBatchTasks=e;let t=e.map(e=>async(t,r)=>{let{adInstance:i,options:s,callbackCollection:n,resolve:o,id:a,_retryCount:l,_retryMsg:d}=e,h={count:l,retry:l>0,message:d};if(e._isResolved||e._isRejected)return void await r(t);this._currentTask=e;try{let l=async e=>{await r(Object.assign({},t,e))},d=await i.initialize(s).ad({options:s,collection:n,recovered:h},l),_=Object.assign({id:a,recovered:h},d);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(_)}`),needRetryAdError({apiError:_?.apiError,configuredAdTimeout:i._adTimeoutTime,errorRetryStrategy:this._errorRetryStrategy})&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++,e._retryMsg=_?.apiError?.errMsg||"unknown";let t=`任务 ${a} 在后台失败,加入重试队列 (即将第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount}, 重试原因: ${e._retryMsg})`;this.logger.warn(t),_.recovered.retry=!0,_.recovered.count=e._retryCount,_.recovered.message=e._retryMsg,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;o(_),i?.record(_)}catch(n){let s=Object.assign({id:a,apiError:n,recovered:h});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(s)}`),e._isRejected=!0;try{i?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:a,apiError:e})))}o(s),i?.record(s),await r(t)}}),r={roundTasks:t.length};compose(t)(r,async e=>{this.logger.info("本轮活动队列已经清空",e),this._taskStack.length>0?Promise.resolve().then(()=>{this._compose()}):(this._isRunning=!1,this._currentTask=null,this._currentBatchTasks=[])})()}clearTasks(){if(this._currentTask){if(this._currentTask._isResolved||this._currentTask._isRejected){this._currentTask=null;return}try{this._currentTask.callbackCollection&&this._currentTask.callbackCollection.cancel&&this._currentTask.callbackCollection.cancel(),this._currentTask._isResolved=!0,this._currentTask.resolve()}catch(e){this.logger.error("clear current task error: ",e)}this._currentTask=null}this._currentBatchTasks.length>0&&(this._currentBatchTasks.forEach(e=>{if(e!==this._currentTask&&!e._isResolved&&!e._isRejected)try{e.callbackCollection&&e.callbackCollection.cancel&&e.callbackCollection.cancel(),e._isResolved=!0,e.resolve()}catch(e){this.logger.error("clear current batch task error: ",e)}}),this._currentBatchTasks=[]),this._taskStack.forEach(e=>{if(!e._isResolved&&!e._isRejected&&(e._isResolved=!0,e.resolve(),e.callbackCollection&&e.callbackCollection.cancel))try{e.callbackCollection.cancel()}catch(e){this.logger.error("clear task error: ",e)}}),this._retryQueue.forEach(e=>{if(!e._isResolved&&!e._isRejected&&(e._isResolved=!0,e.resolve(),e.callbackCollection&&e.callbackCollection.cancel))try{e.callbackCollection.cancel()}catch(e){this.logger.error("clear retry task error: ",e)}}),this._taskStack=[],this._retryQueue=[],this._isRunning=!1}getTaskCount(){return this._taskStack.filter(e=>!e._isResolved&&!e._isRejected).length+this._currentBatchTasks.filter(e=>e!==this._currentTask&&!e._isResolved&&!e._isRejected).length+(!this._currentTask||this._currentTask._isResolved||this._currentTask._isRejected?0:1)+this._retryQueue.filter(e=>!e._isResolved&&!e._isRejected).length}isRunning(){return this._isRunning}getCurrentTaskId(){return this._currentTask?.id||null}whenAllTasksComplete(){return new Promise(e=>{let t=null,r=()=>{let i=0===this._taskStack.length,s=!this._isRunning,n=null===this._currentTask,o=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),a=0===this._retryQueue.length;i&&s&&n&&o&&a?(t&&clearTimeout(t),e()):t=setTimeout(r,500)};r()})}}const src_AdExecuteManager=AdExecuteManager;class SerializableError extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.stack=Error(e).stack,this.errMsg=t.errMsg,this.errorCode=t.errorCode,Object.defineProperty(this,"message",{enumerable:!0}),Object.defineProperty(this,"name",{enumerable:!0}),Object.defineProperty(this,"stack",{enumerable:!0}),Object.defineProperty(this,"errMsg",{enumerable:!0}),Object.defineProperty(this,"errorCode",{enumerable:!0})}toJSON(){return{name:this.name,message:this.message,stack:this.stack,errMsg:this.errMsg,errorCode:this.errorCode}}}class RewardAdFather{static args=null;_logger=null;_adTimeoutTime=8e3;_initSign="";_preserveOnEnd=!1;_rewardAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302];__bindAdErrorForeverHandler=this.__adErrorForeverHandler.bind(this);constructor(e){this._logger=new Logger({prefix:"RewardAdFather",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return this._logger.warn("rewardAd has been initialized"),t?.(this._rewardAd),this;let r=Object.assign({},RewardAdFather.args,this._adConfig,e);if(!r.adUnitId)throw this._logger.error("reward args The adUnitId is required",r),new SerializableError("[RewardAdFather] reward args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100002});let i=tt.createRewardedVideoAd(r);return this._logger.info("bindAdErrorForeverHandler at initialized:",e?.foreverErrorBind),e?.foreverErrorBind&&(i?.offError(this.__bindAdErrorForeverHandler),i?.onError(this.__bindAdErrorForeverHandler)),this._rewardAd=i,this.__ad__=i,t?.(this._rewardAd),this}initialized(){return!!this._rewardAd}__adErrorForeverHandler(e){this.adErrorForeverHandler(e)}adErrorForeverHandler(e){return null}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return RewardAdFather.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(e=!1){return!this._rewardAd||this._preserveOnEnd||e?Promise.reject({errMsg:`can not destroy,ad is: ${!!this._rewardAd}, preserved: ${e}, preservedOnEnd: ${this._preserveOnEnd}`,errorCode:110003}):this._rewardAd.destroy().then(e=>Promise.resolve(e))?.catch(e=>Promise.reject({errMsg:`rewardAd destroy failed: ${JSON.stringify(e)}`,errorCode:110004}))?.finally(()=>{this._rewardAd=null})}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._rewardAd&&this._rewardAd.onClose(e)}offClose(e){this._rewardAd&&this._rewardAd.offClose(e)}show(){return this._rewardAd?this._rewardAd.show():Promise.reject({errMsg:"[RewardAdFather] can not show,rewardAd is null",errorCode:110001})}load(){return this._rewardAd?this._rewardAd.load():Promise.reject({errMsg:"[RewardAdFather] can not load,rewardAd is null",errorCode:110002})}onError(e){this._rewardAd&&this._rewardAd.onError(e)}offError(e){this._rewardAd&&this._rewardAd.offError(e)}onLoad(e){this._rewardAd&&this._rewardAd.onLoad(e)}offLoad(e){this._rewardAd&&this._rewardAd.offLoad(e)}placeholder(){return null}static buildArgs(e){e?.adUnitId||new Logger({prefix:"RewardAdFather",enable:!0}).error("RewardParams.adUnitId is required"),RewardAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof RewardAdFather?src_AdExecuteManager.getInstance().addTask(e,t):(new Logger({prefix:"RewardAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const src_RewardAdFather=RewardAdFather;function matchErrorWithKeywords(e,t){return!!t&&e.some(e=>RegExp(e,"i").test(t))}function getAdSceneTextObj(e){return Object.entries(e).reduce((e,[t,r])=>(e[r]=Number(t),e),{})}const DEFAULT_SCENT_TYPE_OBJ={9999:"inner_default_other"},DEFAULT_SCENT_TEXT_OBJ=getAdSceneTextObj(DEFAULT_SCENT_TYPE_OBJ),AD_TYPE_ENUM={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2},AD_TYPE_ENUM_REVERSE=Object.entries(AD_TYPE_ENUM).reduce((e,[t,r])=>(e[r]=t,e),{});class RewardAdNovel extends src_RewardAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_adExecuteArgs=null;_adNext=null;_scene=DEFAULT_SCENT_TEXT_OBJ.inner_default_other;_eId=null;_adTypeR=AD_TYPE_ENUM.AD_TYPE_REWARD;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_lookUpRemainOnError=!1;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.__adCloseLister__.bind(this);bindAdErrorLister=this.__adErrorLister__.bind(this);bindAdLoadLister=this.__adLoadLister__.bind(this);bindApiAdErrorLister=this.__apiAdErrorLister__.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);bindAdTimeoutCloseLister=this.__adTimeoutCloseLister__.bind(this);bindAdTimeoutErrorLister=this.__adTimeoutErrorLister__.bind(this);constructor(e){super(e),this._logger=new Logger({prefix:"RewardAdNovel",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._needEndOnTimeout=e?.needEndOnTimeout??!0,this._lookUpRemainOnError=e?.lookUpRemainOnError??!1,this._onHalfway=e?.collection?.onHalfway??null,this._onShow=e?.collection?.onShow??null,this._onFinish=e?.collection?.onFinish??null,this._onAlways=e?.collection?.onAlways??null,this._onError=e?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=RewardAdNovelConfig.new({retry:e?.retry})}_onInnerExecuteBefore(e){return null}_onAdExecuteBefore(e){return null}_onInnerAdShowSuccess(e){return null}_onInnerAdDestroySuccess(e){return null}_onInnerAdDestroyFailed(e){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let r="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,eId:this._eId,msg:r,errorCode:1e5,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:r,errorCode:1e5}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout){let t=e?.timeout??this._adTimeoutTime;this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,eId:this._eId,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),this._adTimeoutBeforeEnd({scene:e?.scene,timeout:t}),this.onClose(this.bindAdTimeoutCloseLister),this.onError(this.bindAdTimeoutErrorLister),e?.end({preserved:e?.preserved,resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})},t)}}_adTimeoutBeforeEnd(e){return e}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearInterval(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}ad(e,t=null){return this._alwaysCallback=e?.collection?.always,this._halfwayCallback=e?.collection?.halfway,this._finishedCallback=e?.collection?.finished,this._recovered=e?.recovered,this._preservedOnTimeout=e?.options?.preservedOnTimeout,this._adExecuteArgs=e,this._adNext=t,this._onAdExecuteBefore({eId:this._eId}),new Promise(r=>{this._resolve=r,this._adInner({options:{scene:e?.options?.scene,timeout:e?.options?.timeout},collection:{resolve:r,before:e.collection?.before,success:e.collection?.success,prelude:e.collection?.prelude},recovered:e.recovered},t)})}_adInner(e,t=null){this._eId=`ead_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,this._onInnerExecuteBefore({eId:this._eId});let r=e?.collection?.resolve,i=e?.options?.scene??this._scene??DEFAULT_SCENT_TEXT_OBJ.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,a=e?.recovered??this._recovered,l=e=>{this._clearAdTimeout(),this.adDestroy(e?.preserved),r?.(Object.assign({scene:i,adTypeR:this._adTypeR,eId:this._eId},e?.resolvedValue)),this._resolve=null,t?.(Object.assign({scene:i},e?.nextValue)),this._next=null,this._adExecuteArgs=null,this._adNext=null},d=()=>{this._scene=i,s?.({scene:i}),this._before=s,this._onShow?.({scene:i}),this._adShowBeforeAnalytics({scene:i,eId:this._eId}),this._resolve=r,this._next=t,this._setAdTimeout({scene:i,end:l,timeout:e?.options?.timeout,preserved:this._preservedOnTimeout}),this._adPreludeInterval({scene:i,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:i}),this._success=n,this._adShowSuccessAnalytics({scene:i,eId:this._eId,result:1,recovered:a}),this._onInnerAdShowSuccess({scene:i,eId:this._eId,result:1,recovered:a})}).catch(e=>{(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:i,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),matchErrorWithKeywords(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?l({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:i,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
|
|
2
|
-
tt: {errMsg: ${e?.errMsg}, errorCode: ${e?.errorCode}}`,errorCode:1e5}},nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:i,result:1,frequency:this.novelConfig.frequency}),d()}).catch(e=>{this._adLoadFailureAnalytics({scene:i,msg:e?.errMsg,result:0}),l({scene:i,resolvedValue:{apiError:e},nextValue:null})}))})};d()}adCircleInner(e){let t={scene:e?.options?.scene??this._adExecuteArgs?.options?.scene,timeout:e?.options?.timeout??this._adExecuteArgs?.options?.timeout},r={resolve:this._resolve,before:e?.collection?.before??this._adExecuteArgs?.collection?.before,success:e?.collection?.success??this._adExecuteArgs?.collection?.success,prelude:e?.collection?.prelude??this._adExecuteArgs?.collection?.prelude};this._adInner({options:t,collection:r,recovered:this._adExecuteArgs?.recovered},this._adNext)}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(...e){return this._alwaysCallback?.(...e)}onExeAlways(...e){return this._alwaysCallback?.(...e)}_outerHalfwayCallback(...e){return this._halfwayCallback?.(...e)}onExeHalfway(...e){return this._halfwayCallback?.(...e)}_outerFinishedCallback(...e){return this._finishedCallback?.(...e)}onExeFinished(...e){return this._finishedCallback?.(...e)}onFinish(...e){return this._onFinish?.(...e)}onHalfway(...e){return this._onHalfway?.(...e)}onAlways(...e){return this._onAlways?.(...e)}__adTimeoutCloseLister__(e){let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId});this._logger.warn("ad close lister that after task end because timeout:",t),this._clearAdTimeout(),this.offClose(this.bindAdTimeoutCloseLister),this.adTimeoutCloseLister(t)}adTimeoutCloseLister(e){return e}__adTimeoutErrorLister__(e){let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId});this._logger.error("ad error lister that after task end because timeout:",t),this._clearAdTimeout(),this.offError(this.bindAdTimeoutErrorLister),this.adTimeoutErrorLister(t)}adTimeoutErrorLister(e){return e}__adCloseLister__(e){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:+!!e.isEnded,ad_count:e.count});let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId,end_type:e.isEnded?"finished":"halfway"}),r=e=>{this.adDestroy(),this._resolve?.(Object.assign({},t,e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null},i=e=>{let r=Object.assign({},t,e);r?.isEnded?(this._outerFinishedCallback(r),this.onExeFinished(r),this._onFinish?.(r),this.onFinish(r)):(this._outerHalfwayCallback(r),this.onExeHalfway(r),this._onHalfway?.(r),this.onHalfway(r)),this._outerCloseCallback(r),this.onExeAlways(r),this._onAlways?.(r),this.onAlways(r)};this.adCloseLister(t,{conn:i,end:r})}adCloseLister(e,t){t?.conn?.(e),t?.end?.(e)}__adErrorLister__(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adErrorLister(e);let t=()=>{this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR,eId:this._eId}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null};(!this._lookUpRemainOnError||0>=this.novelConfig.remain())&&t()}adErrorLister(e){return e}__apiAdErrorLister__(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.apiAdErrorLister(e),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}apiAdErrorLister(e){return e}__adLoadLister__(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e})),this.adLoadLister(e)}adLoadLister(e){return e}__novelDestroy__(e){this.destroy(e?.preserved).then(e=>{this._onInnerAdDestroySuccess?.({scene:this._scene,eId:this._eId,errMsg:e})}).catch(e=>{this._logger.warn("ad destroy failed:",JSON.stringify(e)),this._onInnerAdDestroyFailed?.({scene:this._scene,eId:this._eId,errorCode:e?.errorCode,errMsg:e?.errMsg})})}adDestroy(e=!1){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.__novelDestroy__({preserved:e})}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.__novelDestroy__(),this._resolve=null,this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.offClose(this._bindShiftCloseLister),this.__novelDestroy__(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.offError(this._bindShiftErrorLister),this.__novelDestroy__(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return RewardAdNovel.instance||(RewardAdNovel.instance=new RewardAdNovel(e)),RewardAdNovel.instance}static getInstance(){if(!RewardAdNovel.instance)throw Error("RewardAdNovel instance is not init");return RewardAdNovel.instance}static new(e){return new RewardAdNovel(e)}}class RewardAdNovelConfig{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new RewardAdNovelConfig(e)}}const src_RewardAdNovel=RewardAdNovel;class InterstitialAdFather{static args=null;_logger=null;_initSign="";_preserveOnEnd=!1;_interstitialAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302,140502];constructor(e){this._logger=new Logger({prefix:"InterstitialAdFather",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._interstitialAd)return this._logger.warn("interstitialAd has been initialized"),t?.(this._interstitialAd),this;let r=Object.assign({},InterstitialAdFather.args,this._adConfig,e);if(!r.adUnitId)throw this._logger.error("interstitialAd args The adUnitId is required",r),new SerializableError("[InterstitialAdFather] interstitialAd args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100003});let i=tt.createInterstitialAd(r);return this._interstitialAd=i,this.__ad__=i,t?.(this._interstitialAd),this}initialized(){return!!this._interstitialAd}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return InterstitialAdFather.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){this._interstitialAd&&!this._preserveOnEnd&&(this._interstitialAd.destroy(),this._interstitialAd=null)}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._interstitialAd&&this._interstitialAd.onClose(e)}offClose(e){this._interstitialAd&&this._interstitialAd.offClose(e)}show(){return this._interstitialAd?this._interstitialAd.show():Promise.reject({errMsg:"[InterstitialAdFather] can not show,interstitialAd is null",errorCode:120001})}load(){return this._interstitialAd?this._interstitialAd.load():Promise.reject({errMsg:"[InterstitialAdFather] can not load,interstitialAd is null",errorCode:120002})}onError(e){this._interstitialAd&&this._interstitialAd.onError(e)}offError(e){this._interstitialAd&&this._interstitialAd.offError(e)}onLoad(e){this._interstitialAd&&this._interstitialAd.onLoad(e)}offLoad(e){this._interstitialAd&&this._interstitialAd.offLoad(e)}placeholder(){return null}static buildArgs(e){e?.adUnitId||new Logger({prefix:"InterstitialAdFather",enable:!0}).error("interstitialAdParams.adUnitId is required"),InterstitialAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof InterstitialAdFather?src_AdExecuteManager.getInstance().addTask(e,t):(new Logger({prefix:"InterstitialAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const src_InterstitialAdFather=InterstitialAdFather;function functional_matchErrorWithKeywords(e,t){return!!t&&e.some(e=>RegExp(e,"i").test(t))}function functional_getAdSceneTextObj(e){return Object.entries(e).reduce((e,[t,r])=>(e[r]=Number(t),e),{})}const const_DEFAULT_SCENT_TYPE_OBJ={9999:"inner_default_other"},const_DEFAULT_SCENT_TEXT_OBJ=functional_getAdSceneTextObj(const_DEFAULT_SCENT_TYPE_OBJ),const_AD_TYPE_ENUM={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2},const_AD_TYPE_ENUM_REVERSE=Object.entries(const_AD_TYPE_ENUM).reduce((e,[t,r])=>(e[r]=t,e),{});class InterstitialAdNovel extends src_InterstitialAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=const_DEFAULT_SCENT_TEXT_OBJ.inner_default_other;_adTypeR=const_AD_TYPE_ENUM.AD_TYPE_INTERSTITIAL;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.adCloseLister.bind(this);bindAdErrorLister=this.adErrorLister.bind(this);bindAdLoadLister=this.adLoadLister.bind(this);bindApiAdErrorLister=this.apiAdErrorLister.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);constructor(e){super(e),this._logger=new Logger({prefix:"InterstitialAdNovel",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._needEndOnTimeout=e?.needEndOnTimeout??!0,this._onHalfway=e?.collection?.onHalfway??null,this._onShow=e?.collection?.onShow??null,this._onFinish=e?.collection?.onFinish??null,this._onAlways=e?.collection?.onAlways??null,this._onError=e?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=InterstitialAdNovel_RewardAdNovelConfig.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let r="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,msg:r,errorCode:100001,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:r,errorCode:100001}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout&&(this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case, scene:",e?.scene),this._adShowFailureAnalytics({scene:e?.scene,msg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001}},nextValue:null})},this._adTimeoutTime))}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearTimeout(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}ad(e,t=null){return this._alwaysCallback=e?.collection?.always,this._halfwayCallback=e?.collection?.halfway,this._finishedCallback=e?.collection?.finished,this._onInnerExecuteBefore(),new Promise(r=>{this._adInner({options:{scene:e?.options?.scene},collection:{resolve:r,before:e.collection?.before,success:e.collection?.success,prelude:e.collection?.prelude}},t)})}_adInner(e,t=null){let r=e?.collection?.resolve,i=e?.options?.scene??this._scene??const_DEFAULT_SCENT_TEXT_OBJ.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,a=e=>{this._clearAdTimeout(),this.adDestroy(),r?.(Object.assign({scene:i,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:i},e?.nextValue))},l=()=>{this._scene=i,s?.({scene:i}),this._before=s,this._onShow?.({scene:i}),this._adShowBeforeAnalytics({scene:i}),this._resolve=r,this._next=t,this._setAdTimeout({scene:i,end:a}),this._adPreludeInterval({scene:i,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:i}),this._success=n,this._adShowSuccessAnalytics({scene:i,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:i,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),functional_matchErrorWithKeywords(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?a({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?a({scene:i,resolvedValue:null,nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:i,result:1}),l()}).catch(e=>{this._adLoadFailureAnalytics({scene:i,msg:e?.errMsg,result:0}),a({scene:i,resolvedValue:{apiError:e},nextValue:null})}))})};l()}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(e){this._alwaysCallback?.(e)}_outerHalfwayCallback(e){this._halfwayCallback?.(e)}_outerFinishedCallback(e){this._finishedCallback?.(e)}adCloseLister(){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:1});let e={scene:this._scene},t=e=>{this.adDestroy(),this._resolve?.(Object.assign({},{scene:this._scene,adTypeR:this._adTypeR},e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null};this._outerFinishedCallback(e),this._onFinish?.(e),this._outerHalfwayCallback(e),this._onHalfway?.(e),this._outerCloseCallback(e),this._onAlways?.(e),t({end_type:"finished"})}adErrorLister(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this._onError?.(e),0>=this.novelConfig.remain()&&(this.adDestroy(),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null)}apiAdErrorLister(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}adLoadLister(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e}))}adDestroy(){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy()}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy(),this._resolve=null,this._next=null,this._success=null,this._before=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offClose(this._bindShiftCloseLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offError(this._bindShiftErrorLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return InterstitialAdNovel.instance||(InterstitialAdNovel.instance=new InterstitialAdNovel(e)),InterstitialAdNovel.instance}static getInstance(){if(!InterstitialAdNovel.instance)throw Error("InterstitialAdNovel instance is not init");return InterstitialAdNovel.instance}static new(e){return new InterstitialAdNovel(e)}}class InterstitialAdNovel_RewardAdNovelConfig{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new InterstitialAdNovel_RewardAdNovelConfig(e)}}const src_InterstitialAdNovel=InterstitialAdNovel;class Storage{constructor(e={}){this.config={prefix:"storage_",expire:null,...e},this.logger=new Logger({prefix:"Storage"})}getTodayEndTimestamp(){let e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),23,59,59,999).getTime()}_setItem(e,t,r){let i=void 0!==r?r:this.config.expire;"today"===i&&(i=this.getTodayEndTimestamp()-Date.now());let s={value:t,expire:i,timestamp:Date.now()};try{tt.setStorageSync(e,JSON.stringify(s))}catch(e){console.error("Storage setItem error:",e)}}_getItem(e){try{let t=tt.getStorageSync(e);if(!t)return null;let r=JSON.parse(t);if(r.expire&&Date.now()-r.timestamp>r.expire)return this.removeItem(e),null;return r.value}catch(e){return console.error("Storage getItem error:",e),null}}setItem(e,t,r){let i=this.config.prefix+e;return this._setItem(i,t,r)}getItem(e){let t=this.config.prefix+e;return this._getItem(t)}getUserItem(e){let t=this.config.userId??"null";if("null"===t)return this.logger.error("userId is required"),null;let r=`${this.config.prefix}_${t}_${e}`;return this._getItem(r)}setUserItem(e,t,r){let i=this.config.userId??"null";if("null"===i)return void this.logger.error("userId is required");let s=`${this.config.prefix}_${i}_${e}`;return this._setItem(s,t,r)}removeUserItem(e){let t=this.config.userId??"null";if("null"===t)return void this.logger.error("userId is required");let r=`${this.config.prefix}_${t}_${e}`;try{tt.removeStorageSync(r)}catch(e){console.error("Storage removeUserItem error:",e)}}removeItem(e){try{tt.removeStorageSync(e)}catch(e){console.error("Storage removeItem error:",e)}}clear(){try{tt.clearStorageSync()}catch(e){console.error("Storage clear error:",e)}}keys(){try{let e=[];return(tt.getStorageInfoSync().keys??[]).forEach(t=>{if(t.startsWith(this.config.prefix)){let r=JSON.parse(tt.getStorageSync(t));(!r.expire||Date.now()-r.timestamp<=r.expire)&&e.push(t.replace(this.config.prefix,""))}}),e}catch(e){return console.error("Storage keys error:",e),[]}}static new(e){return new Storage(e)}}const src_Storage=Storage;class CountRecorder{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=src_Storage.new({userId:e.userId}),!e.local_sign)throw Error("local_sign is required");this._local_sign=e.local_sign,this._total=e.total??0,this._expire=e.expire??"today",this._init()}_init(){this._initLocalTimes()}_adTimes(){return this._total}_safeLocalValue(e){return"object"!=typeof e||null===e?{}:e}_initLocalTimes(){let e=this._adTimes(),t=this.storage.getUserItem(this._local_sign),r=this._safeLocalValue(t);r&&r?.total==e||this.storage.setUserItem(this._local_sign,{total:e,today:r?.today??0},this._expire)}updateToday(){let e=this._adTimes(),t=this.storage.getUserItem(this._local_sign),r=this._safeLocalValue(t),i=r?.today??0;this.storage.setUserItem(this._local_sign,{total:e,today:i+1},this._expire)}remain(){let e=this.storage.getUserItem(this._local_sign),t=this._safeLocalValue(e),r=t?.today??0;return Number(t?.total??0)-Number(r)}save(e){let t=e;"number"!=typeof t&&(t=0);let r=this._adTimes();this.storage.setUserItem(this._local_sign,{total:r,today:t},this._expire)}clear(){this.storage.removeUserItem(this._local_sign)}reset(){let e=this._adTimes();this.storage.setUserItem(this._local_sign,{total:e,today:0},this._expire)}static new(e){return new CountRecorder(e)}}class PubSub{constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.off(e,t)}}off(e,t){if(this.events[e]){if(!t){this.events[e]=[];return}this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,...t){this.events[e]&&this.events[e].forEach(r=>{try{r(...t)}catch(t){console.error(`Error in event listener for ${e}:`,t)}})}once(e,t){let r=(...i)=>{t(...i),this.off(e,r)};this.on(e,r)}listenerCount(e){return this.events[e]?this.events[e].length:0}removeAllListeners(){this.events={}}}class EventEmitter{constructor(e={}){this.events={},this.queues={},this.onceEvents={},this.maxListeners=e.maxListeners||5,this.maxQueueSize=e.maxQueueSize||1,this.maxOnceEvents=e.maxOnceEvents||5}on(e,t){(this.events[e]||(this.events[e]=[]),this.events[e].length>=this.maxListeners)?console.warn(`EventEmitter: Maximum listeners (${this.maxListeners}) reached for event "${e}". Listener not added.`):(this.events[e].push(t),this.queues[e]&&this.queues[e].length>0&&(this.queues[e].forEach(e=>{t(...e)}),this.queues[e]=[]))}once(e,t){let r=(...i)=>{t(...i),this.off(e,r)};(this.onceEvents[e]||(this.onceEvents[e]=new Set),this.onceEvents[e].size>=this.maxOnceEvents)?console.warn(`EventEmitter: Maximum once events (${this.maxOnceEvents}) reached for event "${e}". Once listener not added.`):(this.onceEvents[e].add(r),this.on(e,r))}emit(e,...t){this.events[e]&&this.events[e].length>0?[...this.events[e]].forEach(e=>{e(...t)}):(this.queues[e]||(this.queues[e]=[]),this.queues[e].length>=this.maxQueueSize&&(console.warn(`EventEmitter: Maximum queue size (${this.maxQueueSize}) reached for event "${e}". Oldest event removed.`),this.queues[e].shift()),this.queues[e].push(t))}off(e,t){if(!t){this.events[e]=[],this.onceEvents[e]=new Set;return}this.events[e]=this.events[e].filter(e=>e!==t),this.onceEvents[e]&&this.onceEvents[e].delete(t)}removeAllListeners(e){e?(delete this.events[e],delete this.queues[e],delete this.onceEvents[e]):(this.events={},this.queues={},this.onceEvents={})}static geInstance(e){return this._instance||(this._instance=new EventEmitter(e)),this._instance}}class AdAnalyticsJS{static instance=null;_logger=null;_initSign="";_needReport=!1;constructor(e){if(AdAnalyticsJS.instance)return AdAnalyticsJS.instance;this._logger=new Logger({prefix:"AdAnalyticsJS",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._needReport=e?.needReport??!1,this._commonConfig=e?.commonConfig??null,AdAnalyticsJS.instance=this}initialize(e){return this._needReport?e:void this._logger.warn("needReport is false, do not report")}track(e,t,r){if(!this._needReport)return;if(!e)throw Error("eventName is required");let i=Object.assign({},this.getTrackCommonInfo(),t),s=r?.sign??"track";this._logger.log(`---------${s}----------:`,e,i),tt.reportAnalytics(e,i)}getCommonInfo(){return this._commonConfig??{}}getTrackCommonInfo(){return this._commonConfig??{}}identify(e,t){if(!e&&0!==e)throw Error("identify user_id is required");return this._commonConfig=Object.assign({},this._commonConfig,{__user_id:e},t),this}alias(){return null}pages(){return null}page(e,t){this.track(e,t,{sign:"page"})}cpage(e){return this.page("cpage",e)}placeholder(){return null}static build(e){return AdAnalyticsJS.instance||(AdAnalyticsJS.instance=new AdAnalyticsJS(e)),AdAnalyticsJS.instance}static getInstance(){if(!AdAnalyticsJS.instance)throw Error("AdAnalyticsJS instance is not init");return AdAnalyticsJS.instance}static new(e){return new AdAnalyticsJS(e)}}const src_AdAnalyticsJS=AdAnalyticsJS,packages_0=src_AdExecuteManager;for(var __rspack_i in exports.AdAnalyticsJS=__webpack_exports__.AdAnalyticsJS,exports.AdExecuteManager=__webpack_exports__.AdExecuteManager,exports.CountRecorder=__webpack_exports__.CountRecorder,exports.EventEmitter=__webpack_exports__.EventEmitter,exports.InterstitialAdDrama=__webpack_exports__.InterstitialAdDrama,exports.InterstitialAdFather=__webpack_exports__.InterstitialAdFather,exports.InterstitialAdNovel=__webpack_exports__.InterstitialAdNovel,exports.Logger=__webpack_exports__.Logger,exports.PubSub=__webpack_exports__.PubSub,exports.RewardAdDrama=__webpack_exports__.RewardAdDrama,exports.RewardAdFather=__webpack_exports__.RewardAdFather,exports.RewardAdNovel=__webpack_exports__.RewardAdNovel,exports.SerializableError=__webpack_exports__.SerializableError,exports.Storage=__webpack_exports__.Storage,exports.default=__webpack_exports__.default,__webpack_exports__)-1===["AdAnalyticsJS","AdExecuteManager","CountRecorder","EventEmitter","InterstitialAdDrama","InterstitialAdFather","InterstitialAdNovel","Logger","PubSub","RewardAdDrama","RewardAdFather","RewardAdNovel","SerializableError","Storage","default"].indexOf(__rspack_i)&&(exports[__rspack_i]=__webpack_exports__[__rspack_i]);Object.defineProperty(exports,"__esModule",{value:!0});
|
|
1
|
+
"use strict";const __rslib_import_meta_url__="u"<typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{Storage:()=>src_Storage,CountRecorder:()=>CountRecorder,RewardAdFather:()=>src_RewardAdFather,InterstitialAdFather:()=>src_InterstitialAdFather,InterstitialAdDrama:()=>src_InterstitialAdNovel,default:()=>packages_0,EventEmitter:()=>EventEmitter,InterstitialAdNovel:()=>src_InterstitialAdNovel,PubSub:()=>PubSub,RewardAdNovel:()=>src_RewardAdNovel,AdAnalyticsJS:()=>src_AdAnalyticsJS,Logger:()=>Logger,SerializableError:()=>SerializableError,AdExecuteManager:()=>src_AdExecuteManager,RewardAdDrama:()=>src_RewardAdNovel});class Logger{constructor(e={}){const{prefix:t="Logger",level:r="log",enabled:i=!0}=e;this.prefix=t,this.enabled=i,this.levels={error:0,warn:1,info:2,log:3,debug:4},this.currentLevel=this.levels[r]||this.levels.log}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}setLevel(e){Object.prototype.hasOwnProperty.call(this.levels,e)&&(this.currentLevel=this.levels[e])}formatMessage(e,t){let r=new Date,i=`${r.getFullYear()}/${r.getMonth()+1}/${r.getDate()} ${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}`;return`[${i}] [${e.toUpperCase()}] [${this.prefix}] ${t}`}_log(e,t,...r){if(!this.enabled)return;let i=this.levels[e];if(void 0!==i&&this.currentLevel>=i){let i=this.formatMessage(e,t);switch(e){case"error":console.error(i,...r);break;case"warn":console.warn(i,...r);break;case"info":console.info(i,...r);break;case"log":default:console.log(i,...r);break;case"debug":console.debug(i,...r)}}}error(e,...t){this._log("error",e,...t)}warn(e,...t){this._log("warn",e,...t)}info(e,...t){this._log("info",e,...t)}log(e,...t){this._log("log",e,...t)}debug(e,...t){this._log("debug",e,...t)}}function isTimeoutError(e,t){return e?.errMsg&&"string"==typeof e.errMsg&&e.errMsg.startsWith("ad_show_timeout: normal")&&e?.timeout==t}function isBackgroundError(e){return e?.errMsg&&"string"==typeof e.errMsg&&(e.errMsg.startsWith("app in background is not support show ad")||e.errMsg.startsWith("other controller is presented"))}function needRetryAdError({apiError:e,configuredAdTimeout:t,errorRetryStrategy:r}){return!!(r?.timeout&&isTimeoutError(e,t)||r?.background&&isBackgroundError(e))}const compose=e=>e.map(e=>(t,r)=>async i=>await e(Object.assign({},t,i),r)).reduce((e,t)=>(r,i)=>e(r,t(r,i))),src_compose=compose;class AdExecuteManager{static _instance=null;_taskStack=[];_currentBatchTasks=[];_isRunning=!1;_currentTask=null;_isForeground=!0;_appShowListener=null;_appHideListener=null;_enableVisibilityListener=!1;_maxRetryCount=1;_retryQueue=[];_errorRetryStrategy={timeout:!0,background:!0};constructor(e){this.logger=new Logger({prefix:"AdExecuteManager",enabled:!!e?.log}),e?.errorRetryStrategy&&(this._errorRetryStrategy=Object.assign({},this._errorRetryStrategy,e?.errorRetryStrategy)),this._enableVisibilityListener=e?.enableVisibilityListener,this._maxRetryCount=e?.maxRetryCount??1,this._enableVisibilityListener&&this._initVisibilityListener()}initialize(e){return this}static getInstance(e){return AdExecuteManager._instance||(AdExecuteManager._instance=new AdExecuteManager(e)),AdExecuteManager._instance}static build(e){return AdExecuteManager._instance||(AdExecuteManager._instance=new AdExecuteManager(e)),AdExecuteManager._instance}static new(e){return new AdExecuteManager(e)}static getSafeInstance(){return AdExecuteManager._instance?AdExecuteManager._instance:(this.logger.error("AdExecuteManager实例不存在"),null)}_initVisibilityListener(){!("u"<typeof tt)&&tt.onAppShow&&tt.onAppHide?(this._appShowListener=()=>{this._isForeground=!0,this._handleAppShow()},this._appHideListener=()=>{this._isForeground=!1,this._handleAppHide()},tt.onAppShow(this._appShowListener),tt.onAppHide(this._appHideListener),this.logger.info("前后台监听器已初始化")):this.logger.warn("tt API不可用,无法监听前后台状态")}_handleAppHide(){if(this._isRunning&&this._currentBatchTasks.length>0){let e=this._currentBatchTasks.filter(e=>e.id!==this._currentTask?.id&&!e._isResolved&&!e._isRejected);e.length>0&&(this.logger.info(`将 ${e.length} 个未执行的任务放回任务栈,任务ID: ${e.map(e=>e.id).join(",")}`),this._taskStack=[...e,...this._taskStack],this._currentBatchTasks=this._currentBatchTasks.filter(t=>!e.some(e=>e.id===t.id)))}}_handleAppShow(){this._retryQueue.length>0&&(this.logger.info(`应用进入前台:优先执行重试队列,任务数: ${this._retryQueue.length}, 任务ID: ${this._retryQueue.map(e=>e.id).join(",")}`),this._taskStack=[...this._retryQueue,...this._taskStack],this._retryQueue=[]),this._taskStack.length>0&&!this._isRunning&&(this.logger.info(`应用进入前台:恢复待执行任务数: ${this._taskStack.length}, 任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._compose())}destroyVisibilityListener(){this._appShowListener&&"u">typeof tt&&tt.offAppShow&&(tt.offAppShow(this._appShowListener),this._appShowListener=null),this._appHideListener&&"u">typeof tt&&tt.offAppHide&&(tt.offAppHide(this._appHideListener),this._appHideListener=null),this.logger.info("前后台监听器已销毁")}enableVisibilityListener(){this._enableVisibilityListener||(this._enableVisibilityListener=!0,this._initVisibilityListener()),this.logger.info("前后台监听器已启用")}disableVisibilityListener(){this._enableVisibilityListener&&(this._enableVisibilityListener=!1,this.destroyVisibilityListener()),this.logger.info("前后台监听器已禁用")}isVisibilityListenerEnabled(){return this._enableVisibilityListener}addTask(e,t){return e&&"function"==typeof e.ad?new Promise((r,i)=>{let s={adInstance:e,options:t.options??{},callbackCollection:t.collection??{},resolve:r,reject:i,id:`ad_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_isResolved:!1,_isRejected:!1,_retryCount:0,_retryMsg:"ok"};this._taskStack.push(s),this._isRunning||this._compose()}):(this.logger.error("无效的广告实例 请正确实现.ad方法"),Promise.reject(Error("无效的广告实例")))}_compose(){if(0===this._taskStack.length){this._isRunning=!1,this._currentTask=null;return}if(!this._isForeground){this.logger.info(`应用处于后台,暂停任务执行,任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._isRunning=!1;return}this._isRunning=!0;let e=[...this._taskStack];this._taskStack=[],this._currentBatchTasks=e;let t=e.map(e=>async(t,r)=>{let{adInstance:i,options:s,callbackCollection:n,resolve:o,id:a,_retryCount:l,_retryMsg:d}=e,h={count:l,retry:l>0,message:d};if(e._isResolved||e._isRejected)return void await r(t);this._currentTask=e;try{let l=async e=>{await r(Object.assign({},t,e))},d=await i.initialize(s).ad({options:s,collection:n,recovered:h},l),_=Object.assign({id:a,recovered:h},d);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(_)}`),needRetryAdError({apiError:_?.apiError,configuredAdTimeout:i._adTimeoutTime,errorRetryStrategy:this._errorRetryStrategy})&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++,e._retryMsg=_?.apiError?.errMsg||"unknown";let t=`任务 ${a} 在后台失败,加入重试队列 (即将第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount}, 重试原因: ${e._retryMsg})`;this.logger.warn(t),_.recovered.retry=!0,_.recovered.count=e._retryCount,_.recovered.message=e._retryMsg,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;o(_),i?.record(_)}catch(n){let s=Object.assign({id:a,apiError:n,recovered:h});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(s)}`),e._isRejected=!0;try{i?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:a,apiError:e})))}o(s),i?.record(s),await r(t)}}),r={roundTasks:t.length};compose(t)(r,async e=>{this.logger.info("本轮活动队列已经清空",e),this._taskStack.length>0?Promise.resolve().then(()=>{this._compose()}):(this._isRunning=!1,this._currentTask=null,this._currentBatchTasks=[])})()}clearTasks(){if(this._currentTask){if(this._currentTask._isResolved||this._currentTask._isRejected){this._currentTask=null;return}try{this._currentTask.callbackCollection&&this._currentTask.callbackCollection.cancel&&this._currentTask.callbackCollection.cancel(),this._currentTask._isResolved=!0,this._currentTask.resolve()}catch(e){this.logger.error("clear current task error: ",e)}this._currentTask=null}this._currentBatchTasks.length>0&&(this._currentBatchTasks.forEach(e=>{if(e!==this._currentTask&&!e._isResolved&&!e._isRejected)try{e.callbackCollection&&e.callbackCollection.cancel&&e.callbackCollection.cancel(),e._isResolved=!0,e.resolve()}catch(e){this.logger.error("clear current batch task error: ",e)}}),this._currentBatchTasks=[]),this._taskStack.forEach(e=>{if(!e._isResolved&&!e._isRejected&&(e._isResolved=!0,e.resolve(),e.callbackCollection&&e.callbackCollection.cancel))try{e.callbackCollection.cancel()}catch(e){this.logger.error("clear task error: ",e)}}),this._retryQueue.forEach(e=>{if(!e._isResolved&&!e._isRejected&&(e._isResolved=!0,e.resolve(),e.callbackCollection&&e.callbackCollection.cancel))try{e.callbackCollection.cancel()}catch(e){this.logger.error("clear retry task error: ",e)}}),this._taskStack=[],this._retryQueue=[],this._isRunning=!1}getTaskCount(){return this._taskStack.filter(e=>!e._isResolved&&!e._isRejected).length+this._currentBatchTasks.filter(e=>e!==this._currentTask&&!e._isResolved&&!e._isRejected).length+(!this._currentTask||this._currentTask._isResolved||this._currentTask._isRejected?0:1)+this._retryQueue.filter(e=>!e._isResolved&&!e._isRejected).length}isRunning(){return this._isRunning}getCurrentTaskId(){return this._currentTask?.id||null}whenAllTasksComplete(){return new Promise(e=>{let t=null,r=()=>{let i=0===this._taskStack.length,s=!this._isRunning,n=null===this._currentTask,o=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),a=0===this._retryQueue.length;i&&s&&n&&o&&a?(t&&clearTimeout(t),e()):t=setTimeout(r,500)};r()})}}const src_AdExecuteManager=AdExecuteManager;class SerializableError extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.stack=Error(e).stack,this.errMsg=t.errMsg,this.errorCode=t.errorCode,Object.defineProperty(this,"message",{enumerable:!0}),Object.defineProperty(this,"name",{enumerable:!0}),Object.defineProperty(this,"stack",{enumerable:!0}),Object.defineProperty(this,"errMsg",{enumerable:!0}),Object.defineProperty(this,"errorCode",{enumerable:!0})}toJSON(){return{name:this.name,message:this.message,stack:this.stack,errMsg:this.errMsg,errorCode:this.errorCode}}}class RewardAdFather{static args=null;_logger=null;_adTimeoutTime=8e3;_initSign="";_preserveOnEnd=!1;_rewardAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302];__bindAdErrorForeverHandler=this.__adErrorForeverHandler.bind(this);constructor(e){this._logger=new Logger({prefix:"RewardAdFather",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return this._logger.warn("rewardAd has been initialized"),t?.(this._rewardAd),this;let r=Object.assign({},RewardAdFather.args,this._adConfig,e);if(!r.adUnitId)throw this._logger.error("reward args The adUnitId is required",r),new SerializableError("[RewardAdFather] reward args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100002});let i=tt.createRewardedVideoAd(r);return this._logger.info("bindAdErrorForeverHandler at initialized:",e?.foreverErrorBind),e?.foreverErrorBind&&(i?.offError(this.__bindAdErrorForeverHandler),i?.onError(this.__bindAdErrorForeverHandler)),this._rewardAd=i,this.__ad__=i,t?.(this._rewardAd),this}initialized(){return!!this._rewardAd}__adErrorForeverHandler(e){this.adErrorForeverHandler(e)}adErrorForeverHandler(e){return null}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return RewardAdFather.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(e=!1){return!this._rewardAd||this._preserveOnEnd||e?Promise.reject({errMsg:`can not destroy,ad is: ${!!this._rewardAd}, preserved: ${e}, preservedOnEnd: ${this._preserveOnEnd}`,errorCode:110003}):this._rewardAd.destroy().then(e=>Promise.resolve(e))?.catch(e=>Promise.reject({errMsg:`rewardAd destroy failed: ${JSON.stringify(e)}`,errorCode:110004}))?.finally(()=>{this._rewardAd=null})}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._rewardAd&&this._rewardAd.onClose(e)}offClose(e){this._rewardAd&&this._rewardAd.offClose(e)}show(){return this._rewardAd?this._rewardAd.show():Promise.reject({errMsg:"[RewardAdFather] can not show,rewardAd is null",errorCode:110001})}load(){return this._rewardAd?this._rewardAd.load():Promise.reject({errMsg:"[RewardAdFather] can not load,rewardAd is null",errorCode:110002})}onError(e){this._rewardAd&&this._rewardAd.onError(e)}offError(e){this._rewardAd&&this._rewardAd.offError(e)}onLoad(e){this._rewardAd&&this._rewardAd.onLoad(e)}offLoad(e){this._rewardAd&&this._rewardAd.offLoad(e)}placeholder(){return null}static buildArgs(e){e?.adUnitId||new Logger({prefix:"RewardAdFather",enable:!0}).error("RewardParams.adUnitId is required"),RewardAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof RewardAdFather?src_AdExecuteManager.getInstance().addTask(e,t):(new Logger({prefix:"RewardAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const src_RewardAdFather=RewardAdFather;function matchErrorWithKeywords(e,t){return!!t&&e.some(e=>RegExp(e,"i").test(t))}function getAdSceneTextObj(e){return Object.entries(e).reduce((e,[t,r])=>(e[r]=Number(t),e),{})}const DEFAULT_SCENT_TYPE_OBJ={9999:"inner_default_other"},DEFAULT_SCENT_TEXT_OBJ=getAdSceneTextObj(DEFAULT_SCENT_TYPE_OBJ),AD_TYPE_ENUM={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2},AD_TYPE_ENUM_REVERSE=Object.entries(AD_TYPE_ENUM).reduce((e,[t,r])=>(e[r]=t,e),{});class RewardAdNovel extends src_RewardAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_adExecuteArgs=null;_adNext=null;_scene=DEFAULT_SCENT_TEXT_OBJ.inner_default_other;_eId=null;_adTypeR=AD_TYPE_ENUM.AD_TYPE_REWARD;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_lookUpRemainOnError=!1;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.__adCloseLister__.bind(this);bindAdErrorLister=this.__adErrorLister__.bind(this);bindAdLoadLister=this.__adLoadLister__.bind(this);bindApiAdErrorLister=this.__apiAdErrorLister__.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);bindAdTimeoutCloseLister=this.__adTimeoutCloseLister__.bind(this);bindAdTimeoutErrorLister=this.__adTimeoutErrorLister__.bind(this);constructor(e){super(e),this._logger=new Logger({prefix:"RewardAdNovel",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._needEndOnTimeout=e?.needEndOnTimeout??!0,this._lookUpRemainOnError=e?.lookUpRemainOnError??!1,this._onHalfway=e?.collection?.onHalfway??null,this._onShow=e?.collection?.onShow??null,this._onFinish=e?.collection?.onFinish??null,this._onAlways=e?.collection?.onAlways??null,this._onError=e?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=RewardAdNovelConfig.new({retry:e?.retry})}_onInnerExecuteBefore(e){return null}_onAdExecuteBefore(e){return null}_onInnerAdShowSuccess(e){return null}_onInnerAdDestroySuccess(e){return null}_onInnerAdDestroyFailed(e){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let r="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,eId:this._eId,msg:r,errorCode:1e5,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:r,errorCode:1e5}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout){let t=e?.timeout??this._adTimeoutTime;this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,eId:this._eId,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),this._adTimeoutBeforeEnd({scene:e?.scene,timeout:t}),this.onClose(this.bindAdTimeoutCloseLister),this.onError(this.bindAdTimeoutErrorLister);let r=()=>{e?.end({preserved:e?.preserved,resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})};try{this.customExecuteAfterTimeout({scene:e?.scene,timeout:t,end:r})}catch(e){this._logger.warn("use default timeout end task logic:",e),r()}},t)}}customExecuteAfterTimeout(e){throw Error("customExecuteAfterTimeout not be implemented")}_adTimeoutBeforeEnd(e){return e}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearInterval(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}ad(e,t=null){return this._alwaysCallback=e?.collection?.always,this._halfwayCallback=e?.collection?.halfway,this._finishedCallback=e?.collection?.finished,this._recovered=e?.recovered,this._preservedOnTimeout=e?.options?.preservedOnTimeout,this._adExecuteArgs=e,this._adNext=t,this._onAdExecuteBefore({eId:this._eId}),new Promise(r=>{this._resolve=r,this._adInner({options:{scene:e?.options?.scene,timeout:e?.options?.timeout},collection:{resolve:r,before:e.collection?.before,success:e.collection?.success,prelude:e.collection?.prelude},recovered:e.recovered},t)})}_adInner(e,t=null){this._eId=`ead_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,this._onInnerExecuteBefore({eId:this._eId});let r=e?.collection?.resolve,i=e?.options?.scene??this._scene??DEFAULT_SCENT_TEXT_OBJ.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,a=e?.recovered??this._recovered,l=e=>{this._clearAdTimeout(),this.adDestroy(e?.preserved),r?.(Object.assign({scene:i,adTypeR:this._adTypeR,eId:this._eId},e?.resolvedValue)),this._resolve=null,t?.(Object.assign({scene:i},e?.nextValue)),this._next=null,this._adExecuteArgs=null,this._adNext=null},d=()=>{this._scene=i,s?.({scene:i}),this._before=s,this._onShow?.({scene:i}),this._adShowBeforeAnalytics({scene:i,eId:this._eId}),this._resolve=r,this._next=t,this._setAdTimeout({scene:i,end:l,timeout:e?.options?.timeout,preserved:this._preservedOnTimeout}),this._adPreludeInterval({scene:i,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:i}),this._success=n,this._adShowSuccessAnalytics({scene:i,eId:this._eId,result:1,recovered:a}),this._onInnerAdShowSuccess({scene:i,eId:this._eId,result:1,recovered:a})}).catch(e=>{(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:i,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),matchErrorWithKeywords(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?l({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:i,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
|
|
2
|
+
tt: {errMsg: ${e?.errMsg}, errorCode: ${e?.errorCode}}`,errorCode:1e5}},nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:i,result:1,frequency:this.novelConfig.frequency}),d()}).catch(e=>{this._adLoadFailureAnalytics({scene:i,msg:e?.errMsg,result:0}),l({scene:i,resolvedValue:{apiError:e},nextValue:null})}))})};d()}adCircleInner(e){let t={scene:e?.options?.scene??this._adExecuteArgs?.options?.scene,timeout:e?.options?.timeout??this._adExecuteArgs?.options?.timeout},r={resolve:this._resolve,before:e?.collection?.before??this._adExecuteArgs?.collection?.before,success:e?.collection?.success??this._adExecuteArgs?.collection?.success,prelude:e?.collection?.prelude??this._adExecuteArgs?.collection?.prelude};this._adInner({options:t,collection:r,recovered:this._adExecuteArgs?.recovered},this._adNext)}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(...e){return this._alwaysCallback?.(...e)}onExeAlways(...e){return this._alwaysCallback?.(...e)}_outerHalfwayCallback(...e){return this._halfwayCallback?.(...e)}onExeHalfway(...e){return this._halfwayCallback?.(...e)}_outerFinishedCallback(...e){return this._finishedCallback?.(...e)}onExeFinished(...e){return this._finishedCallback?.(...e)}onFinish(...e){return this._onFinish?.(...e)}onHalfway(...e){return this._onHalfway?.(...e)}onAlways(...e){return this._onAlways?.(...e)}__adTimeoutCloseLister__(e){let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId});this._logger.warn("ad close lister that after task end because timeout:",t),this._clearAdTimeout(),this.offClose(this.bindAdTimeoutCloseLister),this.adTimeoutCloseLister(t)}adTimeoutCloseLister(e){return e}__adTimeoutErrorLister__(e){let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId});this._logger.error("ad error lister that after task end because timeout:",t),this._clearAdTimeout(),this.offError(this.bindAdTimeoutErrorLister),this.adTimeoutErrorLister(t)}adTimeoutErrorLister(e){return e}__adCloseLister__(e){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:+!!e.isEnded,ad_count:e.count});let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId,end_type:e.isEnded?"finished":"halfway"}),r=e=>{this.adDestroy(),this._resolve?.(Object.assign({},t,e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null},i=e=>{let r=Object.assign({},t,e);r?.isEnded?(this._outerFinishedCallback(r),this.onExeFinished(r),this._onFinish?.(r),this.onFinish(r)):(this._outerHalfwayCallback(r),this.onExeHalfway(r),this._onHalfway?.(r),this.onHalfway(r)),this._outerCloseCallback(r),this.onExeAlways(r),this._onAlways?.(r),this.onAlways(r)};this.adCloseLister(t,{conn:i,end:r})}adCloseLister(e,t){t?.conn?.(e),t?.end?.(e)}__adErrorLister__(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adErrorLister(e);let t=()=>{this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR,eId:this._eId}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null};(!this._lookUpRemainOnError||0>=this.novelConfig.remain())&&t()}adErrorLister(e){return e}__apiAdErrorLister__(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.apiAdErrorLister(e),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}apiAdErrorLister(e){return e}__adLoadLister__(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e})),this.adLoadLister(e)}adLoadLister(e){return e}__novelDestroy__(e){this.destroy(e?.preserved).then(e=>{this._onInnerAdDestroySuccess?.({scene:this._scene,eId:this._eId,errMsg:e})}).catch(e=>{this._logger.warn("ad destroy failed:",JSON.stringify(e)),this._onInnerAdDestroyFailed?.({scene:this._scene,eId:this._eId,errorCode:e?.errorCode,errMsg:e?.errMsg})})}adDestroy(e=!1){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.__novelDestroy__({preserved:e})}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.__novelDestroy__(),this._resolve=null,this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.offClose(this._bindShiftCloseLister),this.__novelDestroy__(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.offError(this._bindShiftErrorLister),this.__novelDestroy__(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return RewardAdNovel.instance||(RewardAdNovel.instance=new RewardAdNovel(e)),RewardAdNovel.instance}static getInstance(){if(!RewardAdNovel.instance)throw Error("RewardAdNovel instance is not init");return RewardAdNovel.instance}static new(e){return new RewardAdNovel(e)}}class RewardAdNovelConfig{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new RewardAdNovelConfig(e)}}const src_RewardAdNovel=RewardAdNovel;class InterstitialAdFather{static args=null;_logger=null;_initSign="";_preserveOnEnd=!1;_interstitialAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302,140502];constructor(e){this._logger=new Logger({prefix:"InterstitialAdFather",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._interstitialAd)return this._logger.warn("interstitialAd has been initialized"),t?.(this._interstitialAd),this;let r=Object.assign({},InterstitialAdFather.args,this._adConfig,e);if(!r.adUnitId)throw this._logger.error("interstitialAd args The adUnitId is required",r),new SerializableError("[InterstitialAdFather] interstitialAd args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100003});let i=tt.createInterstitialAd(r);return this._interstitialAd=i,this.__ad__=i,t?.(this._interstitialAd),this}initialized(){return!!this._interstitialAd}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return InterstitialAdFather.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){this._interstitialAd&&!this._preserveOnEnd&&(this._interstitialAd.destroy(),this._interstitialAd=null)}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._interstitialAd&&this._interstitialAd.onClose(e)}offClose(e){this._interstitialAd&&this._interstitialAd.offClose(e)}show(){return this._interstitialAd?this._interstitialAd.show():Promise.reject({errMsg:"[InterstitialAdFather] can not show,interstitialAd is null",errorCode:120001})}load(){return this._interstitialAd?this._interstitialAd.load():Promise.reject({errMsg:"[InterstitialAdFather] can not load,interstitialAd is null",errorCode:120002})}onError(e){this._interstitialAd&&this._interstitialAd.onError(e)}offError(e){this._interstitialAd&&this._interstitialAd.offError(e)}onLoad(e){this._interstitialAd&&this._interstitialAd.onLoad(e)}offLoad(e){this._interstitialAd&&this._interstitialAd.offLoad(e)}placeholder(){return null}static buildArgs(e){e?.adUnitId||new Logger({prefix:"InterstitialAdFather",enable:!0}).error("interstitialAdParams.adUnitId is required"),InterstitialAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof InterstitialAdFather?src_AdExecuteManager.getInstance().addTask(e,t):(new Logger({prefix:"InterstitialAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const src_InterstitialAdFather=InterstitialAdFather;function functional_matchErrorWithKeywords(e,t){return!!t&&e.some(e=>RegExp(e,"i").test(t))}function functional_getAdSceneTextObj(e){return Object.entries(e).reduce((e,[t,r])=>(e[r]=Number(t),e),{})}const const_DEFAULT_SCENT_TYPE_OBJ={9999:"inner_default_other"},const_DEFAULT_SCENT_TEXT_OBJ=functional_getAdSceneTextObj(const_DEFAULT_SCENT_TYPE_OBJ),const_AD_TYPE_ENUM={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2},const_AD_TYPE_ENUM_REVERSE=Object.entries(const_AD_TYPE_ENUM).reduce((e,[t,r])=>(e[r]=t,e),{});class InterstitialAdNovel extends src_InterstitialAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=const_DEFAULT_SCENT_TEXT_OBJ.inner_default_other;_adTypeR=const_AD_TYPE_ENUM.AD_TYPE_INTERSTITIAL;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.adCloseLister.bind(this);bindAdErrorLister=this.adErrorLister.bind(this);bindAdLoadLister=this.adLoadLister.bind(this);bindApiAdErrorLister=this.apiAdErrorLister.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);constructor(e){super(e),this._logger=new Logger({prefix:"InterstitialAdNovel",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._needEndOnTimeout=e?.needEndOnTimeout??!0,this._onHalfway=e?.collection?.onHalfway??null,this._onShow=e?.collection?.onShow??null,this._onFinish=e?.collection?.onFinish??null,this._onAlways=e?.collection?.onAlways??null,this._onError=e?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=InterstitialAdNovel_RewardAdNovelConfig.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let r="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,msg:r,errorCode:100001,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:r,errorCode:100001}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout&&(this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case, scene:",e?.scene),this._adShowFailureAnalytics({scene:e?.scene,msg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001}},nextValue:null})},this._adTimeoutTime))}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearTimeout(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}ad(e,t=null){return this._alwaysCallback=e?.collection?.always,this._halfwayCallback=e?.collection?.halfway,this._finishedCallback=e?.collection?.finished,this._onInnerExecuteBefore(),new Promise(r=>{this._adInner({options:{scene:e?.options?.scene},collection:{resolve:r,before:e.collection?.before,success:e.collection?.success,prelude:e.collection?.prelude}},t)})}_adInner(e,t=null){let r=e?.collection?.resolve,i=e?.options?.scene??this._scene??const_DEFAULT_SCENT_TEXT_OBJ.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,a=e=>{this._clearAdTimeout(),this.adDestroy(),r?.(Object.assign({scene:i,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:i},e?.nextValue))},l=()=>{this._scene=i,s?.({scene:i}),this._before=s,this._onShow?.({scene:i}),this._adShowBeforeAnalytics({scene:i}),this._resolve=r,this._next=t,this._setAdTimeout({scene:i,end:a}),this._adPreludeInterval({scene:i,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:i}),this._success=n,this._adShowSuccessAnalytics({scene:i,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:i,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),functional_matchErrorWithKeywords(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?a({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?a({scene:i,resolvedValue:null,nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:i,result:1}),l()}).catch(e=>{this._adLoadFailureAnalytics({scene:i,msg:e?.errMsg,result:0}),a({scene:i,resolvedValue:{apiError:e},nextValue:null})}))})};l()}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(e){this._alwaysCallback?.(e)}_outerHalfwayCallback(e){this._halfwayCallback?.(e)}_outerFinishedCallback(e){this._finishedCallback?.(e)}adCloseLister(){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:1});let e={scene:this._scene},t=e=>{this.adDestroy(),this._resolve?.(Object.assign({},{scene:this._scene,adTypeR:this._adTypeR},e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null};this._outerFinishedCallback(e),this._onFinish?.(e),this._outerHalfwayCallback(e),this._onHalfway?.(e),this._outerCloseCallback(e),this._onAlways?.(e),t({end_type:"finished"})}adErrorLister(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this._onError?.(e),0>=this.novelConfig.remain()&&(this.adDestroy(),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null)}apiAdErrorLister(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}adLoadLister(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e}))}adDestroy(){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy()}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy(),this._resolve=null,this._next=null,this._success=null,this._before=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offClose(this._bindShiftCloseLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offError(this._bindShiftErrorLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return InterstitialAdNovel.instance||(InterstitialAdNovel.instance=new InterstitialAdNovel(e)),InterstitialAdNovel.instance}static getInstance(){if(!InterstitialAdNovel.instance)throw Error("InterstitialAdNovel instance is not init");return InterstitialAdNovel.instance}static new(e){return new InterstitialAdNovel(e)}}class InterstitialAdNovel_RewardAdNovelConfig{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new InterstitialAdNovel_RewardAdNovelConfig(e)}}const src_InterstitialAdNovel=InterstitialAdNovel;class Storage{constructor(e={}){this.config={prefix:"storage_",expire:null,...e},this.logger=new Logger({prefix:"Storage"})}getTodayEndTimestamp(){let e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),23,59,59,999).getTime()}_setItem(e,t,r){let i=void 0!==r?r:this.config.expire;"today"===i&&(i=this.getTodayEndTimestamp()-Date.now());let s={value:t,expire:i,timestamp:Date.now()};try{tt.setStorageSync(e,JSON.stringify(s))}catch(e){console.error("Storage setItem error:",e)}}_getItem(e){try{let t=tt.getStorageSync(e);if(!t)return null;let r=JSON.parse(t);if(r.expire&&Date.now()-r.timestamp>r.expire)return this.removeItem(e),null;return r.value}catch(e){return console.error("Storage getItem error:",e),null}}setItem(e,t,r){let i=this.config.prefix+e;return this._setItem(i,t,r)}getItem(e){let t=this.config.prefix+e;return this._getItem(t)}getUserItem(e){let t=this.config.userId??"null";if("null"===t)return this.logger.error("userId is required"),null;let r=`${this.config.prefix}_${t}_${e}`;return this._getItem(r)}setUserItem(e,t,r){let i=this.config.userId??"null";if("null"===i)return void this.logger.error("userId is required");let s=`${this.config.prefix}_${i}_${e}`;return this._setItem(s,t,r)}removeUserItem(e){let t=this.config.userId??"null";if("null"===t)return void this.logger.error("userId is required");let r=`${this.config.prefix}_${t}_${e}`;try{tt.removeStorageSync(r)}catch(e){console.error("Storage removeUserItem error:",e)}}removeItem(e){try{tt.removeStorageSync(e)}catch(e){console.error("Storage removeItem error:",e)}}clear(){try{tt.clearStorageSync()}catch(e){console.error("Storage clear error:",e)}}keys(){try{let e=[];return(tt.getStorageInfoSync().keys??[]).forEach(t=>{if(t.startsWith(this.config.prefix)){let r=JSON.parse(tt.getStorageSync(t));(!r.expire||Date.now()-r.timestamp<=r.expire)&&e.push(t.replace(this.config.prefix,""))}}),e}catch(e){return console.error("Storage keys error:",e),[]}}static new(e){return new Storage(e)}}const src_Storage=Storage;class CountRecorder{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=src_Storage.new({userId:e.userId}),!e.local_sign)throw Error("local_sign is required");this._local_sign=e.local_sign,this._total=e.total??0,this._expire=e.expire??"today",this._init()}_init(){this._initLocalTimes()}_adTimes(){return this._total}_safeLocalValue(e){return"object"!=typeof e||null===e?{}:e}_initLocalTimes(){let e=this._adTimes(),t=this.storage.getUserItem(this._local_sign),r=this._safeLocalValue(t);r&&r?.total==e||this.storage.setUserItem(this._local_sign,{total:e,today:r?.today??0},this._expire)}updateToday(){let e=this._adTimes(),t=this.storage.getUserItem(this._local_sign),r=this._safeLocalValue(t),i=r?.today??0;this.storage.setUserItem(this._local_sign,{total:e,today:i+1},this._expire)}remain(){let e=this.storage.getUserItem(this._local_sign),t=this._safeLocalValue(e),r=t?.today??0;return Number(t?.total??0)-Number(r)}save(e){let t=e;"number"!=typeof t&&(t=0);let r=this._adTimes();this.storage.setUserItem(this._local_sign,{total:r,today:t},this._expire)}clear(){this.storage.removeUserItem(this._local_sign)}reset(){let e=this._adTimes();this.storage.setUserItem(this._local_sign,{total:e,today:0},this._expire)}static new(e){return new CountRecorder(e)}}class PubSub{constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.off(e,t)}}off(e,t){if(this.events[e]){if(!t){this.events[e]=[];return}this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,...t){this.events[e]&&this.events[e].forEach(r=>{try{r(...t)}catch(t){console.error(`Error in event listener for ${e}:`,t)}})}once(e,t){let r=(...i)=>{t(...i),this.off(e,r)};this.on(e,r)}listenerCount(e){return this.events[e]?this.events[e].length:0}removeAllListeners(){this.events={}}}class EventEmitter{constructor(e={}){this.events={},this.queues={},this.onceEvents={},this.maxListeners=e.maxListeners||5,this.maxQueueSize=e.maxQueueSize||1,this.maxOnceEvents=e.maxOnceEvents||5}on(e,t){(this.events[e]||(this.events[e]=[]),this.events[e].length>=this.maxListeners)?console.warn(`EventEmitter: Maximum listeners (${this.maxListeners}) reached for event "${e}". Listener not added.`):(this.events[e].push(t),this.queues[e]&&this.queues[e].length>0&&(this.queues[e].forEach(e=>{t(...e)}),this.queues[e]=[]))}once(e,t){let r=(...i)=>{t(...i),this.off(e,r)};(this.onceEvents[e]||(this.onceEvents[e]=new Set),this.onceEvents[e].size>=this.maxOnceEvents)?console.warn(`EventEmitter: Maximum once events (${this.maxOnceEvents}) reached for event "${e}". Once listener not added.`):(this.onceEvents[e].add(r),this.on(e,r))}emit(e,...t){this.events[e]&&this.events[e].length>0?[...this.events[e]].forEach(e=>{e(...t)}):(this.queues[e]||(this.queues[e]=[]),this.queues[e].length>=this.maxQueueSize&&(console.warn(`EventEmitter: Maximum queue size (${this.maxQueueSize}) reached for event "${e}". Oldest event removed.`),this.queues[e].shift()),this.queues[e].push(t))}off(e,t){if(!t){this.events[e]=[],this.onceEvents[e]=new Set;return}this.events[e]=this.events[e].filter(e=>e!==t),this.onceEvents[e]&&this.onceEvents[e].delete(t)}removeAllListeners(e){e?(delete this.events[e],delete this.queues[e],delete this.onceEvents[e]):(this.events={},this.queues={},this.onceEvents={})}static geInstance(e){return this._instance||(this._instance=new EventEmitter(e)),this._instance}}class AdAnalyticsJS{static instance=null;_logger=null;_initSign="";_needReport=!1;constructor(e){if(AdAnalyticsJS.instance)return AdAnalyticsJS.instance;this._logger=new Logger({prefix:"AdAnalyticsJS",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._needReport=e?.needReport??!1,this._commonConfig=e?.commonConfig??null,AdAnalyticsJS.instance=this}initialize(e){return this._needReport?e:void this._logger.warn("needReport is false, do not report")}track(e,t,r){if(!this._needReport)return;if(!e)throw Error("eventName is required");let i=Object.assign({},this.getTrackCommonInfo(),t),s=r?.sign??"track";this._logger.log(`---------${s}----------:`,e,i),tt.reportAnalytics(e,i)}getCommonInfo(e){let t=this._commonConfig??{};return"string"==typeof e||"number"==typeof e?t[e]:t}getTrackCommonInfo(){return this._commonConfig??{}}identify(e,t){if(!e&&0!==e)throw Error("identify user_id is required");return this._commonConfig=Object.assign({},this._commonConfig,{__user_id:e},t),this}alias(){return null}pages(){return null}page(e,t){this.track(e,t,{sign:"page"})}cpage(e){return this.page("cpage",e)}placeholder(){return null}static build(e){return AdAnalyticsJS.instance||(AdAnalyticsJS.instance=new AdAnalyticsJS(e)),AdAnalyticsJS.instance}static getInstance(){if(!AdAnalyticsJS.instance)throw Error("AdAnalyticsJS instance is not init");return AdAnalyticsJS.instance}static new(e){return new AdAnalyticsJS(e)}}const src_AdAnalyticsJS=AdAnalyticsJS,packages_0=src_AdExecuteManager;for(var __rspack_i in exports.AdAnalyticsJS=__webpack_exports__.AdAnalyticsJS,exports.AdExecuteManager=__webpack_exports__.AdExecuteManager,exports.CountRecorder=__webpack_exports__.CountRecorder,exports.EventEmitter=__webpack_exports__.EventEmitter,exports.InterstitialAdDrama=__webpack_exports__.InterstitialAdDrama,exports.InterstitialAdFather=__webpack_exports__.InterstitialAdFather,exports.InterstitialAdNovel=__webpack_exports__.InterstitialAdNovel,exports.Logger=__webpack_exports__.Logger,exports.PubSub=__webpack_exports__.PubSub,exports.RewardAdDrama=__webpack_exports__.RewardAdDrama,exports.RewardAdFather=__webpack_exports__.RewardAdFather,exports.RewardAdNovel=__webpack_exports__.RewardAdNovel,exports.SerializableError=__webpack_exports__.SerializableError,exports.Storage=__webpack_exports__.Storage,exports.default=__webpack_exports__.default,__webpack_exports__)-1===["AdAnalyticsJS","AdExecuteManager","CountRecorder","EventEmitter","InterstitialAdDrama","InterstitialAdFather","InterstitialAdNovel","Logger","PubSub","RewardAdDrama","RewardAdFather","RewardAdNovel","SerializableError","Storage","default"].indexOf(__rspack_i)&&(exports[__rspack_i]=__webpack_exports__[__rspack_i]);Object.defineProperty(exports,"__esModule",{value:!0});
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class e{constructor(e={}){let{prefix:t="Logger",level:i="log",enabled:r=!0}=e;this.prefix=t,this.enabled=r,this.levels={error:0,warn:1,info:2,log:3,debug:4},this.currentLevel=this.levels[i]||this.levels.log}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}setLevel(e){Object.prototype.hasOwnProperty.call(this.levels,e)&&(this.currentLevel=this.levels[e])}formatMessage(e,t){let i=new Date,r=`${i.getFullYear()}/${i.getMonth()+1}/${i.getDate()} ${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}`;return`[${r}] [${e.toUpperCase()}] [${this.prefix}] ${t}`}_log(e,t,...i){if(!this.enabled)return;let r=this.levels[e];if(void 0!==r&&this.currentLevel>=r){let r=this.formatMessage(e,t);switch(e){case"error":console.error(r,...i);break;case"warn":console.warn(r,...i);break;case"info":console.info(r,...i);break;case"log":default:console.log(r,...i);break;case"debug":console.debug(r,...i)}}}error(e,...t){this._log("error",e,...t)}warn(e,...t){this._log("warn",e,...t)}info(e,...t){this._log("info",e,...t)}log(e,...t){this._log("log",e,...t)}debug(e,...t){this._log("debug",e,...t)}}class t{static _instance=null;_taskStack=[];_currentBatchTasks=[];_isRunning=!1;_currentTask=null;_isForeground=!0;_appShowListener=null;_appHideListener=null;_enableVisibilityListener=!1;_maxRetryCount=1;_retryQueue=[];_errorRetryStrategy={timeout:!0,background:!0};constructor(t){this.logger=new e({prefix:"AdExecuteManager",enabled:!!t?.log}),t?.errorRetryStrategy&&(this._errorRetryStrategy=Object.assign({},this._errorRetryStrategy,t?.errorRetryStrategy)),this._enableVisibilityListener=t?.enableVisibilityListener,this._maxRetryCount=t?.maxRetryCount??1,this._enableVisibilityListener&&this._initVisibilityListener()}initialize(e){return this}static getInstance(e){return t._instance||(t._instance=new t(e)),t._instance}static build(e){return t._instance||(t._instance=new t(e)),t._instance}static new(e){return new t(e)}static getSafeInstance(){return t._instance?t._instance:(this.logger.error("AdExecuteManager实例不存在"),null)}_initVisibilityListener(){!("u"<typeof tt)&&tt.onAppShow&&tt.onAppHide?(this._appShowListener=()=>{this._isForeground=!0,this._handleAppShow()},this._appHideListener=()=>{this._isForeground=!1,this._handleAppHide()},tt.onAppShow(this._appShowListener),tt.onAppHide(this._appHideListener),this.logger.info("前后台监听器已初始化")):this.logger.warn("tt API不可用,无法监听前后台状态")}_handleAppHide(){if(this._isRunning&&this._currentBatchTasks.length>0){let e=this._currentBatchTasks.filter(e=>e.id!==this._currentTask?.id&&!e._isResolved&&!e._isRejected);e.length>0&&(this.logger.info(`将 ${e.length} 个未执行的任务放回任务栈,任务ID: ${e.map(e=>e.id).join(",")}`),this._taskStack=[...e,...this._taskStack],this._currentBatchTasks=this._currentBatchTasks.filter(t=>!e.some(e=>e.id===t.id)))}}_handleAppShow(){this._retryQueue.length>0&&(this.logger.info(`应用进入前台:优先执行重试队列,任务数: ${this._retryQueue.length}, 任务ID: ${this._retryQueue.map(e=>e.id).join(",")}`),this._taskStack=[...this._retryQueue,...this._taskStack],this._retryQueue=[]),this._taskStack.length>0&&!this._isRunning&&(this.logger.info(`应用进入前台:恢复待执行任务数: ${this._taskStack.length}, 任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._compose())}destroyVisibilityListener(){this._appShowListener&&"u">typeof tt&&tt.offAppShow&&(tt.offAppShow(this._appShowListener),this._appShowListener=null),this._appHideListener&&"u">typeof tt&&tt.offAppHide&&(tt.offAppHide(this._appHideListener),this._appHideListener=null),this.logger.info("前后台监听器已销毁")}enableVisibilityListener(){this._enableVisibilityListener||(this._enableVisibilityListener=!0,this._initVisibilityListener()),this.logger.info("前后台监听器已启用")}disableVisibilityListener(){this._enableVisibilityListener&&(this._enableVisibilityListener=!1,this.destroyVisibilityListener()),this.logger.info("前后台监听器已禁用")}isVisibilityListenerEnabled(){return this._enableVisibilityListener}addTask(e,t){return e&&"function"==typeof e.ad?new Promise((i,r)=>{let s={adInstance:e,options:t.options??{},callbackCollection:t.collection??{},resolve:i,reject:r,id:`ad_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_isResolved:!1,_isRejected:!1,_retryCount:0,_retryMsg:"ok"};this._taskStack.push(s),this._isRunning||this._compose()}):(this.logger.error("无效的广告实例 请正确实现.ad方法"),Promise.reject(Error("无效的广告实例")))}_compose(){if(0===this._taskStack.length){this._isRunning=!1,this._currentTask=null;return}if(!this._isForeground){this.logger.info(`应用处于后台,暂停任务执行,任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._isRunning=!1;return}this._isRunning=!0;let e=[...this._taskStack];this._taskStack=[],this._currentBatchTasks=e;let t=e.map(e=>async(t,i)=>{let{adInstance:r,options:s,callbackCollection:n,resolve:o,id:l,_retryCount:a,_retryMsg:h}=e,d={count:a,retry:a>0,message:h};if(e._isResolved||e._isRejected)return void await i(t);this._currentTask=e;try{let a=async e=>{await i(Object.assign({},t,e))},h=await r.initialize(s).ad({options:s,collection:n,recovered:d},a),_=Object.assign({id:l,recovered:d},h);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(_)}`),function({apiError:e,configuredAdTimeout:t,errorRetryStrategy:i}){return!!(i?.timeout&&e?.errMsg&&"string"==typeof e.errMsg&&e.errMsg.startsWith("ad_show_timeout: normal")&&e?.timeout==t)||!!(i?.background&&e?.errMsg&&"string"==typeof e.errMsg&&(e.errMsg.startsWith("app in background is not support show ad")||e.errMsg.startsWith("other controller is presented")))}({apiError:_?.apiError,configuredAdTimeout:r._adTimeoutTime,errorRetryStrategy:this._errorRetryStrategy})&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++,e._retryMsg=_?.apiError?.errMsg||"unknown";let t=`任务 ${l} 在后台失败,加入重试队列 (即将第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount}, 重试原因: ${e._retryMsg})`;this.logger.warn(t),_.recovered.retry=!0,_.recovered.count=e._retryCount,_.recovered.message=e._retryMsg,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;o(_),r?.record(_)}catch(n){let s=Object.assign({id:l,apiError:n,recovered:d});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(s)}`),e._isRejected=!0;try{r?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:l,apiError:e})))}o(s),r?.record(s),await i(t)}}),i={roundTasks:t.length};t.map(e=>(t,i)=>async r=>await e(Object.assign({},t,r),i)).reduce((e,t)=>(i,r)=>e(i,t(i,r)))(i,async e=>{this.logger.info("本轮活动队列已经清空",e),this._taskStack.length>0?Promise.resolve().then(()=>{this._compose()}):(this._isRunning=!1,this._currentTask=null,this._currentBatchTasks=[])})()}clearTasks(){if(this._currentTask){if(this._currentTask._isResolved||this._currentTask._isRejected){this._currentTask=null;return}try{this._currentTask.callbackCollection&&this._currentTask.callbackCollection.cancel&&this._currentTask.callbackCollection.cancel(),this._currentTask._isResolved=!0,this._currentTask.resolve()}catch(e){this.logger.error("clear current task error: ",e)}this._currentTask=null}this._currentBatchTasks.length>0&&(this._currentBatchTasks.forEach(e=>{if(e!==this._currentTask&&!e._isResolved&&!e._isRejected)try{e.callbackCollection&&e.callbackCollection.cancel&&e.callbackCollection.cancel(),e._isResolved=!0,e.resolve()}catch(e){this.logger.error("clear current batch task error: ",e)}}),this._currentBatchTasks=[]),this._taskStack.forEach(e=>{if(!e._isResolved&&!e._isRejected&&(e._isResolved=!0,e.resolve(),e.callbackCollection&&e.callbackCollection.cancel))try{e.callbackCollection.cancel()}catch(e){this.logger.error("clear task error: ",e)}}),this._retryQueue.forEach(e=>{if(!e._isResolved&&!e._isRejected&&(e._isResolved=!0,e.resolve(),e.callbackCollection&&e.callbackCollection.cancel))try{e.callbackCollection.cancel()}catch(e){this.logger.error("clear retry task error: ",e)}}),this._taskStack=[],this._retryQueue=[],this._isRunning=!1}getTaskCount(){return this._taskStack.filter(e=>!e._isResolved&&!e._isRejected).length+this._currentBatchTasks.filter(e=>e!==this._currentTask&&!e._isResolved&&!e._isRejected).length+(!this._currentTask||this._currentTask._isResolved||this._currentTask._isRejected?0:1)+this._retryQueue.filter(e=>!e._isResolved&&!e._isRejected).length}isRunning(){return this._isRunning}getCurrentTaskId(){return this._currentTask?.id||null}whenAllTasksComplete(){return new Promise(e=>{let t=null,i=()=>{let r=0===this._taskStack.length,s=!this._isRunning,n=null===this._currentTask,o=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),l=0===this._retryQueue.length;r&&s&&n&&o&&l?(t&&clearTimeout(t),e()):t=setTimeout(i,500)};i()})}}let i=t;class r extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.stack=Error(e).stack,this.errMsg=t.errMsg,this.errorCode=t.errorCode,Object.defineProperty(this,"message",{enumerable:!0}),Object.defineProperty(this,"name",{enumerable:!0}),Object.defineProperty(this,"stack",{enumerable:!0}),Object.defineProperty(this,"errMsg",{enumerable:!0}),Object.defineProperty(this,"errorCode",{enumerable:!0})}toJSON(){return{name:this.name,message:this.message,stack:this.stack,errMsg:this.errMsg,errorCode:this.errorCode}}}class s{static args=null;_logger=null;_adTimeoutTime=8e3;_initSign="";_preserveOnEnd=!1;_rewardAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302];__bindAdErrorForeverHandler=this.__adErrorForeverHandler.bind(this);constructor(t){this._logger=new e({prefix:"RewardAdFather",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._preserveOnEnd=t?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return this._logger.warn("rewardAd has been initialized"),t?.(this._rewardAd),this;let i=Object.assign({},s.args,this._adConfig,e);if(!i.adUnitId)throw this._logger.error("reward args The adUnitId is required",i),new r("[RewardAdFather] reward args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100002});let n=tt.createRewardedVideoAd(i);return this._logger.info("bindAdErrorForeverHandler at initialized:",e?.foreverErrorBind),e?.foreverErrorBind&&(n?.offError(this.__bindAdErrorForeverHandler),n?.onError(this.__bindAdErrorForeverHandler)),this._rewardAd=n,this.__ad__=n,t?.(this._rewardAd),this}initialized(){return!!this._rewardAd}__adErrorForeverHandler(e){this.adErrorForeverHandler(e)}adErrorForeverHandler(e){return null}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return s.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(e=!1){return!this._rewardAd||this._preserveOnEnd||e?Promise.reject({errMsg:`can not destroy,ad is: ${!!this._rewardAd}, preserved: ${e}, preservedOnEnd: ${this._preserveOnEnd}`,errorCode:110003}):this._rewardAd.destroy().then(e=>Promise.resolve(e))?.catch(e=>Promise.reject({errMsg:`rewardAd destroy failed: ${JSON.stringify(e)}`,errorCode:110004}))?.finally(()=>{this._rewardAd=null})}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._rewardAd&&this._rewardAd.onClose(e)}offClose(e){this._rewardAd&&this._rewardAd.offClose(e)}show(){return this._rewardAd?this._rewardAd.show():Promise.reject({errMsg:"[RewardAdFather] can not show,rewardAd is null",errorCode:110001})}load(){return this._rewardAd?this._rewardAd.load():Promise.reject({errMsg:"[RewardAdFather] can not load,rewardAd is null",errorCode:110002})}onError(e){this._rewardAd&&this._rewardAd.onError(e)}offError(e){this._rewardAd&&this._rewardAd.offError(e)}onLoad(e){this._rewardAd&&this._rewardAd.onLoad(e)}offLoad(e){this._rewardAd&&this._rewardAd.offLoad(e)}placeholder(){return null}static buildArgs(t){t?.adUnitId||new e({prefix:"RewardAdFather",enable:!0}).error("RewardParams.adUnitId is required"),s.args=t}static async executeWithManager(t,r){return t&&t instanceof s?i.getInstance().addTask(t,r):(new e({prefix:"RewardAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let n=s,o=Object.entries({9999:"inner_default_other"}).reduce((e,[t,i])=>(e[i]=Number(t),e),{}),l={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2};Object.entries(l).reduce((e,[t,i])=>(e[i]=t,e),{});class a extends n{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_adExecuteArgs=null;_adNext=null;_scene=o.inner_default_other;_eId=null;_adTypeR=l.AD_TYPE_REWARD;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_lookUpRemainOnError=!1;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.__adCloseLister__.bind(this);bindAdErrorLister=this.__adErrorLister__.bind(this);bindAdLoadLister=this.__adLoadLister__.bind(this);bindApiAdErrorLister=this.__apiAdErrorLister__.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);bindAdTimeoutCloseLister=this.__adTimeoutCloseLister__.bind(this);bindAdTimeoutErrorLister=this.__adTimeoutErrorLister__.bind(this);constructor(t){super(t),this._logger=new e({prefix:"RewardAdNovel",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._needEndOnTimeout=t?.needEndOnTimeout??!0,this._lookUpRemainOnError=t?.lookUpRemainOnError??!1,this._onHalfway=t?.collection?.onHalfway??null,this._onShow=t?.collection?.onShow??null,this._onFinish=t?.collection?.onFinish??null,this._onAlways=t?.collection?.onAlways??null,this._onError=t?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=h.new({retry:e?.retry})}_onInnerExecuteBefore(e){return null}_onAdExecuteBefore(e){return null}_onInnerAdShowSuccess(e){return null}_onInnerAdDestroySuccess(e){return null}_onInnerAdDestroyFailed(e){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let i="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,eId:this._eId,msg:i,errorCode:1e5,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:i,errorCode:1e5}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout){let t=e?.timeout??this._adTimeoutTime;this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,eId:this._eId,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),this._adTimeoutBeforeEnd({scene:e?.scene,timeout:t}),this.onClose(this.bindAdTimeoutCloseLister),this.onError(this.bindAdTimeoutErrorLister),e?.end({preserved:e?.preserved,resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})},t)}}_adTimeoutBeforeEnd(e){return e}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearInterval(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}ad(e,t=null){return this._alwaysCallback=e?.collection?.always,this._halfwayCallback=e?.collection?.halfway,this._finishedCallback=e?.collection?.finished,this._recovered=e?.recovered,this._preservedOnTimeout=e?.options?.preservedOnTimeout,this._adExecuteArgs=e,this._adNext=t,this._onAdExecuteBefore({eId:this._eId}),new Promise(i=>{this._resolve=i,this._adInner({options:{scene:e?.options?.scene,timeout:e?.options?.timeout},collection:{resolve:i,before:e.collection?.before,success:e.collection?.success,prelude:e.collection?.prelude},recovered:e.recovered},t)})}_adInner(e,t=null){this._eId=`ead_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,this._onInnerExecuteBefore({eId:this._eId});let i=e?.collection?.resolve,r=e?.options?.scene??this._scene??o.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,l=e?.collection?.prelude,a=e?.recovered??this._recovered,h=e=>{this._clearAdTimeout(),this.adDestroy(e?.preserved),i?.(Object.assign({scene:r,adTypeR:this._adTypeR,eId:this._eId},e?.resolvedValue)),this._resolve=null,t?.(Object.assign({scene:r},e?.nextValue)),this._next=null,this._adExecuteArgs=null,this._adNext=null},d=()=>{this._scene=r,s?.({scene:r}),this._before=s,this._onShow?.({scene:r}),this._adShowBeforeAnalytics({scene:r,eId:this._eId}),this._resolve=i,this._next=t,this._setAdTimeout({scene:r,end:h,timeout:e?.options?.timeout,preserved:this._preservedOnTimeout}),this._adPreludeInterval({scene:r,prelude:l}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:r}),this._success=n,this._adShowSuccessAnalytics({scene:r,eId:this._eId,result:1,recovered:a}),this._onInnerAdShowSuccess({scene:r,eId:this._eId,result:1,recovered:a})}).catch(e=>{var t,i;(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:r,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),t=this._ttErrorMsgs,(i=e?.errMsg)&&t.some(e=>RegExp(e,"i").test(i))||this._ttErrorCodes.includes(e?.errorCode))?h({scene:r,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?h({scene:r,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
|
|
2
|
-
tt: {errMsg: ${e?.errMsg}, errorCode: ${e?.errorCode}}`,errorCode:1e5}},nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:r,result:1,frequency:this.novelConfig.frequency}),d()}).catch(e=>{this._adLoadFailureAnalytics({scene:r,msg:e?.errMsg,result:0}),h({scene:r,resolvedValue:{apiError:e},nextValue:null})}))})};d()}adCircleInner(e){let t={scene:e?.options?.scene??this._adExecuteArgs?.options?.scene,timeout:e?.options?.timeout??this._adExecuteArgs?.options?.timeout},i={resolve:this._resolve,before:e?.collection?.before??this._adExecuteArgs?.collection?.before,success:e?.collection?.success??this._adExecuteArgs?.collection?.success,prelude:e?.collection?.prelude??this._adExecuteArgs?.collection?.prelude};this._adInner({options:t,collection:i,recovered:this._adExecuteArgs?.recovered},this._adNext)}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(...e){return this._alwaysCallback?.(...e)}onExeAlways(...e){return this._alwaysCallback?.(...e)}_outerHalfwayCallback(...e){return this._halfwayCallback?.(...e)}onExeHalfway(...e){return this._halfwayCallback?.(...e)}_outerFinishedCallback(...e){return this._finishedCallback?.(...e)}onExeFinished(...e){return this._finishedCallback?.(...e)}onFinish(...e){return this._onFinish?.(...e)}onHalfway(...e){return this._onHalfway?.(...e)}onAlways(...e){return this._onAlways?.(...e)}__adTimeoutCloseLister__(e){let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId});this._logger.warn("ad close lister that after task end because timeout:",t),this._clearAdTimeout(),this.offClose(this.bindAdTimeoutCloseLister),this.adTimeoutCloseLister(t)}adTimeoutCloseLister(e){return e}__adTimeoutErrorLister__(e){let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId});this._logger.error("ad error lister that after task end because timeout:",t),this._clearAdTimeout(),this.offError(this.bindAdTimeoutErrorLister),this.adTimeoutErrorLister(t)}adTimeoutErrorLister(e){return e}__adCloseLister__(e){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:+!!e.isEnded,ad_count:e.count});let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId,end_type:e.isEnded?"finished":"halfway"}),i=e=>{this.adDestroy(),this._resolve?.(Object.assign({},t,e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null},r=e=>{let i=Object.assign({},t,e);i?.isEnded?(this._outerFinishedCallback(i),this.onExeFinished(i),this._onFinish?.(i),this.onFinish(i)):(this._outerHalfwayCallback(i),this.onExeHalfway(i),this._onHalfway?.(i),this.onHalfway(i)),this._outerCloseCallback(i),this.onExeAlways(i),this._onAlways?.(i),this.onAlways(i)};this.adCloseLister(t,{conn:r,end:i})}adCloseLister(e,t){t?.conn?.(e),t?.end?.(e)}__adErrorLister__(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adErrorLister(e);let t=()=>{this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR,eId:this._eId}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null};(!this._lookUpRemainOnError||0>=this.novelConfig.remain())&&t()}adErrorLister(e){return e}__apiAdErrorLister__(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.apiAdErrorLister(e),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}apiAdErrorLister(e){return e}__adLoadLister__(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e})),this.adLoadLister(e)}adLoadLister(e){return e}__novelDestroy__(e){this.destroy(e?.preserved).then(e=>{this._onInnerAdDestroySuccess?.({scene:this._scene,eId:this._eId,errMsg:e})}).catch(e=>{this._logger.warn("ad destroy failed:",JSON.stringify(e)),this._onInnerAdDestroyFailed?.({scene:this._scene,eId:this._eId,errorCode:e?.errorCode,errMsg:e?.errMsg})})}adDestroy(e=!1){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.__novelDestroy__({preserved:e})}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.__novelDestroy__(),this._resolve=null,this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.offClose(this._bindShiftCloseLister),this.__novelDestroy__(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.offError(this._bindShiftErrorLister),this.__novelDestroy__(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return a.instance||(a.instance=new a(e)),a.instance}static getInstance(){if(!a.instance)throw Error("RewardAdNovel instance is not init");return a.instance}static new(e){return new a(e)}}class h{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new h(e)}}let d=a;class _{static args=null;_logger=null;_initSign="";_preserveOnEnd=!1;_interstitialAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302,140502];constructor(t){this._logger=new e({prefix:"InterstitialAdFather",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._preserveOnEnd=t?.preserveOnEnd??!1}initialize(e,t){if(this._interstitialAd)return this._logger.warn("interstitialAd has been initialized"),t?.(this._interstitialAd),this;let i=Object.assign({},_.args,this._adConfig,e);if(!i.adUnitId)throw this._logger.error("interstitialAd args The adUnitId is required",i),new r("[InterstitialAdFather] interstitialAd args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100003});let s=tt.createInterstitialAd(i);return this._interstitialAd=s,this.__ad__=s,t?.(this._interstitialAd),this}initialized(){return!!this._interstitialAd}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return _.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){this._interstitialAd&&!this._preserveOnEnd&&(this._interstitialAd.destroy(),this._interstitialAd=null)}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._interstitialAd&&this._interstitialAd.onClose(e)}offClose(e){this._interstitialAd&&this._interstitialAd.offClose(e)}show(){return this._interstitialAd?this._interstitialAd.show():Promise.reject({errMsg:"[InterstitialAdFather] can not show,interstitialAd is null",errorCode:120001})}load(){return this._interstitialAd?this._interstitialAd.load():Promise.reject({errMsg:"[InterstitialAdFather] can not load,interstitialAd is null",errorCode:120002})}onError(e){this._interstitialAd&&this._interstitialAd.onError(e)}offError(e){this._interstitialAd&&this._interstitialAd.offError(e)}onLoad(e){this._interstitialAd&&this._interstitialAd.onLoad(e)}offLoad(e){this._interstitialAd&&this._interstitialAd.offLoad(e)}placeholder(){return null}static buildArgs(t){t?.adUnitId||new e({prefix:"InterstitialAdFather",enable:!0}).error("interstitialAdParams.adUnitId is required"),_.args=t}static async executeWithManager(t,r){return t&&t instanceof _?i.getInstance().addTask(t,r):(new e({prefix:"InterstitialAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let c=_,u=Object.entries({9999:"inner_default_other"}).reduce((e,[t,i])=>(e[i]=Number(t),e),{}),f={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2};Object.entries(f).reduce((e,[t,i])=>(e[i]=t,e),{});class g extends c{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=u.inner_default_other;_adTypeR=f.AD_TYPE_INTERSTITIAL;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.adCloseLister.bind(this);bindAdErrorLister=this.adErrorLister.bind(this);bindAdLoadLister=this.adLoadLister.bind(this);bindApiAdErrorLister=this.apiAdErrorLister.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);constructor(t){super(t),this._logger=new e({prefix:"InterstitialAdNovel",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._needEndOnTimeout=t?.needEndOnTimeout??!0,this._onHalfway=t?.collection?.onHalfway??null,this._onShow=t?.collection?.onShow??null,this._onFinish=t?.collection?.onFinish??null,this._onAlways=t?.collection?.onAlways??null,this._onError=t?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=m.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let i="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,msg:i,errorCode:100001,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:i,errorCode:100001}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout&&(this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case, scene:",e?.scene),this._adShowFailureAnalytics({scene:e?.scene,msg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001}},nextValue:null})},this._adTimeoutTime))}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearTimeout(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}ad(e,t=null){return this._alwaysCallback=e?.collection?.always,this._halfwayCallback=e?.collection?.halfway,this._finishedCallback=e?.collection?.finished,this._onInnerExecuteBefore(),new Promise(i=>{this._adInner({options:{scene:e?.options?.scene},collection:{resolve:i,before:e.collection?.before,success:e.collection?.success,prelude:e.collection?.prelude}},t)})}_adInner(e,t=null){let i=e?.collection?.resolve,r=e?.options?.scene??this._scene??u.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,l=e=>{this._clearAdTimeout(),this.adDestroy(),i?.(Object.assign({scene:r,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:r},e?.nextValue))},a=()=>{this._scene=r,s?.({scene:r}),this._before=s,this._onShow?.({scene:r}),this._adShowBeforeAnalytics({scene:r}),this._resolve=i,this._next=t,this._setAdTimeout({scene:r,end:l}),this._adPreludeInterval({scene:r,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:r}),this._success=n,this._adShowSuccessAnalytics({scene:r,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{var t,i;(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:r,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),t=this._ttErrorMsgs,(i=e?.errMsg)&&t.some(e=>RegExp(e,"i").test(i))||this._ttErrorCodes.includes(e?.errorCode))?l({scene:r,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:r,resolvedValue:null,nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:r,result:1}),a()}).catch(e=>{this._adLoadFailureAnalytics({scene:r,msg:e?.errMsg,result:0}),l({scene:r,resolvedValue:{apiError:e},nextValue:null})}))})};a()}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(e){this._alwaysCallback?.(e)}_outerHalfwayCallback(e){this._halfwayCallback?.(e)}_outerFinishedCallback(e){this._finishedCallback?.(e)}adCloseLister(){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:1});let e={scene:this._scene},t=e=>{this.adDestroy(),this._resolve?.(Object.assign({},{scene:this._scene,adTypeR:this._adTypeR},e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null};this._outerFinishedCallback(e),this._onFinish?.(e),this._outerHalfwayCallback(e),this._onHalfway?.(e),this._outerCloseCallback(e),this._onAlways?.(e),t({end_type:"finished"})}adErrorLister(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this._onError?.(e),0>=this.novelConfig.remain()&&(this.adDestroy(),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null)}apiAdErrorLister(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}adLoadLister(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e}))}adDestroy(){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy()}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy(),this._resolve=null,this._next=null,this._success=null,this._before=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offClose(this._bindShiftCloseLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offError(this._bindShiftErrorLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return g.instance||(g.instance=new g(e)),g.instance}static getInstance(){if(!g.instance)throw Error("InterstitialAdNovel instance is not init");return g.instance}static new(e){return new g(e)}}class m{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new m(e)}}let y=g;class p{constructor(t={}){this.config={prefix:"storage_",expire:null,...t},this.logger=new e({prefix:"Storage"})}getTodayEndTimestamp(){let e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),23,59,59,999).getTime()}_setItem(e,t,i){let r=void 0!==i?i:this.config.expire;"today"===r&&(r=this.getTodayEndTimestamp()-Date.now());let s={value:t,expire:r,timestamp:Date.now()};try{tt.setStorageSync(e,JSON.stringify(s))}catch(e){console.error("Storage setItem error:",e)}}_getItem(e){try{let t=tt.getStorageSync(e);if(!t)return null;let i=JSON.parse(t);if(i.expire&&Date.now()-i.timestamp>i.expire)return this.removeItem(e),null;return i.value}catch(e){return console.error("Storage getItem error:",e),null}}setItem(e,t,i){let r=this.config.prefix+e;return this._setItem(r,t,i)}getItem(e){let t=this.config.prefix+e;return this._getItem(t)}getUserItem(e){let t=this.config.userId??"null";if("null"===t)return this.logger.error("userId is required"),null;let i=`${this.config.prefix}_${t}_${e}`;return this._getItem(i)}setUserItem(e,t,i){let r=this.config.userId??"null";if("null"===r)return void this.logger.error("userId is required");let s=`${this.config.prefix}_${r}_${e}`;return this._setItem(s,t,i)}removeUserItem(e){let t=this.config.userId??"null";if("null"===t)return void this.logger.error("userId is required");let i=`${this.config.prefix}_${t}_${e}`;try{tt.removeStorageSync(i)}catch(e){console.error("Storage removeUserItem error:",e)}}removeItem(e){try{tt.removeStorageSync(e)}catch(e){console.error("Storage removeItem error:",e)}}clear(){try{tt.clearStorageSync()}catch(e){console.error("Storage clear error:",e)}}keys(){try{let e=[];return(tt.getStorageInfoSync().keys??[]).forEach(t=>{if(t.startsWith(this.config.prefix)){let i=JSON.parse(tt.getStorageSync(t));(!i.expire||Date.now()-i.timestamp<=i.expire)&&e.push(t.replace(this.config.prefix,""))}}),e}catch(e){return console.error("Storage keys error:",e),[]}}static new(e){return new p(e)}}let A=p;class w{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=A.new({userId:e.userId}),!e.local_sign)throw Error("local_sign is required");this._local_sign=e.local_sign,this._total=e.total??0,this._expire=e.expire??"today",this._init()}_init(){this._initLocalTimes()}_adTimes(){return this._total}_safeLocalValue(e){return"object"!=typeof e||null===e?{}:e}_initLocalTimes(){let e=this._adTimes(),t=this.storage.getUserItem(this._local_sign),i=this._safeLocalValue(t);i&&i?.total==e||this.storage.setUserItem(this._local_sign,{total:e,today:i?.today??0},this._expire)}updateToday(){let e=this._adTimes(),t=this.storage.getUserItem(this._local_sign),i=this._safeLocalValue(t),r=i?.today??0;this.storage.setUserItem(this._local_sign,{total:e,today:r+1},this._expire)}remain(){let e=this.storage.getUserItem(this._local_sign),t=this._safeLocalValue(e),i=t?.today??0;return Number(t?.total??0)-Number(i)}save(e){let t=e;"number"!=typeof t&&(t=0);let i=this._adTimes();this.storage.setUserItem(this._local_sign,{total:i,today:t},this._expire)}clear(){this.storage.removeUserItem(this._local_sign)}reset(){let e=this._adTimes();this.storage.setUserItem(this._local_sign,{total:e,today:0},this._expire)}static new(e){return new w(e)}}class b{constructor(e={}){this.events={},this.queues={},this.onceEvents={},this.maxListeners=e.maxListeners||5,this.maxQueueSize=e.maxQueueSize||1,this.maxOnceEvents=e.maxOnceEvents||5}on(e,t){(this.events[e]||(this.events[e]=[]),this.events[e].length>=this.maxListeners)?console.warn(`EventEmitter: Maximum listeners (${this.maxListeners}) reached for event "${e}". Listener not added.`):(this.events[e].push(t),this.queues[e]&&this.queues[e].length>0&&(this.queues[e].forEach(e=>{t(...e)}),this.queues[e]=[]))}once(e,t){let i=(...r)=>{t(...r),this.off(e,i)};(this.onceEvents[e]||(this.onceEvents[e]=new Set),this.onceEvents[e].size>=this.maxOnceEvents)?console.warn(`EventEmitter: Maximum once events (${this.maxOnceEvents}) reached for event "${e}". Once listener not added.`):(this.onceEvents[e].add(i),this.on(e,i))}emit(e,...t){this.events[e]&&this.events[e].length>0?[...this.events[e]].forEach(e=>{e(...t)}):(this.queues[e]||(this.queues[e]=[]),this.queues[e].length>=this.maxQueueSize&&(console.warn(`EventEmitter: Maximum queue size (${this.maxQueueSize}) reached for event "${e}". Oldest event removed.`),this.queues[e].shift()),this.queues[e].push(t))}off(e,t){if(!t){this.events[e]=[],this.onceEvents[e]=new Set;return}this.events[e]=this.events[e].filter(e=>e!==t),this.onceEvents[e]&&this.onceEvents[e].delete(t)}removeAllListeners(e){e?(delete this.events[e],delete this.queues[e],delete this.onceEvents[e]):(this.events={},this.queues={},this.onceEvents={})}static geInstance(e){return this._instance||(this._instance=new b(e)),this._instance}}class E{constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.off(e,t)}}off(e,t){if(this.events[e]){if(!t){this.events[e]=[];return}this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,...t){this.events[e]&&this.events[e].forEach(i=>{try{i(...t)}catch(t){console.error(`Error in event listener for ${e}:`,t)}})}once(e,t){let i=(...r)=>{t(...r),this.off(e,i)};this.on(e,i)}listenerCount(e){return this.events[e]?this.events[e].length:0}removeAllListeners(){this.events={}}}class T{static instance=null;_logger=null;_initSign="";_needReport=!1;constructor(t){if(T.instance)return T.instance;this._logger=new e({prefix:"AdAnalyticsJS",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._needReport=t?.needReport??!1,this._commonConfig=t?.commonConfig??null,T.instance=this}initialize(e){return this._needReport?e:void this._logger.warn("needReport is false, do not report")}track(e,t,i){if(!this._needReport)return;if(!e)throw Error("eventName is required");let r=Object.assign({},this.getTrackCommonInfo(),t),s=i?.sign??"track";this._logger.log(`---------${s}----------:`,e,r),tt.reportAnalytics(e,r)}getCommonInfo(){return this._commonConfig??{}}getTrackCommonInfo(){return this._commonConfig??{}}identify(e,t){if(!e&&0!==e)throw Error("identify user_id is required");return this._commonConfig=Object.assign({},this._commonConfig,{__user_id:e},t),this}alias(){return null}pages(){return null}page(e,t){this.track(e,t,{sign:"page"})}cpage(e){return this.page("cpage",e)}placeholder(){return null}static build(e){return T.instance||(T.instance=new T(e)),T.instance}static getInstance(){if(!T.instance)throw Error("AdAnalyticsJS instance is not init");return T.instance}static new(e){return new T(e)}}let C=T,v=i;export{C as AdAnalyticsJS,i as AdExecuteManager,w as CountRecorder,b as EventEmitter,y as InterstitialAdDrama,c as InterstitialAdFather,y as InterstitialAdNovel,e as Logger,E as PubSub,d as RewardAdDrama,n as RewardAdFather,d as RewardAdNovel,r as SerializableError,A as Storage,v as default};
|
|
1
|
+
class e{constructor(e={}){let{prefix:t="Logger",level:i="log",enabled:r=!0}=e;this.prefix=t,this.enabled=r,this.levels={error:0,warn:1,info:2,log:3,debug:4},this.currentLevel=this.levels[i]||this.levels.log}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}setLevel(e){Object.prototype.hasOwnProperty.call(this.levels,e)&&(this.currentLevel=this.levels[e])}formatMessage(e,t){let i=new Date,r=`${i.getFullYear()}/${i.getMonth()+1}/${i.getDate()} ${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}`;return`[${r}] [${e.toUpperCase()}] [${this.prefix}] ${t}`}_log(e,t,...i){if(!this.enabled)return;let r=this.levels[e];if(void 0!==r&&this.currentLevel>=r){let r=this.formatMessage(e,t);switch(e){case"error":console.error(r,...i);break;case"warn":console.warn(r,...i);break;case"info":console.info(r,...i);break;case"log":default:console.log(r,...i);break;case"debug":console.debug(r,...i)}}}error(e,...t){this._log("error",e,...t)}warn(e,...t){this._log("warn",e,...t)}info(e,...t){this._log("info",e,...t)}log(e,...t){this._log("log",e,...t)}debug(e,...t){this._log("debug",e,...t)}}class t{static _instance=null;_taskStack=[];_currentBatchTasks=[];_isRunning=!1;_currentTask=null;_isForeground=!0;_appShowListener=null;_appHideListener=null;_enableVisibilityListener=!1;_maxRetryCount=1;_retryQueue=[];_errorRetryStrategy={timeout:!0,background:!0};constructor(t){this.logger=new e({prefix:"AdExecuteManager",enabled:!!t?.log}),t?.errorRetryStrategy&&(this._errorRetryStrategy=Object.assign({},this._errorRetryStrategy,t?.errorRetryStrategy)),this._enableVisibilityListener=t?.enableVisibilityListener,this._maxRetryCount=t?.maxRetryCount??1,this._enableVisibilityListener&&this._initVisibilityListener()}initialize(e){return this}static getInstance(e){return t._instance||(t._instance=new t(e)),t._instance}static build(e){return t._instance||(t._instance=new t(e)),t._instance}static new(e){return new t(e)}static getSafeInstance(){return t._instance?t._instance:(this.logger.error("AdExecuteManager实例不存在"),null)}_initVisibilityListener(){!("u"<typeof tt)&&tt.onAppShow&&tt.onAppHide?(this._appShowListener=()=>{this._isForeground=!0,this._handleAppShow()},this._appHideListener=()=>{this._isForeground=!1,this._handleAppHide()},tt.onAppShow(this._appShowListener),tt.onAppHide(this._appHideListener),this.logger.info("前后台监听器已初始化")):this.logger.warn("tt API不可用,无法监听前后台状态")}_handleAppHide(){if(this._isRunning&&this._currentBatchTasks.length>0){let e=this._currentBatchTasks.filter(e=>e.id!==this._currentTask?.id&&!e._isResolved&&!e._isRejected);e.length>0&&(this.logger.info(`将 ${e.length} 个未执行的任务放回任务栈,任务ID: ${e.map(e=>e.id).join(",")}`),this._taskStack=[...e,...this._taskStack],this._currentBatchTasks=this._currentBatchTasks.filter(t=>!e.some(e=>e.id===t.id)))}}_handleAppShow(){this._retryQueue.length>0&&(this.logger.info(`应用进入前台:优先执行重试队列,任务数: ${this._retryQueue.length}, 任务ID: ${this._retryQueue.map(e=>e.id).join(",")}`),this._taskStack=[...this._retryQueue,...this._taskStack],this._retryQueue=[]),this._taskStack.length>0&&!this._isRunning&&(this.logger.info(`应用进入前台:恢复待执行任务数: ${this._taskStack.length}, 任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._compose())}destroyVisibilityListener(){this._appShowListener&&"u">typeof tt&&tt.offAppShow&&(tt.offAppShow(this._appShowListener),this._appShowListener=null),this._appHideListener&&"u">typeof tt&&tt.offAppHide&&(tt.offAppHide(this._appHideListener),this._appHideListener=null),this.logger.info("前后台监听器已销毁")}enableVisibilityListener(){this._enableVisibilityListener||(this._enableVisibilityListener=!0,this._initVisibilityListener()),this.logger.info("前后台监听器已启用")}disableVisibilityListener(){this._enableVisibilityListener&&(this._enableVisibilityListener=!1,this.destroyVisibilityListener()),this.logger.info("前后台监听器已禁用")}isVisibilityListenerEnabled(){return this._enableVisibilityListener}addTask(e,t){return e&&"function"==typeof e.ad?new Promise((i,r)=>{let s={adInstance:e,options:t.options??{},callbackCollection:t.collection??{},resolve:i,reject:r,id:`ad_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_isResolved:!1,_isRejected:!1,_retryCount:0,_retryMsg:"ok"};this._taskStack.push(s),this._isRunning||this._compose()}):(this.logger.error("无效的广告实例 请正确实现.ad方法"),Promise.reject(Error("无效的广告实例")))}_compose(){if(0===this._taskStack.length){this._isRunning=!1,this._currentTask=null;return}if(!this._isForeground){this.logger.info(`应用处于后台,暂停任务执行,任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._isRunning=!1;return}this._isRunning=!0;let e=[...this._taskStack];this._taskStack=[],this._currentBatchTasks=e;let t=e.map(e=>async(t,i)=>{let{adInstance:r,options:s,callbackCollection:n,resolve:o,id:l,_retryCount:a,_retryMsg:h}=e,d={count:a,retry:a>0,message:h};if(e._isResolved||e._isRejected)return void await i(t);this._currentTask=e;try{let a=async e=>{await i(Object.assign({},t,e))},h=await r.initialize(s).ad({options:s,collection:n,recovered:d},a),_=Object.assign({id:l,recovered:d},h);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(_)}`),function({apiError:e,configuredAdTimeout:t,errorRetryStrategy:i}){return!!(i?.timeout&&e?.errMsg&&"string"==typeof e.errMsg&&e.errMsg.startsWith("ad_show_timeout: normal")&&e?.timeout==t)||!!(i?.background&&e?.errMsg&&"string"==typeof e.errMsg&&(e.errMsg.startsWith("app in background is not support show ad")||e.errMsg.startsWith("other controller is presented")))}({apiError:_?.apiError,configuredAdTimeout:r._adTimeoutTime,errorRetryStrategy:this._errorRetryStrategy})&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++,e._retryMsg=_?.apiError?.errMsg||"unknown";let t=`任务 ${l} 在后台失败,加入重试队列 (即将第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount}, 重试原因: ${e._retryMsg})`;this.logger.warn(t),_.recovered.retry=!0,_.recovered.count=e._retryCount,_.recovered.message=e._retryMsg,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;o(_),r?.record(_)}catch(n){let s=Object.assign({id:l,apiError:n,recovered:d});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(s)}`),e._isRejected=!0;try{r?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:l,apiError:e})))}o(s),r?.record(s),await i(t)}}),i={roundTasks:t.length};t.map(e=>(t,i)=>async r=>await e(Object.assign({},t,r),i)).reduce((e,t)=>(i,r)=>e(i,t(i,r)))(i,async e=>{this.logger.info("本轮活动队列已经清空",e),this._taskStack.length>0?Promise.resolve().then(()=>{this._compose()}):(this._isRunning=!1,this._currentTask=null,this._currentBatchTasks=[])})()}clearTasks(){if(this._currentTask){if(this._currentTask._isResolved||this._currentTask._isRejected){this._currentTask=null;return}try{this._currentTask.callbackCollection&&this._currentTask.callbackCollection.cancel&&this._currentTask.callbackCollection.cancel(),this._currentTask._isResolved=!0,this._currentTask.resolve()}catch(e){this.logger.error("clear current task error: ",e)}this._currentTask=null}this._currentBatchTasks.length>0&&(this._currentBatchTasks.forEach(e=>{if(e!==this._currentTask&&!e._isResolved&&!e._isRejected)try{e.callbackCollection&&e.callbackCollection.cancel&&e.callbackCollection.cancel(),e._isResolved=!0,e.resolve()}catch(e){this.logger.error("clear current batch task error: ",e)}}),this._currentBatchTasks=[]),this._taskStack.forEach(e=>{if(!e._isResolved&&!e._isRejected&&(e._isResolved=!0,e.resolve(),e.callbackCollection&&e.callbackCollection.cancel))try{e.callbackCollection.cancel()}catch(e){this.logger.error("clear task error: ",e)}}),this._retryQueue.forEach(e=>{if(!e._isResolved&&!e._isRejected&&(e._isResolved=!0,e.resolve(),e.callbackCollection&&e.callbackCollection.cancel))try{e.callbackCollection.cancel()}catch(e){this.logger.error("clear retry task error: ",e)}}),this._taskStack=[],this._retryQueue=[],this._isRunning=!1}getTaskCount(){return this._taskStack.filter(e=>!e._isResolved&&!e._isRejected).length+this._currentBatchTasks.filter(e=>e!==this._currentTask&&!e._isResolved&&!e._isRejected).length+(!this._currentTask||this._currentTask._isResolved||this._currentTask._isRejected?0:1)+this._retryQueue.filter(e=>!e._isResolved&&!e._isRejected).length}isRunning(){return this._isRunning}getCurrentTaskId(){return this._currentTask?.id||null}whenAllTasksComplete(){return new Promise(e=>{let t=null,i=()=>{let r=0===this._taskStack.length,s=!this._isRunning,n=null===this._currentTask,o=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),l=0===this._retryQueue.length;r&&s&&n&&o&&l?(t&&clearTimeout(t),e()):t=setTimeout(i,500)};i()})}}let i=t;class r extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.stack=Error(e).stack,this.errMsg=t.errMsg,this.errorCode=t.errorCode,Object.defineProperty(this,"message",{enumerable:!0}),Object.defineProperty(this,"name",{enumerable:!0}),Object.defineProperty(this,"stack",{enumerable:!0}),Object.defineProperty(this,"errMsg",{enumerable:!0}),Object.defineProperty(this,"errorCode",{enumerable:!0})}toJSON(){return{name:this.name,message:this.message,stack:this.stack,errMsg:this.errMsg,errorCode:this.errorCode}}}class s{static args=null;_logger=null;_adTimeoutTime=8e3;_initSign="";_preserveOnEnd=!1;_rewardAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302];__bindAdErrorForeverHandler=this.__adErrorForeverHandler.bind(this);constructor(t){this._logger=new e({prefix:"RewardAdFather",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._preserveOnEnd=t?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return this._logger.warn("rewardAd has been initialized"),t?.(this._rewardAd),this;let i=Object.assign({},s.args,this._adConfig,e);if(!i.adUnitId)throw this._logger.error("reward args The adUnitId is required",i),new r("[RewardAdFather] reward args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100002});let n=tt.createRewardedVideoAd(i);return this._logger.info("bindAdErrorForeverHandler at initialized:",e?.foreverErrorBind),e?.foreverErrorBind&&(n?.offError(this.__bindAdErrorForeverHandler),n?.onError(this.__bindAdErrorForeverHandler)),this._rewardAd=n,this.__ad__=n,t?.(this._rewardAd),this}initialized(){return!!this._rewardAd}__adErrorForeverHandler(e){this.adErrorForeverHandler(e)}adErrorForeverHandler(e){return null}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return s.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(e=!1){return!this._rewardAd||this._preserveOnEnd||e?Promise.reject({errMsg:`can not destroy,ad is: ${!!this._rewardAd}, preserved: ${e}, preservedOnEnd: ${this._preserveOnEnd}`,errorCode:110003}):this._rewardAd.destroy().then(e=>Promise.resolve(e))?.catch(e=>Promise.reject({errMsg:`rewardAd destroy failed: ${JSON.stringify(e)}`,errorCode:110004}))?.finally(()=>{this._rewardAd=null})}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._rewardAd&&this._rewardAd.onClose(e)}offClose(e){this._rewardAd&&this._rewardAd.offClose(e)}show(){return this._rewardAd?this._rewardAd.show():Promise.reject({errMsg:"[RewardAdFather] can not show,rewardAd is null",errorCode:110001})}load(){return this._rewardAd?this._rewardAd.load():Promise.reject({errMsg:"[RewardAdFather] can not load,rewardAd is null",errorCode:110002})}onError(e){this._rewardAd&&this._rewardAd.onError(e)}offError(e){this._rewardAd&&this._rewardAd.offError(e)}onLoad(e){this._rewardAd&&this._rewardAd.onLoad(e)}offLoad(e){this._rewardAd&&this._rewardAd.offLoad(e)}placeholder(){return null}static buildArgs(t){t?.adUnitId||new e({prefix:"RewardAdFather",enable:!0}).error("RewardParams.adUnitId is required"),s.args=t}static async executeWithManager(t,r){return t&&t instanceof s?i.getInstance().addTask(t,r):(new e({prefix:"RewardAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let n=s,o=Object.entries({9999:"inner_default_other"}).reduce((e,[t,i])=>(e[i]=Number(t),e),{}),l={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2};Object.entries(l).reduce((e,[t,i])=>(e[i]=t,e),{});class a extends n{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_adExecuteArgs=null;_adNext=null;_scene=o.inner_default_other;_eId=null;_adTypeR=l.AD_TYPE_REWARD;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_lookUpRemainOnError=!1;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.__adCloseLister__.bind(this);bindAdErrorLister=this.__adErrorLister__.bind(this);bindAdLoadLister=this.__adLoadLister__.bind(this);bindApiAdErrorLister=this.__apiAdErrorLister__.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);bindAdTimeoutCloseLister=this.__adTimeoutCloseLister__.bind(this);bindAdTimeoutErrorLister=this.__adTimeoutErrorLister__.bind(this);constructor(t){super(t),this._logger=new e({prefix:"RewardAdNovel",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._needEndOnTimeout=t?.needEndOnTimeout??!0,this._lookUpRemainOnError=t?.lookUpRemainOnError??!1,this._onHalfway=t?.collection?.onHalfway??null,this._onShow=t?.collection?.onShow??null,this._onFinish=t?.collection?.onFinish??null,this._onAlways=t?.collection?.onAlways??null,this._onError=t?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=h.new({retry:e?.retry})}_onInnerExecuteBefore(e){return null}_onAdExecuteBefore(e){return null}_onInnerAdShowSuccess(e){return null}_onInnerAdDestroySuccess(e){return null}_onInnerAdDestroyFailed(e){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let i="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,eId:this._eId,msg:i,errorCode:1e5,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:i,errorCode:1e5}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout){let t=e?.timeout??this._adTimeoutTime;this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,eId:this._eId,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),this._adTimeoutBeforeEnd({scene:e?.scene,timeout:t}),this.onClose(this.bindAdTimeoutCloseLister),this.onError(this.bindAdTimeoutErrorLister);let i=()=>{e?.end({preserved:e?.preserved,resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})};try{this.customExecuteAfterTimeout({scene:e?.scene,timeout:t,end:i})}catch(e){this._logger.warn("use default timeout end task logic:",e),i()}},t)}}customExecuteAfterTimeout(e){throw Error("customExecuteAfterTimeout not be implemented")}_adTimeoutBeforeEnd(e){return e}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearInterval(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}ad(e,t=null){return this._alwaysCallback=e?.collection?.always,this._halfwayCallback=e?.collection?.halfway,this._finishedCallback=e?.collection?.finished,this._recovered=e?.recovered,this._preservedOnTimeout=e?.options?.preservedOnTimeout,this._adExecuteArgs=e,this._adNext=t,this._onAdExecuteBefore({eId:this._eId}),new Promise(i=>{this._resolve=i,this._adInner({options:{scene:e?.options?.scene,timeout:e?.options?.timeout},collection:{resolve:i,before:e.collection?.before,success:e.collection?.success,prelude:e.collection?.prelude},recovered:e.recovered},t)})}_adInner(e,t=null){this._eId=`ead_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,this._onInnerExecuteBefore({eId:this._eId});let i=e?.collection?.resolve,r=e?.options?.scene??this._scene??o.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,l=e?.collection?.prelude,a=e?.recovered??this._recovered,h=e=>{this._clearAdTimeout(),this.adDestroy(e?.preserved),i?.(Object.assign({scene:r,adTypeR:this._adTypeR,eId:this._eId},e?.resolvedValue)),this._resolve=null,t?.(Object.assign({scene:r},e?.nextValue)),this._next=null,this._adExecuteArgs=null,this._adNext=null},d=()=>{this._scene=r,s?.({scene:r}),this._before=s,this._onShow?.({scene:r}),this._adShowBeforeAnalytics({scene:r,eId:this._eId}),this._resolve=i,this._next=t,this._setAdTimeout({scene:r,end:h,timeout:e?.options?.timeout,preserved:this._preservedOnTimeout}),this._adPreludeInterval({scene:r,prelude:l}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:r}),this._success=n,this._adShowSuccessAnalytics({scene:r,eId:this._eId,result:1,recovered:a}),this._onInnerAdShowSuccess({scene:r,eId:this._eId,result:1,recovered:a})}).catch(e=>{var t,i;(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:r,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),t=this._ttErrorMsgs,(i=e?.errMsg)&&t.some(e=>RegExp(e,"i").test(i))||this._ttErrorCodes.includes(e?.errorCode))?h({scene:r,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?h({scene:r,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
|
|
2
|
+
tt: {errMsg: ${e?.errMsg}, errorCode: ${e?.errorCode}}`,errorCode:1e5}},nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:r,result:1,frequency:this.novelConfig.frequency}),d()}).catch(e=>{this._adLoadFailureAnalytics({scene:r,msg:e?.errMsg,result:0}),h({scene:r,resolvedValue:{apiError:e},nextValue:null})}))})};d()}adCircleInner(e){let t={scene:e?.options?.scene??this._adExecuteArgs?.options?.scene,timeout:e?.options?.timeout??this._adExecuteArgs?.options?.timeout},i={resolve:this._resolve,before:e?.collection?.before??this._adExecuteArgs?.collection?.before,success:e?.collection?.success??this._adExecuteArgs?.collection?.success,prelude:e?.collection?.prelude??this._adExecuteArgs?.collection?.prelude};this._adInner({options:t,collection:i,recovered:this._adExecuteArgs?.recovered},this._adNext)}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(...e){return this._alwaysCallback?.(...e)}onExeAlways(...e){return this._alwaysCallback?.(...e)}_outerHalfwayCallback(...e){return this._halfwayCallback?.(...e)}onExeHalfway(...e){return this._halfwayCallback?.(...e)}_outerFinishedCallback(...e){return this._finishedCallback?.(...e)}onExeFinished(...e){return this._finishedCallback?.(...e)}onFinish(...e){return this._onFinish?.(...e)}onHalfway(...e){return this._onHalfway?.(...e)}onAlways(...e){return this._onAlways?.(...e)}__adTimeoutCloseLister__(e){let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId});this._logger.warn("ad close lister that after task end because timeout:",t),this._clearAdTimeout(),this.offClose(this.bindAdTimeoutCloseLister),this.adTimeoutCloseLister(t)}adTimeoutCloseLister(e){return e}__adTimeoutErrorLister__(e){let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId});this._logger.error("ad error lister that after task end because timeout:",t),this._clearAdTimeout(),this.offError(this.bindAdTimeoutErrorLister),this.adTimeoutErrorLister(t)}adTimeoutErrorLister(e){return e}__adCloseLister__(e){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:+!!e.isEnded,ad_count:e.count});let t=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,eId:this._eId,end_type:e.isEnded?"finished":"halfway"}),i=e=>{this.adDestroy(),this._resolve?.(Object.assign({},t,e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null},r=e=>{let i=Object.assign({},t,e);i?.isEnded?(this._outerFinishedCallback(i),this.onExeFinished(i),this._onFinish?.(i),this.onFinish(i)):(this._outerHalfwayCallback(i),this.onExeHalfway(i),this._onHalfway?.(i),this.onHalfway(i)),this._outerCloseCallback(i),this.onExeAlways(i),this._onAlways?.(i),this.onAlways(i)};this.adCloseLister(t,{conn:r,end:i})}adCloseLister(e,t){t?.conn?.(e),t?.end?.(e)}__adErrorLister__(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adErrorLister(e);let t=()=>{this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR,eId:this._eId}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null};(!this._lookUpRemainOnError||0>=this.novelConfig.remain())&&t()}adErrorLister(e){return e}__apiAdErrorLister__(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,eId:this._eId,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.apiAdErrorLister(e),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}apiAdErrorLister(e){return e}__adLoadLister__(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e})),this.adLoadLister(e)}adLoadLister(e){return e}__novelDestroy__(e){this.destroy(e?.preserved).then(e=>{this._onInnerAdDestroySuccess?.({scene:this._scene,eId:this._eId,errMsg:e})}).catch(e=>{this._logger.warn("ad destroy failed:",JSON.stringify(e)),this._onInnerAdDestroyFailed?.({scene:this._scene,eId:this._eId,errorCode:e?.errorCode,errMsg:e?.errMsg})})}adDestroy(e=!1){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.__novelDestroy__({preserved:e})}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.__novelDestroy__(),this._resolve=null,this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.offClose(this._bindShiftCloseLister),this.__novelDestroy__(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this._recovered=null,this._preservedOnTimeout=null,this.offError(this._bindShiftErrorLister),this.__novelDestroy__(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null,this._adExecuteArgs=null,this._adNext=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return a.instance||(a.instance=new a(e)),a.instance}static getInstance(){if(!a.instance)throw Error("RewardAdNovel instance is not init");return a.instance}static new(e){return new a(e)}}class h{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new h(e)}}let d=a;class _{static args=null;_logger=null;_initSign="";_preserveOnEnd=!1;_interstitialAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302,140502];constructor(t){this._logger=new e({prefix:"InterstitialAdFather",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._preserveOnEnd=t?.preserveOnEnd??!1}initialize(e,t){if(this._interstitialAd)return this._logger.warn("interstitialAd has been initialized"),t?.(this._interstitialAd),this;let i=Object.assign({},_.args,this._adConfig,e);if(!i.adUnitId)throw this._logger.error("interstitialAd args The adUnitId is required",i),new r("[InterstitialAdFather] interstitialAd args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100003});let s=tt.createInterstitialAd(i);return this._interstitialAd=s,this.__ad__=s,t?.(this._interstitialAd),this}initialized(){return!!this._interstitialAd}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return _.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){this._interstitialAd&&!this._preserveOnEnd&&(this._interstitialAd.destroy(),this._interstitialAd=null)}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._interstitialAd&&this._interstitialAd.onClose(e)}offClose(e){this._interstitialAd&&this._interstitialAd.offClose(e)}show(){return this._interstitialAd?this._interstitialAd.show():Promise.reject({errMsg:"[InterstitialAdFather] can not show,interstitialAd is null",errorCode:120001})}load(){return this._interstitialAd?this._interstitialAd.load():Promise.reject({errMsg:"[InterstitialAdFather] can not load,interstitialAd is null",errorCode:120002})}onError(e){this._interstitialAd&&this._interstitialAd.onError(e)}offError(e){this._interstitialAd&&this._interstitialAd.offError(e)}onLoad(e){this._interstitialAd&&this._interstitialAd.onLoad(e)}offLoad(e){this._interstitialAd&&this._interstitialAd.offLoad(e)}placeholder(){return null}static buildArgs(t){t?.adUnitId||new e({prefix:"InterstitialAdFather",enable:!0}).error("interstitialAdParams.adUnitId is required"),_.args=t}static async executeWithManager(t,r){return t&&t instanceof _?i.getInstance().addTask(t,r):(new e({prefix:"InterstitialAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let c=_,u=Object.entries({9999:"inner_default_other"}).reduce((e,[t,i])=>(e[i]=Number(t),e),{}),f={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2};Object.entries(f).reduce((e,[t,i])=>(e[i]=t,e),{});class g extends c{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=u.inner_default_other;_adTypeR=f.AD_TYPE_INTERSTITIAL;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.adCloseLister.bind(this);bindAdErrorLister=this.adErrorLister.bind(this);bindAdLoadLister=this.adLoadLister.bind(this);bindApiAdErrorLister=this.apiAdErrorLister.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);constructor(t){super(t),this._logger=new e({prefix:"InterstitialAdNovel",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._needEndOnTimeout=t?.needEndOnTimeout??!0,this._onHalfway=t?.collection?.onHalfway??null,this._onShow=t?.collection?.onShow??null,this._onFinish=t?.collection?.onFinish??null,this._onAlways=t?.collection?.onAlways??null,this._onError=t?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=m.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let i="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,msg:i,errorCode:100001,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:i,errorCode:100001}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout&&(this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case, scene:",e?.scene),this._adShowFailureAnalytics({scene:e?.scene,msg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001}},nextValue:null})},this._adTimeoutTime))}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearTimeout(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}ad(e,t=null){return this._alwaysCallback=e?.collection?.always,this._halfwayCallback=e?.collection?.halfway,this._finishedCallback=e?.collection?.finished,this._onInnerExecuteBefore(),new Promise(i=>{this._adInner({options:{scene:e?.options?.scene},collection:{resolve:i,before:e.collection?.before,success:e.collection?.success,prelude:e.collection?.prelude}},t)})}_adInner(e,t=null){let i=e?.collection?.resolve,r=e?.options?.scene??this._scene??u.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,l=e=>{this._clearAdTimeout(),this.adDestroy(),i?.(Object.assign({scene:r,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:r},e?.nextValue))},a=()=>{this._scene=r,s?.({scene:r}),this._before=s,this._onShow?.({scene:r}),this._adShowBeforeAnalytics({scene:r}),this._resolve=i,this._next=t,this._setAdTimeout({scene:r,end:l}),this._adPreludeInterval({scene:r,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:r}),this._success=n,this._adShowSuccessAnalytics({scene:r,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{var t,i;(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:r,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),t=this._ttErrorMsgs,(i=e?.errMsg)&&t.some(e=>RegExp(e,"i").test(i))||this._ttErrorCodes.includes(e?.errorCode))?l({scene:r,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:r,resolvedValue:null,nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:r,result:1}),a()}).catch(e=>{this._adLoadFailureAnalytics({scene:r,msg:e?.errMsg,result:0}),l({scene:r,resolvedValue:{apiError:e},nextValue:null})}))})};a()}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(e){this._alwaysCallback?.(e)}_outerHalfwayCallback(e){this._halfwayCallback?.(e)}_outerFinishedCallback(e){this._finishedCallback?.(e)}adCloseLister(){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:1});let e={scene:this._scene},t=e=>{this.adDestroy(),this._resolve?.(Object.assign({},{scene:this._scene,adTypeR:this._adTypeR},e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null};this._outerFinishedCallback(e),this._onFinish?.(e),this._outerHalfwayCallback(e),this._onHalfway?.(e),this._outerCloseCallback(e),this._onAlways?.(e),t({end_type:"finished"})}adErrorLister(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this._onError?.(e),0>=this.novelConfig.remain()&&(this.adDestroy(),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null)}apiAdErrorLister(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}adLoadLister(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e}))}adDestroy(){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy()}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy(),this._resolve=null,this._next=null,this._success=null,this._before=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offClose(this._bindShiftCloseLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offError(this._bindShiftErrorLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return g.instance||(g.instance=new g(e)),g.instance}static getInstance(){if(!g.instance)throw Error("InterstitialAdNovel instance is not init");return g.instance}static new(e){return new g(e)}}class m{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new m(e)}}let y=g;class p{constructor(t={}){this.config={prefix:"storage_",expire:null,...t},this.logger=new e({prefix:"Storage"})}getTodayEndTimestamp(){let e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate(),23,59,59,999).getTime()}_setItem(e,t,i){let r=void 0!==i?i:this.config.expire;"today"===r&&(r=this.getTodayEndTimestamp()-Date.now());let s={value:t,expire:r,timestamp:Date.now()};try{tt.setStorageSync(e,JSON.stringify(s))}catch(e){console.error("Storage setItem error:",e)}}_getItem(e){try{let t=tt.getStorageSync(e);if(!t)return null;let i=JSON.parse(t);if(i.expire&&Date.now()-i.timestamp>i.expire)return this.removeItem(e),null;return i.value}catch(e){return console.error("Storage getItem error:",e),null}}setItem(e,t,i){let r=this.config.prefix+e;return this._setItem(r,t,i)}getItem(e){let t=this.config.prefix+e;return this._getItem(t)}getUserItem(e){let t=this.config.userId??"null";if("null"===t)return this.logger.error("userId is required"),null;let i=`${this.config.prefix}_${t}_${e}`;return this._getItem(i)}setUserItem(e,t,i){let r=this.config.userId??"null";if("null"===r)return void this.logger.error("userId is required");let s=`${this.config.prefix}_${r}_${e}`;return this._setItem(s,t,i)}removeUserItem(e){let t=this.config.userId??"null";if("null"===t)return void this.logger.error("userId is required");let i=`${this.config.prefix}_${t}_${e}`;try{tt.removeStorageSync(i)}catch(e){console.error("Storage removeUserItem error:",e)}}removeItem(e){try{tt.removeStorageSync(e)}catch(e){console.error("Storage removeItem error:",e)}}clear(){try{tt.clearStorageSync()}catch(e){console.error("Storage clear error:",e)}}keys(){try{let e=[];return(tt.getStorageInfoSync().keys??[]).forEach(t=>{if(t.startsWith(this.config.prefix)){let i=JSON.parse(tt.getStorageSync(t));(!i.expire||Date.now()-i.timestamp<=i.expire)&&e.push(t.replace(this.config.prefix,""))}}),e}catch(e){return console.error("Storage keys error:",e),[]}}static new(e){return new p(e)}}let A=p;class w{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=A.new({userId:e.userId}),!e.local_sign)throw Error("local_sign is required");this._local_sign=e.local_sign,this._total=e.total??0,this._expire=e.expire??"today",this._init()}_init(){this._initLocalTimes()}_adTimes(){return this._total}_safeLocalValue(e){return"object"!=typeof e||null===e?{}:e}_initLocalTimes(){let e=this._adTimes(),t=this.storage.getUserItem(this._local_sign),i=this._safeLocalValue(t);i&&i?.total==e||this.storage.setUserItem(this._local_sign,{total:e,today:i?.today??0},this._expire)}updateToday(){let e=this._adTimes(),t=this.storage.getUserItem(this._local_sign),i=this._safeLocalValue(t),r=i?.today??0;this.storage.setUserItem(this._local_sign,{total:e,today:r+1},this._expire)}remain(){let e=this.storage.getUserItem(this._local_sign),t=this._safeLocalValue(e),i=t?.today??0;return Number(t?.total??0)-Number(i)}save(e){let t=e;"number"!=typeof t&&(t=0);let i=this._adTimes();this.storage.setUserItem(this._local_sign,{total:i,today:t},this._expire)}clear(){this.storage.removeUserItem(this._local_sign)}reset(){let e=this._adTimes();this.storage.setUserItem(this._local_sign,{total:e,today:0},this._expire)}static new(e){return new w(e)}}class b{constructor(e={}){this.events={},this.queues={},this.onceEvents={},this.maxListeners=e.maxListeners||5,this.maxQueueSize=e.maxQueueSize||1,this.maxOnceEvents=e.maxOnceEvents||5}on(e,t){(this.events[e]||(this.events[e]=[]),this.events[e].length>=this.maxListeners)?console.warn(`EventEmitter: Maximum listeners (${this.maxListeners}) reached for event "${e}". Listener not added.`):(this.events[e].push(t),this.queues[e]&&this.queues[e].length>0&&(this.queues[e].forEach(e=>{t(...e)}),this.queues[e]=[]))}once(e,t){let i=(...r)=>{t(...r),this.off(e,i)};(this.onceEvents[e]||(this.onceEvents[e]=new Set),this.onceEvents[e].size>=this.maxOnceEvents)?console.warn(`EventEmitter: Maximum once events (${this.maxOnceEvents}) reached for event "${e}". Once listener not added.`):(this.onceEvents[e].add(i),this.on(e,i))}emit(e,...t){this.events[e]&&this.events[e].length>0?[...this.events[e]].forEach(e=>{e(...t)}):(this.queues[e]||(this.queues[e]=[]),this.queues[e].length>=this.maxQueueSize&&(console.warn(`EventEmitter: Maximum queue size (${this.maxQueueSize}) reached for event "${e}". Oldest event removed.`),this.queues[e].shift()),this.queues[e].push(t))}off(e,t){if(!t){this.events[e]=[],this.onceEvents[e]=new Set;return}this.events[e]=this.events[e].filter(e=>e!==t),this.onceEvents[e]&&this.onceEvents[e].delete(t)}removeAllListeners(e){e?(delete this.events[e],delete this.queues[e],delete this.onceEvents[e]):(this.events={},this.queues={},this.onceEvents={})}static geInstance(e){return this._instance||(this._instance=new b(e)),this._instance}}class E{constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.off(e,t)}}off(e,t){if(this.events[e]){if(!t){this.events[e]=[];return}this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,...t){this.events[e]&&this.events[e].forEach(i=>{try{i(...t)}catch(t){console.error(`Error in event listener for ${e}:`,t)}})}once(e,t){let i=(...r)=>{t(...r),this.off(e,i)};this.on(e,i)}listenerCount(e){return this.events[e]?this.events[e].length:0}removeAllListeners(){this.events={}}}class T{static instance=null;_logger=null;_initSign="";_needReport=!1;constructor(t){if(T.instance)return T.instance;this._logger=new e({prefix:"AdAnalyticsJS",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._needReport=t?.needReport??!1,this._commonConfig=t?.commonConfig??null,T.instance=this}initialize(e){return this._needReport?e:void this._logger.warn("needReport is false, do not report")}track(e,t,i){if(!this._needReport)return;if(!e)throw Error("eventName is required");let r=Object.assign({},this.getTrackCommonInfo(),t),s=i?.sign??"track";this._logger.log(`---------${s}----------:`,e,r),tt.reportAnalytics(e,r)}getCommonInfo(e){let t=this._commonConfig??{};return"string"==typeof e||"number"==typeof e?t[e]:t}getTrackCommonInfo(){return this._commonConfig??{}}identify(e,t){if(!e&&0!==e)throw Error("identify user_id is required");return this._commonConfig=Object.assign({},this._commonConfig,{__user_id:e},t),this}alias(){return null}pages(){return null}page(e,t){this.track(e,t,{sign:"page"})}cpage(e){return this.page("cpage",e)}placeholder(){return null}static build(e){return T.instance||(T.instance=new T(e)),T.instance}static getInstance(){if(!T.instance)throw Error("AdAnalyticsJS instance is not init");return T.instance}static new(e){return new T(e)}}let C=T,v=i;export{C as AdAnalyticsJS,i as AdExecuteManager,w as CountRecorder,b as EventEmitter,y as InterstitialAdDrama,c as InterstitialAdFather,y as InterstitialAdNovel,e as Logger,E as PubSub,d as RewardAdDrama,n as RewardAdFather,d as RewardAdNovel,r as SerializableError,A as Storage,v as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@singcl/ad-execute-manager",
|
|
3
|
-
"version": "1.17.
|
|
3
|
+
"version": "1.17.6",
|
|
4
4
|
"description": "A powerful and flexible ad execution management library for handling reward-based ads, interstitial ads, and other advertising formats in JavaScript applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|