@singcl/ad-execute-manager 1.10.1 → 1.10.2

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.
@@ -32,6 +32,10 @@ export type AdTask = {
32
32
  * 广告任务是否已被拒绝
33
33
  */
34
34
  _isRejected: boolean;
35
+ /**
36
+ * 广告任务后台恢复前台时重试次数
37
+ */
38
+ _retryCount: number;
35
39
  };
36
40
  export type IConstructArgs = {
37
41
  /**
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__,{SerializableError:()=>SerializableError,default:()=>src,InterstitialAdNovel:()=>ad_InterstitialAdNovel,PubSub:()=>EventEmitter,Storage:()=>ad_Storage,RewardAdGlobalRecorder:()=>ad_RewardAdGlobalRecorder,CountRecorder:()=>CountRecorder,RewardAdNovel:()=>ad_RewardAdNovel,AdAnalyticsJS:()=>ad_AdAnalyticsJS,InterstitialAdFather:()=>ad_InterstitialAdFather,Logger:()=>Logger,AdExecuteManager:()=>ad_AdExecuteManager,RewardAdFather:()=>ad_RewardAdFather,RewardAdSceneTriggerManager:()=>ad_RewardAdSceneTriggerManager});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))),ad_compose=compose;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)}}class AdExecuteManager{static _instance=null;_taskStack=[];_currentBatchTasks=[];_isRunning=!1;_currentTask=null;_isForeground=!0;_appShowListener=null;_appHideListener=null;_enableVisibilityListener=!1;_maxRetryCount=1;_retryQueue=[];constructor(e){this.logger=new Logger({prefix:"AdExecuteManager",enabled:!!e?.log}),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};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("应用在后台,暂停任务执行"),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:a,id:o}=e;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},l),h=Object.assign({id:o,isRetry:!1},d);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(h)}`),h?.apiError?.errMsg&&"string"==typeof h.apiError.errMsg&&h.apiError.errMsg.startsWith("ad_show_timeout: normal")&&h?.apiError?.timeout==i._adTimeoutTime&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++;let t=`任务 ${o} 在后台超时,加入重试队列 (第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount})`;this.logger.warn(t),h.isRetry=!0,h.retryReason=t,h.retryCount=e._retryCount,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;a(h),i?.record(h)}catch(n){let s=Object.assign({id:o,apiError:n,isRetry:!1});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(s)}`),e._isRejected=!0;try{i?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:o,apiError:e})))}a(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.onCancel&&this._currentTask.callbackCollection.onCancel(),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.onCancel&&e.callbackCollection.onCancel(),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.onCancel))try{e.callbackCollection.onCancel()}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.onCancel))try{e.callbackCollection.onCancel()}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,a=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),o=0===this._retryQueue.length;i&&s&&n&&a&&o?(t&&clearTimeout(t),e()):t=setTimeout(r,500)};r()})}}const ad_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;_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._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return console.warn("RewardAdFather: rewardAd has been initialized"),t?.(this._rewardAd),this;let r=Object.assign({},RewardAdFather.args,this._adConfig,e);if(!r.adUnitId)throw console.error("[RewardAdFather] 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 console.info("[RewardAdFather]: 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(){this._rewardAd&&!this._preserveOnEnd&&(this._rewardAd.destroy(),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||console.error("[RewardAdFather] RewardParams.adUnitId is required"),RewardAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof RewardAdFather?ad_AdExecuteManager.getInstance().addTask(e,t):(console.error("RewardAdFather: executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const ad_RewardAdFather=RewardAdFather;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)}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 ad_Storage=Storage;class CountRecorder{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=ad_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)}static new(e){return new CountRecorder(e)}}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 RewardAdGlobalRecorder{static instance=null;_initSign="";_halfway=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}];_finished=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}];constructor(e){if(RewardAdGlobalRecorder.instance)return RewardAdGlobalRecorder.instance;this._initSign=e?.sign??"",this._halfway=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}],this._finished=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}],RewardAdGlobalRecorder.instance=this}initialize(e){}_halfwayUpdate(e){let t=this._halfway.find(t=>t.scene===e.scene);t?t.count+=1:this._halfway.push({scene:e.scene,count:1})}_halfwayGet(e){let t=e?.scenes??[];return(t.length>0?this._halfway.filter(e=>t.includes(e.scene)):this._halfway).reduce((e,t)=>e+t.count,0)}_halfwayReset(){this._halfway=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}]}_finishedUpdate(e){let t=this._finished.find(t=>t.scene===e.scene);t?t.count+=1:this._finished.push({scene:e.scene,count:1})}_finishedGet(e){let t=e?.scenes??[];return(t.length>0?this._finished.filter(e=>t.includes(e.scene)):this._finished).reduce((e,t)=>e+t.count,0)}_finishedReset(){this._finished=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}]}record(e){switch(e.type){case"halfway":this._halfwayUpdate(e);break;case"finished":this._finishedUpdate(e)}}rest(e){switch(e){case"halfway":this._halfwayReset();break;case"finished":this._finishedReset()}}get(e){switch(e.type){case"halfway":return this._halfwayGet(e);case"finished":return this._finishedGet(e);default:return null}}placeholder(){return null}static build(e){return RewardAdGlobalRecorder.instance||(RewardAdGlobalRecorder.instance=new RewardAdGlobalRecorder(e)),RewardAdGlobalRecorder.instance}static getInstance(){if(!RewardAdGlobalRecorder.instance)throw Error("RewardAdGlobalRecorder instance is not init");return RewardAdGlobalRecorder.instance}}const ad_RewardAdGlobalRecorder=RewardAdGlobalRecorder;class RewardAdSceneTriggerManager{static instance=null;_initSign="";_currScene=null;_sceneTypeObj={};constructor(e){if(RewardAdSceneTriggerManager.instance)return RewardAdSceneTriggerManager.instance;this._initSign=e?.sign??"",this._sceneTypeObj=e?.sceneTypeObj??{},RewardAdSceneTriggerManager.instance=this}initialize(e){}addScene(e){return console.log("----------------------AD触发场景:--------------------",e),this._currScene=e,this}addSceneType(e=1){return this.addScene(this._sceneTypeObj[e]),this}getCurrentScene(){return this._currScene}placeholder(){return null}static build(e){return RewardAdSceneTriggerManager.instance||(RewardAdSceneTriggerManager.instance=new RewardAdSceneTriggerManager(e)),RewardAdSceneTriggerManager.instance}static getInstance(){if(!RewardAdSceneTriggerManager.instance)throw Error("RewardAdSceneTriggerManager instance is not init");return RewardAdSceneTriggerManager.instance}}const ad_RewardAdSceneTriggerManager=RewardAdSceneTriggerManager;class AdAnalyticsJS{static instance=null;_initSign="";_needReport=!1;constructor(e){if(AdAnalyticsJS.instance)return AdAnalyticsJS.instance;this._initSign=e?.sign??"",this._needReport=e?.needReport??!1,this._commonConfig=e?.commonConfig??null,AdAnalyticsJS.instance=this}initialize(e){return this._needReport?e:void console.warn("AdAnalyticsJS 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";console.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 ad_AdAnalyticsJS=AdAnalyticsJS;class RewardAdNovel extends ad_RewardAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=DEFAULT_SCENT_TEXT_OBJ.inner_default_other;_adTypeR=AD_TYPE_ENUM.AD_TYPE_REWARD;_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._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=RewardAdNovelConfig.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),console.warn("[RewardAdNovel] 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: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(()=>{console.warn("[RewardAdNovel] Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})},t)}}_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}addExecuteManager(e){return super.addExecuteManager(e)}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,timeout:e?.options?.timeout},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??DEFAULT_SCENT_TEXT_OBJ.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,a=e?.collection?.prelude,o=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:o,timeout:e?.options?.timeout}),this._adPreludeInterval({scene:i,prelude:a}),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}),matchErrorWithKeywords(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?o({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?o({scene:i,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
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__,{SerializableError:()=>SerializableError,default:()=>src,InterstitialAdNovel:()=>ad_InterstitialAdNovel,PubSub:()=>EventEmitter,Storage:()=>ad_Storage,RewardAdGlobalRecorder:()=>ad_RewardAdGlobalRecorder,CountRecorder:()=>CountRecorder,RewardAdNovel:()=>ad_RewardAdNovel,AdAnalyticsJS:()=>ad_AdAnalyticsJS,InterstitialAdFather:()=>ad_InterstitialAdFather,Logger:()=>Logger,AdExecuteManager:()=>ad_AdExecuteManager,RewardAdFather:()=>ad_RewardAdFather,RewardAdSceneTriggerManager:()=>ad_RewardAdSceneTriggerManager});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))),ad_compose=compose;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)}}class AdExecuteManager{static _instance=null;_taskStack=[];_currentBatchTasks=[];_isRunning=!1;_currentTask=null;_isForeground=!0;_appShowListener=null;_appHideListener=null;_enableVisibilityListener=!1;_maxRetryCount=1;_retryQueue=[];constructor(e){this.logger=new Logger({prefix:"AdExecuteManager",enabled:!!e?.log}),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};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("应用在后台,暂停任务执行"),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:a,id:o,_retryCount:l}=e;if(e._isResolved||e._isRejected)return void await r(t);this._currentTask=e;try{let d=async e=>{await r(Object.assign({},t,e))},h=await i.initialize(s).ad({options:s,collection:n},d),c=Object.assign({id:o,recoveredRetry:l>0,recoveredRetryCount:l},h);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(c)}`),c?.apiError?.errMsg&&"string"==typeof c.apiError.errMsg&&c.apiError.errMsg.startsWith("ad_show_timeout: normal")&&c?.apiError?.timeout==i._adTimeoutTime&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++;let t=`任务 ${o} 在后台超时,加入重试队列 (第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount})`;this.logger.warn(t),c.recoveredRetry=!0,c.recoveredRetryCount=e._retryCount,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;a(c),i?.record(c)}catch(n){let s=Object.assign({id:o,apiError:n,recoveredRetry:l>0,recoveredRetryCount:l});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(s)}`),e._isRejected=!0;try{i?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:o,apiError:e})))}a(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.onCancel&&this._currentTask.callbackCollection.onCancel(),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.onCancel&&e.callbackCollection.onCancel(),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.onCancel))try{e.callbackCollection.onCancel()}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.onCancel))try{e.callbackCollection.onCancel()}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,a=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),o=0===this._retryQueue.length;i&&s&&n&&a&&o?(t&&clearTimeout(t),e()):t=setTimeout(r,500)};r()})}}const ad_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;_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._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return console.warn("RewardAdFather: rewardAd has been initialized"),t?.(this._rewardAd),this;let r=Object.assign({},RewardAdFather.args,this._adConfig,e);if(!r.adUnitId)throw console.error("[RewardAdFather] 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 console.info("[RewardAdFather]: 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(){this._rewardAd&&!this._preserveOnEnd&&(this._rewardAd.destroy(),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||console.error("[RewardAdFather] RewardParams.adUnitId is required"),RewardAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof RewardAdFather?ad_AdExecuteManager.getInstance().addTask(e,t):(console.error("RewardAdFather: executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const ad_RewardAdFather=RewardAdFather;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)}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 ad_Storage=Storage;class CountRecorder{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=ad_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)}static new(e){return new CountRecorder(e)}}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 RewardAdGlobalRecorder{static instance=null;_initSign="";_halfway=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}];_finished=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}];constructor(e){if(RewardAdGlobalRecorder.instance)return RewardAdGlobalRecorder.instance;this._initSign=e?.sign??"",this._halfway=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}],this._finished=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}],RewardAdGlobalRecorder.instance=this}initialize(e){}_halfwayUpdate(e){let t=this._halfway.find(t=>t.scene===e.scene);t?t.count+=1:this._halfway.push({scene:e.scene,count:1})}_halfwayGet(e){let t=e?.scenes??[];return(t.length>0?this._halfway.filter(e=>t.includes(e.scene)):this._halfway).reduce((e,t)=>e+t.count,0)}_halfwayReset(){this._halfway=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}]}_finishedUpdate(e){let t=this._finished.find(t=>t.scene===e.scene);t?t.count+=1:this._finished.push({scene:e.scene,count:1})}_finishedGet(e){let t=e?.scenes??[];return(t.length>0?this._finished.filter(e=>t.includes(e.scene)):this._finished).reduce((e,t)=>e+t.count,0)}_finishedReset(){this._finished=[{scene:DEFAULT_SCENT_TEXT_OBJ.inner_default_other,count:0}]}record(e){switch(e.type){case"halfway":this._halfwayUpdate(e);break;case"finished":this._finishedUpdate(e)}}rest(e){switch(e){case"halfway":this._halfwayReset();break;case"finished":this._finishedReset()}}get(e){switch(e.type){case"halfway":return this._halfwayGet(e);case"finished":return this._finishedGet(e);default:return null}}placeholder(){return null}static build(e){return RewardAdGlobalRecorder.instance||(RewardAdGlobalRecorder.instance=new RewardAdGlobalRecorder(e)),RewardAdGlobalRecorder.instance}static getInstance(){if(!RewardAdGlobalRecorder.instance)throw Error("RewardAdGlobalRecorder instance is not init");return RewardAdGlobalRecorder.instance}}const ad_RewardAdGlobalRecorder=RewardAdGlobalRecorder;class RewardAdSceneTriggerManager{static instance=null;_initSign="";_currScene=null;_sceneTypeObj={};constructor(e){if(RewardAdSceneTriggerManager.instance)return RewardAdSceneTriggerManager.instance;this._initSign=e?.sign??"",this._sceneTypeObj=e?.sceneTypeObj??{},RewardAdSceneTriggerManager.instance=this}initialize(e){}addScene(e){return console.log("----------------------AD触发场景:--------------------",e),this._currScene=e,this}addSceneType(e=1){return this.addScene(this._sceneTypeObj[e]),this}getCurrentScene(){return this._currScene}placeholder(){return null}static build(e){return RewardAdSceneTriggerManager.instance||(RewardAdSceneTriggerManager.instance=new RewardAdSceneTriggerManager(e)),RewardAdSceneTriggerManager.instance}static getInstance(){if(!RewardAdSceneTriggerManager.instance)throw Error("RewardAdSceneTriggerManager instance is not init");return RewardAdSceneTriggerManager.instance}}const ad_RewardAdSceneTriggerManager=RewardAdSceneTriggerManager;class AdAnalyticsJS{static instance=null;_initSign="";_needReport=!1;constructor(e){if(AdAnalyticsJS.instance)return AdAnalyticsJS.instance;this._initSign=e?.sign??"",this._needReport=e?.needReport??!1,this._commonConfig=e?.commonConfig??null,AdAnalyticsJS.instance=this}initialize(e){return this._needReport?e:void console.warn("AdAnalyticsJS 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";console.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 ad_AdAnalyticsJS=AdAnalyticsJS;class RewardAdNovel extends ad_RewardAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=DEFAULT_SCENT_TEXT_OBJ.inner_default_other;_adTypeR=AD_TYPE_ENUM.AD_TYPE_REWARD;_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._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=RewardAdNovelConfig.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),console.warn("[RewardAdNovel] 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: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(()=>{console.warn("[RewardAdNovel] Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})},t)}}_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}addExecuteManager(e){return super.addExecuteManager(e)}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,timeout:e?.options?.timeout},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??DEFAULT_SCENT_TEXT_OBJ.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,a=e?.collection?.prelude,o=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:o,timeout:e?.options?.timeout}),this._adPreludeInterval({scene:i,prelude:a}),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}),matchErrorWithKeywords(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?o({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?o({scene:i,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
2
2
  tt: {errMsg: ${e?.errMsg}, errorCode: ${e?.errorCode}}`,errorCode:1e5}},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}),o({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(e){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:+!!e.isEnded,ad_count:e.count});let t={...e,scene:this._scene},r=t=>{this.adDestroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR},t)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null};e?.isEnded?(this._outerFinishedCallback(t),this._onFinish?.(t)):(this._outerHalfwayCallback(t),this._onHalfway?.(t)),this._outerCloseCallback(t),this._onAlways?.(t),r({end_type:e.isEnded?"finished":"halfway"})}adErrorLister(e){this._clearAdTimeout(),console.error("[RewardAdNovel] adErrorLister",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}apiAdErrorLister(e){this._clearAdTimeout(),console.error("[API RewardAdNovel] 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}),console.info("[RewardAdNovel] 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 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 ad_RewardAdNovel=RewardAdNovel;class InterstitialAdFather{static args=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._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._interstitialAd)return console.warn("InterstitialAdFather: interstitialAd has been initialized"),t?.(this._interstitialAd),this;let r=Object.assign({},InterstitialAdFather.args,this._adConfig,e);if(!r.adUnitId)throw console.error("[InterstitialAdFather] 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||console.error("[InterstitialAdFather] interstitialAdParams.adUnitId is required"),InterstitialAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof InterstitialAdFather?ad_AdExecuteManager.getInstance().addTask(e,t):(console.error("InterstitialAdFather: executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const ad_InterstitialAdFather=InterstitialAdFather;class InterstitialAdNovel extends ad_InterstitialAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=DEFAULT_SCENT_TEXT_OBJ.inner_default_other;_adTypeR=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._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),console.warn("[InterstitialAdNovel] 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(()=>{console.warn("[InterstitialAdNovel] 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}addExecuteManager(e){return super.addExecuteManager(e)}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??DEFAULT_SCENT_TEXT_OBJ.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,a=e?.collection?.prelude,o=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:o}),this._adPreludeInterval({scene:i,prelude:a}),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}),matchErrorWithKeywords(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?o({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?o({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}),o({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(),console.error("[InterstitialAdNovel] 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(),console.error("[API InterstitialAdNovel] 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}),console.info("[InterstitialAdNovel] 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 ad_InterstitialAdNovel=InterstitialAdNovel;class EventEmitter{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={}}}const src=ad_AdExecuteManager;for(var __rspack_i in exports.AdAnalyticsJS=__webpack_exports__.AdAnalyticsJS,exports.AdExecuteManager=__webpack_exports__.AdExecuteManager,exports.CountRecorder=__webpack_exports__.CountRecorder,exports.InterstitialAdFather=__webpack_exports__.InterstitialAdFather,exports.InterstitialAdNovel=__webpack_exports__.InterstitialAdNovel,exports.Logger=__webpack_exports__.Logger,exports.PubSub=__webpack_exports__.PubSub,exports.RewardAdFather=__webpack_exports__.RewardAdFather,exports.RewardAdGlobalRecorder=__webpack_exports__.RewardAdGlobalRecorder,exports.RewardAdNovel=__webpack_exports__.RewardAdNovel,exports.RewardAdSceneTriggerManager=__webpack_exports__.RewardAdSceneTriggerManager,exports.SerializableError=__webpack_exports__.SerializableError,exports.Storage=__webpack_exports__.Storage,exports.default=__webpack_exports__.default,__webpack_exports__)-1===["AdAnalyticsJS","AdExecuteManager","CountRecorder","InterstitialAdFather","InterstitialAdNovel","Logger","PubSub","RewardAdFather","RewardAdGlobalRecorder","RewardAdNovel","RewardAdSceneTriggerManager","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:s=!0}=e;this.prefix=t,this.enabled=s,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,s=`${i.getFullYear()}/${i.getMonth()+1}/${i.getDate()} ${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}`;return`[${s}] [${e.toUpperCase()}] [${this.prefix}] ${t}`}_log(e,t,...i){if(!this.enabled)return;let s=this.levels[e];if(void 0!==s&&this.currentLevel>=s){let s=this.formatMessage(e,t);switch(e){case"error":console.error(s,...i);break;case"warn":console.warn(s,...i);break;case"info":console.info(s,...i);break;case"log":default:console.log(s,...i);break;case"debug":console.debug(s,...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=[];constructor(t){this.logger=new e({prefix:"AdExecuteManager",enabled:!!t?.log}),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,s)=>{let r={adInstance:e,options:t.options??{},callbackCollection:t.collection??{},resolve:i,reject:s,id:`ad_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_isResolved:!1,_isRejected:!1,_retryCount:0};this._taskStack.push(r),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("应用在后台,暂停任务执行"),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:s,options:r,callbackCollection:n,resolve:o,id:l}=e;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 s.initialize(r).ad({options:r,collection:n},a),d=Object.assign({id:l,isRetry:!1},h);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(d)}`),d?.apiError?.errMsg&&"string"==typeof d.apiError.errMsg&&d.apiError.errMsg.startsWith("ad_show_timeout: normal")&&d?.apiError?.timeout==s._adTimeoutTime&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++;let t=`任务 ${l} 在后台超时,加入重试队列 (第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount})`;this.logger.warn(t),d.isRetry=!0,d.retryReason=t,d.retryCount=e._retryCount,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;o(d),s?.record(d)}catch(n){let r=Object.assign({id:l,apiError:n,isRetry:!1});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(r)}`),e._isRejected=!0;try{s?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:l,apiError:e})))}o(r),s?.record(r),await i(t)}}),i={roundTasks:t.length};t.map(e=>(t,i)=>async s=>await e(Object.assign({},t,s),i)).reduce((e,t)=>(i,s)=>e(i,t(i,s)))(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.onCancel&&this._currentTask.callbackCollection.onCancel(),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.onCancel&&e.callbackCollection.onCancel(),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.onCancel))try{e.callbackCollection.onCancel()}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.onCancel))try{e.callbackCollection.onCancel()}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 s=0===this._taskStack.length,r=!this._isRunning,n=null===this._currentTask,o=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),l=0===this._retryQueue.length;s&&r&&n&&o&&l?(t&&clearTimeout(t),e()):t=setTimeout(i,500)};i()})}}let i=t;class s 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 r{static args=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._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return console.warn("RewardAdFather: rewardAd has been initialized"),t?.(this._rewardAd),this;let i=Object.assign({},r.args,this._adConfig,e);if(!i.adUnitId)throw console.error("[RewardAdFather] reward args The adUnitId is required",i),new s("[RewardAdFather] reward args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100002});let n=tt.createRewardedVideoAd(i);return console.info("[RewardAdFather]: 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 r.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){this._rewardAd&&!this._preserveOnEnd&&(this._rewardAd.destroy(),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||console.error("[RewardAdFather] RewardParams.adUnitId is required"),r.args=e}static async executeWithManager(e,t){return e&&e instanceof r?i.getInstance().addTask(e,t):(console.error("RewardAdFather: executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let n=r;class o{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 s=void 0!==i?i:this.config.expire;"today"===s&&(s=this.getTodayEndTimestamp()-Date.now());let r={value:t,expire:s,timestamp:Date.now()};try{tt.setStorageSync(e,JSON.stringify(r))}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 s=this.config.prefix+e;return this._setItem(s,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 s=this.config.userId??"null";if("null"===s)return void this.logger.error("userId is required");let r=`${this.config.prefix}_${s}_${e}`;return this._setItem(r,t,i)}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 o(e)}}let l=o;class a{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=l.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),s=i?.today??0;this.storage.setUserItem(this._local_sign,{total:e,today:s+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)}static new(e){return new a(e)}}function h(e,t){return!!t&&e.some(e=>RegExp(e,"i").test(t))}let d=Object.entries({9999:"inner_default_other"}).reduce((e,[t,i])=>(e[i]=Number(t),e),{}),c={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2};Object.entries(c).reduce((e,[t,i])=>(e[i]=t,e),{});class _{static instance=null;_initSign="";_halfway=[{scene:d.inner_default_other,count:0}];_finished=[{scene:d.inner_default_other,count:0}];constructor(e){if(_.instance)return _.instance;this._initSign=e?.sign??"",this._halfway=[{scene:d.inner_default_other,count:0}],this._finished=[{scene:d.inner_default_other,count:0}],_.instance=this}initialize(e){}_halfwayUpdate(e){let t=this._halfway.find(t=>t.scene===e.scene);t?t.count+=1:this._halfway.push({scene:e.scene,count:1})}_halfwayGet(e){let t=e?.scenes??[];return(t.length>0?this._halfway.filter(e=>t.includes(e.scene)):this._halfway).reduce((e,t)=>e+t.count,0)}_halfwayReset(){this._halfway=[{scene:d.inner_default_other,count:0}]}_finishedUpdate(e){let t=this._finished.find(t=>t.scene===e.scene);t?t.count+=1:this._finished.push({scene:e.scene,count:1})}_finishedGet(e){let t=e?.scenes??[];return(t.length>0?this._finished.filter(e=>t.includes(e.scene)):this._finished).reduce((e,t)=>e+t.count,0)}_finishedReset(){this._finished=[{scene:d.inner_default_other,count:0}]}record(e){switch(e.type){case"halfway":this._halfwayUpdate(e);break;case"finished":this._finishedUpdate(e)}}rest(e){switch(e){case"halfway":this._halfwayReset();break;case"finished":this._finishedReset()}}get(e){switch(e.type){case"halfway":return this._halfwayGet(e);case"finished":return this._finishedGet(e);default:return null}}placeholder(){return null}static build(e){return _.instance||(_.instance=new _(e)),_.instance}static getInstance(){if(!_.instance)throw Error("RewardAdGlobalRecorder instance is not init");return _.instance}}let u=_;class f{static instance=null;_initSign="";_currScene=null;_sceneTypeObj={};constructor(e){if(f.instance)return f.instance;this._initSign=e?.sign??"",this._sceneTypeObj=e?.sceneTypeObj??{},f.instance=this}initialize(e){}addScene(e){return console.log("----------------------AD触发场景:--------------------",e),this._currScene=e,this}addSceneType(e=1){return this.addScene(this._sceneTypeObj[e]),this}getCurrentScene(){return this._currScene}placeholder(){return null}static build(e){return f.instance||(f.instance=new f(e)),f.instance}static getInstance(){if(!f.instance)throw Error("RewardAdSceneTriggerManager instance is not init");return f.instance}}let g=f;class w{static instance=null;_initSign="";_needReport=!1;constructor(e){if(w.instance)return w.instance;this._initSign=e?.sign??"",this._needReport=e?.needReport??!1,this._commonConfig=e?.commonConfig??null,w.instance=this}initialize(e){return this._needReport?e:void console.warn("AdAnalyticsJS needReport is false, do not report")}track(e,t,i){if(!this._needReport)return;if(!e)throw Error("eventName is required");let s=Object.assign({},this.getTrackCommonInfo(),t),r=i?.sign??"track";console.log(`-------------${r}-----------------------:`,e,s),tt.reportAnalytics(e,s)}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 w.instance||(w.instance=new w(e)),w.instance}static getInstance(){if(!w.instance)throw Error("AdAnalyticsJS instance is not init");return w.instance}static new(e){return new w(e)}}let y=w;class p extends n{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=d.inner_default_other;_adTypeR=c.AD_TYPE_REWARD;_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._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=A.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),console.warn("[RewardAdNovel] 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: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(()=>{console.warn("[RewardAdNovel] Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})},t)}}_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}addExecuteManager(e){return super.addExecuteManager(e)}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,timeout:e?.options?.timeout},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,s=e?.options?.scene??this._scene??d.inner_default_other,r=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,l=e=>{this._clearAdTimeout(),this.adDestroy(),i?.(Object.assign({scene:s,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:s},e?.nextValue))},a=()=>{this._scene=s,r?.({scene:s}),this._before=r,this._onShow?.({scene:s}),this._adShowBeforeAnalytics({scene:s}),this._resolve=i,this._next=t,this._setAdTimeout({scene:s,end:l,timeout:e?.options?.timeout}),this._adPreludeInterval({scene:s,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:s}),this._success=n,this._adShowSuccessAnalytics({scene:s,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:s,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),h(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?l({scene:s,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:s,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
1
+ class e{constructor(e={}){let{prefix:t="Logger",level:i="log",enabled:s=!0}=e;this.prefix=t,this.enabled=s,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,s=`${i.getFullYear()}/${i.getMonth()+1}/${i.getDate()} ${i.getHours()}:${i.getMinutes()}:${i.getSeconds()}`;return`[${s}] [${e.toUpperCase()}] [${this.prefix}] ${t}`}_log(e,t,...i){if(!this.enabled)return;let s=this.levels[e];if(void 0!==s&&this.currentLevel>=s){let s=this.formatMessage(e,t);switch(e){case"error":console.error(s,...i);break;case"warn":console.warn(s,...i);break;case"info":console.info(s,...i);break;case"log":default:console.log(s,...i);break;case"debug":console.debug(s,...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=[];constructor(t){this.logger=new e({prefix:"AdExecuteManager",enabled:!!t?.log}),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,s)=>{let r={adInstance:e,options:t.options??{},callbackCollection:t.collection??{},resolve:i,reject:s,id:`ad_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_isResolved:!1,_isRejected:!1,_retryCount:0};this._taskStack.push(r),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("应用在后台,暂停任务执行"),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:s,options:r,callbackCollection:n,resolve:o,id:l,_retryCount:a}=e;if(e._isResolved||e._isRejected)return void await i(t);this._currentTask=e;try{let h=async e=>{await i(Object.assign({},t,e))},d=await s.initialize(r).ad({options:r,collection:n},h),c=Object.assign({id:l,recoveredRetry:a>0,recoveredRetryCount:a},d);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(c)}`),c?.apiError?.errMsg&&"string"==typeof c.apiError.errMsg&&c.apiError.errMsg.startsWith("ad_show_timeout: normal")&&c?.apiError?.timeout==s._adTimeoutTime&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++;let t=`任务 ${l} 在后台超时,加入重试队列 (第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount})`;this.logger.warn(t),c.recoveredRetry=!0,c.recoveredRetryCount=e._retryCount,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;o(c),s?.record(c)}catch(n){let r=Object.assign({id:l,apiError:n,recoveredRetry:a>0,recoveredRetryCount:a});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(r)}`),e._isRejected=!0;try{s?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:l,apiError:e})))}o(r),s?.record(r),await i(t)}}),i={roundTasks:t.length};t.map(e=>(t,i)=>async s=>await e(Object.assign({},t,s),i)).reduce((e,t)=>(i,s)=>e(i,t(i,s)))(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.onCancel&&this._currentTask.callbackCollection.onCancel(),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.onCancel&&e.callbackCollection.onCancel(),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.onCancel))try{e.callbackCollection.onCancel()}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.onCancel))try{e.callbackCollection.onCancel()}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 s=0===this._taskStack.length,r=!this._isRunning,n=null===this._currentTask,o=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),l=0===this._retryQueue.length;s&&r&&n&&o&&l?(t&&clearTimeout(t),e()):t=setTimeout(i,500)};i()})}}let i=t;class s 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 r{static args=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._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return console.warn("RewardAdFather: rewardAd has been initialized"),t?.(this._rewardAd),this;let i=Object.assign({},r.args,this._adConfig,e);if(!i.adUnitId)throw console.error("[RewardAdFather] reward args The adUnitId is required",i),new s("[RewardAdFather] reward args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100002});let n=tt.createRewardedVideoAd(i);return console.info("[RewardAdFather]: 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 r.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){this._rewardAd&&!this._preserveOnEnd&&(this._rewardAd.destroy(),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||console.error("[RewardAdFather] RewardParams.adUnitId is required"),r.args=e}static async executeWithManager(e,t){return e&&e instanceof r?i.getInstance().addTask(e,t):(console.error("RewardAdFather: executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let n=r;class o{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 s=void 0!==i?i:this.config.expire;"today"===s&&(s=this.getTodayEndTimestamp()-Date.now());let r={value:t,expire:s,timestamp:Date.now()};try{tt.setStorageSync(e,JSON.stringify(r))}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 s=this.config.prefix+e;return this._setItem(s,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 s=this.config.userId??"null";if("null"===s)return void this.logger.error("userId is required");let r=`${this.config.prefix}_${s}_${e}`;return this._setItem(r,t,i)}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 o(e)}}let l=o;class a{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=l.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),s=i?.today??0;this.storage.setUserItem(this._local_sign,{total:e,today:s+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)}static new(e){return new a(e)}}function h(e,t){return!!t&&e.some(e=>RegExp(e,"i").test(t))}let d=Object.entries({9999:"inner_default_other"}).reduce((e,[t,i])=>(e[i]=Number(t),e),{}),c={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2};Object.entries(c).reduce((e,[t,i])=>(e[i]=t,e),{});class _{static instance=null;_initSign="";_halfway=[{scene:d.inner_default_other,count:0}];_finished=[{scene:d.inner_default_other,count:0}];constructor(e){if(_.instance)return _.instance;this._initSign=e?.sign??"",this._halfway=[{scene:d.inner_default_other,count:0}],this._finished=[{scene:d.inner_default_other,count:0}],_.instance=this}initialize(e){}_halfwayUpdate(e){let t=this._halfway.find(t=>t.scene===e.scene);t?t.count+=1:this._halfway.push({scene:e.scene,count:1})}_halfwayGet(e){let t=e?.scenes??[];return(t.length>0?this._halfway.filter(e=>t.includes(e.scene)):this._halfway).reduce((e,t)=>e+t.count,0)}_halfwayReset(){this._halfway=[{scene:d.inner_default_other,count:0}]}_finishedUpdate(e){let t=this._finished.find(t=>t.scene===e.scene);t?t.count+=1:this._finished.push({scene:e.scene,count:1})}_finishedGet(e){let t=e?.scenes??[];return(t.length>0?this._finished.filter(e=>t.includes(e.scene)):this._finished).reduce((e,t)=>e+t.count,0)}_finishedReset(){this._finished=[{scene:d.inner_default_other,count:0}]}record(e){switch(e.type){case"halfway":this._halfwayUpdate(e);break;case"finished":this._finishedUpdate(e)}}rest(e){switch(e){case"halfway":this._halfwayReset();break;case"finished":this._finishedReset()}}get(e){switch(e.type){case"halfway":return this._halfwayGet(e);case"finished":return this._finishedGet(e);default:return null}}placeholder(){return null}static build(e){return _.instance||(_.instance=new _(e)),_.instance}static getInstance(){if(!_.instance)throw Error("RewardAdGlobalRecorder instance is not init");return _.instance}}let u=_;class f{static instance=null;_initSign="";_currScene=null;_sceneTypeObj={};constructor(e){if(f.instance)return f.instance;this._initSign=e?.sign??"",this._sceneTypeObj=e?.sceneTypeObj??{},f.instance=this}initialize(e){}addScene(e){return console.log("----------------------AD触发场景:--------------------",e),this._currScene=e,this}addSceneType(e=1){return this.addScene(this._sceneTypeObj[e]),this}getCurrentScene(){return this._currScene}placeholder(){return null}static build(e){return f.instance||(f.instance=new f(e)),f.instance}static getInstance(){if(!f.instance)throw Error("RewardAdSceneTriggerManager instance is not init");return f.instance}}let g=f;class w{static instance=null;_initSign="";_needReport=!1;constructor(e){if(w.instance)return w.instance;this._initSign=e?.sign??"",this._needReport=e?.needReport??!1,this._commonConfig=e?.commonConfig??null,w.instance=this}initialize(e){return this._needReport?e:void console.warn("AdAnalyticsJS needReport is false, do not report")}track(e,t,i){if(!this._needReport)return;if(!e)throw Error("eventName is required");let s=Object.assign({},this.getTrackCommonInfo(),t),r=i?.sign??"track";console.log(`-------------${r}-----------------------:`,e,s),tt.reportAnalytics(e,s)}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 w.instance||(w.instance=new w(e)),w.instance}static getInstance(){if(!w.instance)throw Error("AdAnalyticsJS instance is not init");return w.instance}static new(e){return new w(e)}}let y=w;class p extends n{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=d.inner_default_other;_adTypeR=c.AD_TYPE_REWARD;_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._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=A.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),console.warn("[RewardAdNovel] 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: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(()=>{console.warn("[RewardAdNovel] Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})},t)}}_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}addExecuteManager(e){return super.addExecuteManager(e)}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,timeout:e?.options?.timeout},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,s=e?.options?.scene??this._scene??d.inner_default_other,r=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,l=e=>{this._clearAdTimeout(),this.adDestroy(),i?.(Object.assign({scene:s,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:s},e?.nextValue))},a=()=>{this._scene=s,r?.({scene:s}),this._before=r,this._onShow?.({scene:s}),this._adShowBeforeAnalytics({scene:s}),this._resolve=i,this._next=t,this._setAdTimeout({scene:s,end:l,timeout:e?.options?.timeout}),this._adPreludeInterval({scene:s,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:s}),this._success=n,this._adShowSuccessAnalytics({scene:s,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:s,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),h(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?l({scene:s,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:s,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
2
2
  tt: {errMsg: ${e?.errMsg}, errorCode: ${e?.errorCode}}`,errorCode:1e5}},nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:s,result:1}),a()}).catch(e=>{this._adLoadFailureAnalytics({scene:s,msg:e?.errMsg,result:0}),l({scene:s,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(e){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:+!!e.isEnded,ad_count:e.count});let t={...e,scene:this._scene},i=t=>{this.adDestroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR},t)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null};e?.isEnded?(this._outerFinishedCallback(t),this._onFinish?.(t)):(this._outerHalfwayCallback(t),this._onHalfway?.(t)),this._outerCloseCallback(t),this._onAlways?.(t),i({end_type:e.isEnded?"finished":"halfway"})}adErrorLister(e){this._clearAdTimeout(),console.error("[RewardAdNovel] adErrorLister",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}apiAdErrorLister(e){this._clearAdTimeout(),console.error("[API RewardAdNovel] 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}),console.info("[RewardAdNovel] 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 p.instance||(p.instance=new p(e)),p.instance}static getInstance(){if(!p.instance)throw Error("RewardAdNovel instance is not init");return p.instance}static new(e){return new p(e)}}class A{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 A(e)}}let m=p;class b{static args=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._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._interstitialAd)return console.warn("InterstitialAdFather: interstitialAd has been initialized"),t?.(this._interstitialAd),this;let i=Object.assign({},b.args,this._adConfig,e);if(!i.adUnitId)throw console.error("[InterstitialAdFather] interstitialAd args The adUnitId is required",i),new s("[InterstitialAdFather] interstitialAd args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100003});let r=tt.createInterstitialAd(i);return this._interstitialAd=r,this.__ad__=r,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 b.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||console.error("[InterstitialAdFather] interstitialAdParams.adUnitId is required"),b.args=e}static async executeWithManager(e,t){return e&&e instanceof b?i.getInstance().addTask(e,t):(console.error("InterstitialAdFather: executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let C=b;class T extends C{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=d.inner_default_other;_adTypeR=c.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._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=S.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),console.warn("[InterstitialAdNovel] 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(()=>{console.warn("[InterstitialAdNovel] 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}addExecuteManager(e){return super.addExecuteManager(e)}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,s=e?.options?.scene??this._scene??d.inner_default_other,r=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,l=e=>{this._clearAdTimeout(),this.adDestroy(),i?.(Object.assign({scene:s,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:s},e?.nextValue))},a=()=>{this._scene=s,r?.({scene:s}),this._before=r,this._onShow?.({scene:s}),this._adShowBeforeAnalytics({scene:s}),this._resolve=i,this._next=t,this._setAdTimeout({scene:s,end:l}),this._adPreludeInterval({scene:s,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:s}),this._success=n,this._adShowSuccessAnalytics({scene:s,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:s,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),h(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?l({scene:s,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:s,resolvedValue:null,nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:s,result:1}),a()}).catch(e=>{this._adLoadFailureAnalytics({scene:s,msg:e?.errMsg,result:0}),l({scene:s,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(),console.error("[InterstitialAdNovel] 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(),console.error("[API InterstitialAdNovel] 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}),console.info("[InterstitialAdNovel] 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 T.instance||(T.instance=new T(e)),T.instance}static getInstance(){if(!T.instance)throw Error("InterstitialAdNovel instance is not init");return T.instance}static new(e){return new T(e)}}class S{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 S(e)}}let E=T;class L{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=(...s)=>{t(...s),this.off(e,i)};this.on(e,i)}listenerCount(e){return this.events[e]?this.events[e].length:0}removeAllListeners(){this.events={}}}let k=i;export{y as AdAnalyticsJS,i as AdExecuteManager,a as CountRecorder,C as InterstitialAdFather,E as InterstitialAdNovel,e as Logger,L as PubSub,n as RewardAdFather,u as RewardAdGlobalRecorder,m as RewardAdNovel,g as RewardAdSceneTriggerManager,s as SerializableError,l as Storage,k as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@singcl/ad-execute-manager",
3
- "version": "1.10.1",
3
+ "version": "1.10.2",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {