@singcl/ad-execute-manager 2.0.5 → 2.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ad-interstitial/src/typings/ad.d.ts +1 -5
- package/dist/ad-reward/src/RewardAdFather.d.ts +6 -4
- package/dist/ad-reward/src/RewardAdNovel.d.ts +17 -56
- package/dist/ad-reward/src/typings/ad.d.ts +2 -6
- package/dist/core/src/AdExecuteManager.d.ts +18 -2
- package/dist/core/src/typings/ad.d.ts +15 -5
- package/dist/index.cjs +1 -2
- package/dist/index.d.ts +11 -11
- package/dist/index.js +1 -2
- package/dist/tools/src/typings/ad.d.ts +1 -5
- package/package.json +9 -2
- package/dist/core/typings/ad.d.ts +0 -208
|
@@ -80,14 +80,10 @@ export type CallbackCollection = {
|
|
|
80
80
|
* 半途退出广告外部回调
|
|
81
81
|
*/
|
|
82
82
|
halfway?: (ctx?: IExeCallbackArgs) => void;
|
|
83
|
-
/**
|
|
84
|
-
* 完成广告外部回调 不管看不看完
|
|
85
|
-
*/
|
|
86
|
-
complete?: (ctx?: IExeCallbackArgs) => void;
|
|
87
83
|
/**
|
|
88
84
|
* 取消广告外部回调
|
|
89
85
|
*/
|
|
90
|
-
|
|
86
|
+
cancel?: (ctx?: IExeCallbackArgs) => void;
|
|
91
87
|
/**
|
|
92
88
|
* 展示广告外部回调
|
|
93
89
|
*/
|
|
@@ -27,12 +27,13 @@ declare class RewardAdFather {
|
|
|
27
27
|
* @param {Object} ctx 上下文对象,用于传递数据和状态
|
|
28
28
|
* @param {Object} ctx.options 广告执行选项
|
|
29
29
|
* @param {Object} ctx.collection 回调集合
|
|
30
|
-
* @returns {Promise} 广告执行结果的Promise
|
|
31
30
|
*/
|
|
32
31
|
static executeWithManager(adInstance: any, ctx: {
|
|
33
32
|
options: any;
|
|
34
33
|
collection: any;
|
|
35
|
-
}): Promise<
|
|
34
|
+
}): Promise<import("@ad-execute-manager/core/dist/AdExecuteManager.js").ITaskResult & {
|
|
35
|
+
[key: string]: any;
|
|
36
|
+
}>;
|
|
36
37
|
/**
|
|
37
38
|
* @param {IConstructArgs} args
|
|
38
39
|
*/
|
|
@@ -103,12 +104,13 @@ declare class RewardAdFather {
|
|
|
103
104
|
* @param {Object} [ctx] 上下文对象,用于传递数据和状态
|
|
104
105
|
* @param {IRewordAdConfig} [ctx.options] 广告执行选项
|
|
105
106
|
* @param {CallbackCollection} [ctx.collection] 回调集合
|
|
106
|
-
* @returns {Promise.<unknown>} 广告执行结果的Promise
|
|
107
107
|
*/
|
|
108
108
|
addExecuteManager(ctx?: {
|
|
109
109
|
options?: IRewordAdConfig;
|
|
110
110
|
collection?: CallbackCollection;
|
|
111
|
-
}): Promise<
|
|
111
|
+
}): Promise<import("@ad-execute-manager/core/dist/AdExecuteManager.js").ITaskResult & {
|
|
112
|
+
[key: string]: any;
|
|
113
|
+
}>;
|
|
112
114
|
destroy(): void;
|
|
113
115
|
/**
|
|
114
116
|
* 清理广告实例
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export default RewardAdNovel;
|
|
2
|
-
export type IRewordAdConfig =
|
|
2
|
+
export type IRewordAdConfig = import("./typings/ad.js").IRewordAdConfig;
|
|
3
3
|
export type ICallbackArgs = {
|
|
4
4
|
/**
|
|
5
5
|
* 广告执行场景
|
|
@@ -83,24 +83,6 @@ export type ICloseArgs = {
|
|
|
83
83
|
*/
|
|
84
84
|
count: number;
|
|
85
85
|
};
|
|
86
|
-
export type IEndArgs = {
|
|
87
|
-
/**
|
|
88
|
-
* 是否解锁全部
|
|
89
|
-
*/
|
|
90
|
-
can_unlock_all?: boolean;
|
|
91
|
-
/**
|
|
92
|
-
* 是否解锁小说
|
|
93
|
-
*/
|
|
94
|
-
can_unlock_novel?: boolean;
|
|
95
|
-
/**
|
|
96
|
-
* 剩余次数
|
|
97
|
-
*/
|
|
98
|
-
remain?: number;
|
|
99
|
-
/**
|
|
100
|
-
* 结束类型
|
|
101
|
-
*/
|
|
102
|
-
end_type?: "halfway" | "finished";
|
|
103
|
-
};
|
|
104
86
|
export type IRewardedVideoAd = {
|
|
105
87
|
/**
|
|
106
88
|
* 显示激励视频广告
|
|
@@ -108,7 +90,7 @@ export type IRewardedVideoAd = {
|
|
|
108
90
|
show: () => Promise<void>;
|
|
109
91
|
};
|
|
110
92
|
/**
|
|
111
|
-
* @typedef {import('
|
|
93
|
+
* @typedef {import('./typings/ad.js').IRewordAdConfig} IRewordAdConfig
|
|
112
94
|
*/
|
|
113
95
|
/**
|
|
114
96
|
* @typedef ICallbackArgs
|
|
@@ -141,14 +123,6 @@ export type IRewardedVideoAd = {
|
|
|
141
123
|
* @property {boolean} isEnded 是否看完
|
|
142
124
|
* @property {number} count 完整观看次数
|
|
143
125
|
*/
|
|
144
|
-
/**
|
|
145
|
-
* @typedef IEndArgs
|
|
146
|
-
* @property {boolean} [can_unlock_all] 是否解锁全部
|
|
147
|
-
* @property {boolean} [can_unlock_novel] 是否解锁小说
|
|
148
|
-
* @property {number} [remain] 剩余次数
|
|
149
|
-
* @property {'halfway' | 'finished'} [end_type] 结束类型
|
|
150
|
-
*
|
|
151
|
-
*/
|
|
152
126
|
/**
|
|
153
127
|
* @typedef IRewardedVideoAd
|
|
154
128
|
* @property {() => Promise.<void>} show 显示激励视频广告
|
|
@@ -203,7 +177,6 @@ declare class RewardAdNovel extends RewardAdFather {
|
|
|
203
177
|
bindApiAdErrorLister: any;
|
|
204
178
|
_bindShiftCloseLister: any;
|
|
205
179
|
_bindShiftErrorLister: any;
|
|
206
|
-
_adConfig: any;
|
|
207
180
|
/**
|
|
208
181
|
* 初始化
|
|
209
182
|
* 子类可以选择覆盖此方法,或使用默认实现
|
|
@@ -226,13 +199,13 @@ declare class RewardAdNovel extends RewardAdFather {
|
|
|
226
199
|
* @param {object} _args
|
|
227
200
|
* @param {string} _args.scene 广告执行场景 必填
|
|
228
201
|
* @param {number} [_args.result] 广告执行成功结果 必填
|
|
229
|
-
* @param {import('
|
|
202
|
+
* @param {import('./typings/ad.js').RecoveredInfo} [_args.recovered] 恢复重试信息
|
|
230
203
|
* @returns
|
|
231
204
|
*/
|
|
232
205
|
_onInnerAdShowSuccess(_args: {
|
|
233
206
|
scene: string;
|
|
234
207
|
result?: number;
|
|
235
|
-
recovered?:
|
|
208
|
+
recovered?: import("./typings/ad.js").RecoveredInfo;
|
|
236
209
|
}): any;
|
|
237
210
|
/**
|
|
238
211
|
* 广告展示超时设置
|
|
@@ -290,14 +263,14 @@ declare class RewardAdNovel extends RewardAdFather {
|
|
|
290
263
|
* @param {string} _args.scene 广告执行场景 必填
|
|
291
264
|
* @param {string} [_args.msg] 广告执行成功原因
|
|
292
265
|
* @param {0|1} _args.result 广告执行成功结果 必填
|
|
293
|
-
* @param {import('
|
|
266
|
+
* @param {import('./typings/ad.js').RecoveredInfo} [_args.recovered] 恢复重试信息
|
|
294
267
|
* @returns
|
|
295
268
|
*/
|
|
296
269
|
protected _adShowSuccessAnalytics(_args: {
|
|
297
270
|
scene: string;
|
|
298
271
|
msg?: string;
|
|
299
272
|
result: 0 | 1;
|
|
300
|
-
recovered?:
|
|
273
|
+
recovered?: import("./typings/ad.js").RecoveredInfo;
|
|
301
274
|
}): any;
|
|
302
275
|
/**
|
|
303
276
|
* 广告展示失败分析
|
|
@@ -369,40 +342,28 @@ declare class RewardAdNovel extends RewardAdFather {
|
|
|
369
342
|
ad_count: number;
|
|
370
343
|
}): any;
|
|
371
344
|
get rewardAd(): import("./typings/create-rewarded-video-ad.js").RewardedVideoAd;
|
|
372
|
-
/**
|
|
373
|
-
* 确保广告按顺序执行
|
|
374
|
-
* @override
|
|
375
|
-
* @param {Object} [ctx] 上下文对象,用于传递数据和状态
|
|
376
|
-
* @param {IRewordAdConfig} [ctx.options] 广告执行选项
|
|
377
|
-
* @param {import('../typings/ad.js').CallbackCollection} [ctx.collection] 回调集合
|
|
378
|
-
* @returns {Promise.<IEndArgs & ICloseArgs | Undefined>}
|
|
379
|
-
*/
|
|
380
|
-
override addExecuteManager(ctx?: {
|
|
381
|
-
options?: IRewordAdConfig;
|
|
382
|
-
collection?: any;
|
|
383
|
-
}): Promise<(IEndArgs & ICloseArgs) | undefined>;
|
|
384
345
|
/**
|
|
385
346
|
* @override
|
|
386
347
|
* @param {object} [ctx] 广告执行上下文
|
|
387
|
-
* @param {import('
|
|
388
|
-
* @param {import('
|
|
389
|
-
* @param {import('
|
|
348
|
+
* @param {import('./typings/ad.js').IRewordAdConfig} [ctx.options] 广告执行选项
|
|
349
|
+
* @param {import('./typings/ad.js').CallbackCollection} [ctx.collection] 回调集合
|
|
350
|
+
* @param {import('./typings/ad.js').RecoveredInfo} [ctx.recovered] 恢复重试信息
|
|
390
351
|
* @param {Function} next 执行下一个任务的回调函数,手动调用以继续执行流程
|
|
391
|
-
* @returns {Promise.<
|
|
352
|
+
* @returns {Promise.<object | Undefined>}
|
|
392
353
|
*/
|
|
393
354
|
override ad(ctx?: {
|
|
394
|
-
options?:
|
|
395
|
-
collection?:
|
|
396
|
-
recovered?:
|
|
397
|
-
}, next?: Function): Promise<
|
|
398
|
-
_recovered:
|
|
355
|
+
options?: import("./typings/ad.js").IRewordAdConfig;
|
|
356
|
+
collection?: import("./typings/ad.js").CallbackCollection;
|
|
357
|
+
recovered?: import("./typings/ad.js").RecoveredInfo;
|
|
358
|
+
}, next?: Function): Promise<object | undefined>;
|
|
359
|
+
_recovered: import("./typings/ad.js").RecoveredInfo;
|
|
399
360
|
/**
|
|
400
361
|
* @param {object} [ctx] 广告执行上下文
|
|
401
362
|
* @param {object} [ctx.options] 广告执行选项
|
|
402
363
|
* @param {number} [ctx.options.scene] 广告执行场景 必填
|
|
403
364
|
* @param {number} [ctx.options.timeout] 广告超时时间 单位ms
|
|
404
365
|
* @param {object} ctx.collection 回调集合
|
|
405
|
-
* @param {import('
|
|
366
|
+
* @param {import('./typings/ad.js').RecoveredInfo} [ctx.recovered] 恢复重试信息
|
|
406
367
|
* @param {(v?: unknown) => void} ctx.collection.resolve 广告执行成功的回调函数
|
|
407
368
|
* @param {(v?: unknown) => void} [ctx.collection.reject] 广告执行失败的回调函数
|
|
408
369
|
* @param {(v?: unknown) => void} [ctx.collection.before] 广告执行前的回调函数
|
|
@@ -416,7 +377,7 @@ declare class RewardAdNovel extends RewardAdFather {
|
|
|
416
377
|
timeout?: number;
|
|
417
378
|
};
|
|
418
379
|
collection: object;
|
|
419
|
-
recovered?:
|
|
380
|
+
recovered?: import("./typings/ad.js").RecoveredInfo;
|
|
420
381
|
}, next?: Function): void;
|
|
421
382
|
_before: any;
|
|
422
383
|
_success: any;
|
|
@@ -69,7 +69,7 @@ export type IExeCallbackArgs = {
|
|
|
69
69
|
};
|
|
70
70
|
export type CallbackCollection = {
|
|
71
71
|
/**
|
|
72
|
-
*
|
|
72
|
+
* 完成广告外部回调 不管看不看完
|
|
73
73
|
*/
|
|
74
74
|
always?: (ctx?: IExeCallbackArgs) => void;
|
|
75
75
|
/**
|
|
@@ -80,14 +80,10 @@ export type CallbackCollection = {
|
|
|
80
80
|
* 半途退出广告外部回调
|
|
81
81
|
*/
|
|
82
82
|
halfway?: (ctx?: IExeCallbackArgs) => void;
|
|
83
|
-
/**
|
|
84
|
-
* 完成广告外部回调 不管看不看完
|
|
85
|
-
*/
|
|
86
|
-
complete?: (ctx?: IExeCallbackArgs) => void;
|
|
87
83
|
/**
|
|
88
84
|
* 取消广告外部回调
|
|
89
85
|
*/
|
|
90
|
-
|
|
86
|
+
cancel?: (ctx?: IExeCallbackArgs) => void;
|
|
91
87
|
/**
|
|
92
88
|
* 展示广告外部回调
|
|
93
89
|
*/
|
|
@@ -90,6 +90,20 @@ export type IConstructArgs = {
|
|
|
90
90
|
*/
|
|
91
91
|
errorRetryStrategy?: ErrorRetryStrategy;
|
|
92
92
|
};
|
|
93
|
+
export type ITaskResult = {
|
|
94
|
+
/**
|
|
95
|
+
* 广告任务的唯一标识符
|
|
96
|
+
*/
|
|
97
|
+
id: string;
|
|
98
|
+
/**
|
|
99
|
+
* 广告错误信息
|
|
100
|
+
*/
|
|
101
|
+
apiError?: import("./typings/ad.js").IApiError;
|
|
102
|
+
/**
|
|
103
|
+
* 广告任务后台恢复前台时预估重试次数的原因
|
|
104
|
+
*/
|
|
105
|
+
recovered?: import("./typings/ad.js").RecoveredInfo;
|
|
106
|
+
};
|
|
93
107
|
declare class AdExecuteManager {
|
|
94
108
|
/**
|
|
95
109
|
* 单例实例
|
|
@@ -212,12 +226,14 @@ declare class AdExecuteManager {
|
|
|
212
226
|
* @param {Object} ctx 广告执行上下文
|
|
213
227
|
* @param {IRewordAdConfig} ctx.options 广告执行选项
|
|
214
228
|
* @param {CallbackCollection} ctx.collection 回调集合
|
|
215
|
-
* @returns {Promise} 广告执行结果的Promise
|
|
229
|
+
* @returns {Promise.<ITaskResult & {[key: string]: any}> | Undefined>} 广告执行结果的Promise
|
|
216
230
|
*/
|
|
217
231
|
addTask(adInstance: IAdInstance, ctx: {
|
|
218
232
|
options: IRewordAdConfig;
|
|
219
233
|
collection: CallbackCollection;
|
|
220
|
-
}): Promise<
|
|
234
|
+
}): Promise<ITaskResult & {
|
|
235
|
+
[key: string]: any;
|
|
236
|
+
}> | undefined;
|
|
221
237
|
/**
|
|
222
238
|
* 组合所有任务
|
|
223
239
|
* @private
|
|
@@ -80,14 +80,10 @@ export type CallbackCollection = {
|
|
|
80
80
|
* 半途退出广告外部回调
|
|
81
81
|
*/
|
|
82
82
|
halfway?: (ctx?: IExeCallbackArgs) => void;
|
|
83
|
-
/**
|
|
84
|
-
* 完成广告外部回调 不管看不看完
|
|
85
|
-
*/
|
|
86
|
-
complete?: (ctx?: IExeCallbackArgs) => void;
|
|
87
83
|
/**
|
|
88
84
|
* 取消广告外部回调
|
|
89
85
|
*/
|
|
90
|
-
|
|
86
|
+
cancel?: (ctx?: IExeCallbackArgs) => void;
|
|
91
87
|
/**
|
|
92
88
|
* 展示广告外部回调
|
|
93
89
|
*/
|
|
@@ -115,6 +111,20 @@ export type RecoveredInfo = {
|
|
|
115
111
|
*/
|
|
116
112
|
message: string;
|
|
117
113
|
};
|
|
114
|
+
export type IApiError = {
|
|
115
|
+
/**
|
|
116
|
+
* 错误信息
|
|
117
|
+
*/
|
|
118
|
+
errMsg?: string;
|
|
119
|
+
/**
|
|
120
|
+
* 错误码
|
|
121
|
+
*/
|
|
122
|
+
errorCode?: number;
|
|
123
|
+
/**
|
|
124
|
+
* 错误信息
|
|
125
|
+
*/
|
|
126
|
+
message?: string;
|
|
127
|
+
};
|
|
118
128
|
export type ICallbackArgs = {
|
|
119
129
|
/**
|
|
120
130
|
* 广告执行场景
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
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__,{RewardAdFather:()=>src_RewardAdFather,SerializableError:()=>SerializableError,default:()=>packages_0,InterstitialAdNovel:()=>src_InterstitialAdNovel,PubSub:()=>PubSub,Storage:()=>src_Storage,CountRecorder:()=>CountRecorder,RewardAdNovel:()=>src_RewardAdNovel,AdAnalyticsJS:()=>src_AdAnalyticsJS,InterstitialAdFather:()=>src_InterstitialAdFather,InterstitialAdDrama:()=>src_InterstitialAdNovel,AdExecuteManager:()=>src_AdExecuteManager,Logger:()=>Logger,RewardAdDrama:()=>src_RewardAdNovel});const logger_namespaceObject=require("@ad-execute-manager/logger");function isTimeoutError(e,t){return e?.errMsg&&"string"==typeof e.errMsg&&e.errMsg.startsWith("ad_show_timeout: normal")&&e?.timeout==t}function isBackgroundError(e){return e?.errMsg&&"string"==typeof e.errMsg&&(e.errMsg.startsWith("app in background is not support show ad")||e.errMsg.startsWith("other controller is presented"))}function needRetryAdError({apiError:e,configuredAdTimeout:t,errorRetryStrategy:r}){return!!(r?.timeout&&isTimeoutError(e,t)||r?.background&&isBackgroundError(e))}const compose=e=>e.map(e=>(t,r)=>async i=>await e(Object.assign({},t,i),r)).reduce((e,t)=>(r,i)=>e(r,t(r,i))),src_compose=compose;class AdExecuteManager{static _instance=null;_taskStack=[];_currentBatchTasks=[];_isRunning=!1;_currentTask=null;_isForeground=!0;_appShowListener=null;_appHideListener=null;_enableVisibilityListener=!1;_maxRetryCount=1;_retryQueue=[];_errorRetryStrategy={timeout:!0,background:!0};constructor(e){this.logger=new logger_namespaceObject.Logger({prefix:"AdExecuteManager",enabled:!!e?.log}),e?.errorRetryStrategy&&(this._errorRetryStrategy=Object.assign({},this._errorRetryStrategy,e?.errorRetryStrategy)),this._enableVisibilityListener=e?.enableVisibilityListener,this._maxRetryCount=e?.maxRetryCount??1,this._enableVisibilityListener&&this._initVisibilityListener()}initialize(e){return this}static getInstance(e){return AdExecuteManager._instance||(AdExecuteManager._instance=new AdExecuteManager(e)),AdExecuteManager._instance}static build(e){return AdExecuteManager._instance||(AdExecuteManager._instance=new AdExecuteManager(e)),AdExecuteManager._instance}static new(e){return new AdExecuteManager(e)}static getSafeInstance(){return AdExecuteManager._instance?AdExecuteManager._instance:(this.logger.error("AdExecuteManager实例不存在"),null)}_initVisibilityListener(){!("u"<typeof tt)&&tt.onAppShow&&tt.onAppHide?(this._appShowListener=()=>{this._isForeground=!0,this._handleAppShow()},this._appHideListener=()=>{this._isForeground=!1,this._handleAppHide()},tt.onAppShow(this._appShowListener),tt.onAppHide(this._appHideListener),this.logger.info("前后台监听器已初始化")):this.logger.warn("tt API不可用,无法监听前后台状态")}_handleAppHide(){if(this._isRunning&&this._currentBatchTasks.length>0){let e=this._currentBatchTasks.filter(e=>e.id!==this._currentTask?.id&&!e._isResolved&&!e._isRejected);e.length>0&&(this.logger.info(`将 ${e.length} 个未执行的任务放回任务栈,任务ID: ${e.map(e=>e.id).join(",")}`),this._taskStack=[...e,...this._taskStack],this._currentBatchTasks=this._currentBatchTasks.filter(t=>!e.some(e=>e.id===t.id)))}}_handleAppShow(){this._retryQueue.length>0&&(this.logger.info(`应用进入前台:优先执行重试队列,任务数: ${this._retryQueue.length}, 任务ID: ${this._retryQueue.map(e=>e.id).join(",")}`),this._taskStack=[...this._retryQueue,...this._taskStack],this._retryQueue=[]),this._taskStack.length>0&&!this._isRunning&&(this.logger.info(`应用进入前台:恢复待执行任务数: ${this._taskStack.length}, 任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._compose())}destroyVisibilityListener(){this._appShowListener&&"u">typeof tt&&tt.offAppShow&&(tt.offAppShow(this._appShowListener),this._appShowListener=null),this._appHideListener&&"u">typeof tt&&tt.offAppHide&&(tt.offAppHide(this._appHideListener),this._appHideListener=null),this.logger.info("前后台监听器已销毁")}enableVisibilityListener(){this._enableVisibilityListener||(this._enableVisibilityListener=!0,this._initVisibilityListener()),this.logger.info("前后台监听器已启用")}disableVisibilityListener(){this._enableVisibilityListener&&(this._enableVisibilityListener=!1,this.destroyVisibilityListener()),this.logger.info("前后台监听器已禁用")}isVisibilityListenerEnabled(){return this._enableVisibilityListener}addTask(e,t){return e&&"function"==typeof e.ad?new Promise((r,i)=>{let s={adInstance:e,options:t.options??{},callbackCollection:t.collection??{},resolve:r,reject:i,id:`ad_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_isResolved:!1,_isRejected:!1,_retryCount:0,_retryMsg:"ok"};this._taskStack.push(s),this._isRunning||this._compose()}):(this.logger.error("无效的广告实例 请正确实现.ad方法"),Promise.reject(Error("无效的广告实例")))}_compose(){if(0===this._taskStack.length){this._isRunning=!1,this._currentTask=null;return}if(!this._isForeground){this.logger.info(`应用处于后台,暂停任务执行,任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._isRunning=!1;return}this._isRunning=!0;let e=[...this._taskStack];this._taskStack=[],this._currentBatchTasks=e;let t=e.map(e=>async(t,r)=>{let{adInstance:i,options:s,callbackCollection:n,resolve:o,id:a,_retryCount:l,_retryMsg:d}=e,h={count:l,retry:l>0,message:d};if(e._isResolved||e._isRejected)return void await r(t);this._currentTask=e;try{let l=async e=>{await r(Object.assign({},t,e))},d=await i.initialize(s).ad({options:s,collection:n,recovered:h},l),_=Object.assign({id:a,recovered:h},d);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(_)}`),needRetryAdError({apiError:_?.apiError,configuredAdTimeout:i._adTimeoutTime,errorRetryStrategy:this._errorRetryStrategy})&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++,e._retryMsg=_?.apiError?.errMsg||"unknown";let t=`任务 ${a} 在后台失败,加入重试队列 (即将第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount}, 重试原因: ${e._retryMsg})`;this.logger.warn(t),_.recovered.retry=!0,_.recovered.count=e._retryCount,_.recovered.message=e._retryMsg,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;o(_),i?.record(_)}catch(n){let s=Object.assign({id:a,apiError:n,recovered:h});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(s)}`),e._isRejected=!0;try{i?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:a,apiError:e})))}o(s),i?.record(s),await r(t)}}),r={roundTasks:t.length};compose(t)(r,async e=>{this.logger.info("本轮活动队列已经清空",e),this._taskStack.length>0?Promise.resolve().then(()=>{this._compose()}):(this._isRunning=!1,this._currentTask=null,this._currentBatchTasks=[])})()}clearTasks(){if(this._currentTask){if(this._currentTask._isResolved||this._currentTask._isRejected){this._currentTask=null;return}try{this._currentTask.callbackCollection&&this._currentTask.callbackCollection.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,o=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),a=0===this._retryQueue.length;i&&s&&n&&o&&a?(t&&clearTimeout(t),e()):t=setTimeout(r,500)};r()})}}const src_AdExecuteManager=AdExecuteManager,core_namespaceObject=require("@ad-execute-manager/core");class dist_e extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.stack=Error(e).stack,this.errMsg=t.errMsg,this.errorCode=t.errorCode,Object.defineProperty(this,"message",{enumerable:!0}),Object.defineProperty(this,"name",{enumerable:!0}),Object.defineProperty(this,"stack",{enumerable:!0}),Object.defineProperty(this,"errMsg",{enumerable:!0}),Object.defineProperty(this,"errorCode",{enumerable:!0})}toJSON(){return{name:this.name,message:this.message,stack:this.stack,errMsg:this.errMsg,errorCode:this.errorCode}}}class RewardAdFather{static args=null;_logger=null;_adTimeoutTime=8e3;_initSign="";_preserveOnEnd=!1;_rewardAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302];__bindAdErrorForeverHandler=this.__adErrorForeverHandler.bind(this);constructor(e){this._logger=new logger_namespaceObject.Logger({prefix:"RewardAdFather",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return this._logger.warn("rewardAd has been initialized"),t?.(this._rewardAd),this;let r=Object.assign({},RewardAdFather.args,this._adConfig,e);if(!r.adUnitId)throw this._logger.error("reward args The adUnitId is required",r),new dist_e("[RewardAdFather] reward args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100002});let i=tt.createRewardedVideoAd(r);return this._logger.info("bindAdErrorForeverHandler at initialized:",e?.foreverErrorBind),e?.foreverErrorBind&&(i?.offError(this.__bindAdErrorForeverHandler),i?.onError(this.__bindAdErrorForeverHandler)),this._rewardAd=i,this.__ad__=i,t?.(this._rewardAd),this}initialized(){return!!this._rewardAd}__adErrorForeverHandler(e){this.adErrorForeverHandler(e)}adErrorForeverHandler(e){return null}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return RewardAdFather.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){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||new logger_namespaceObject.Logger({prefix:"RewardAdFather",enable:!0}).error("RewardParams.adUnitId is required"),RewardAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof RewardAdFather?core_namespaceObject.AdExecuteManager.getInstance().addTask(e,t):(new logger_namespaceObject.Logger({prefix:"RewardAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const src_RewardAdFather=RewardAdFather;function matchErrorWithKeywords(e,t){return!!t&&e.some(e=>RegExp(e,"i").test(t))}function getAdSceneTextObj(e){return Object.entries(e).reduce((e,[t,r])=>(e[r]=Number(t),e),{})}const DEFAULT_SCENT_TYPE_OBJ={9999:"inner_default_other"},DEFAULT_SCENT_TEXT_OBJ=getAdSceneTextObj(DEFAULT_SCENT_TYPE_OBJ),AD_TYPE_ENUM={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2},AD_TYPE_ENUM_REVERSE=Object.entries(AD_TYPE_ENUM).reduce((e,[t,r])=>(e[r]=t,e),{});class RewardAdNovel extends src_RewardAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_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._logger=new logger_namespaceObject.Logger({prefix:"RewardAdNovel",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._needEndOnTimeout=e?.needEndOnTimeout??!0,this._onHalfway=e?.collection?.onHalfway??null,this._onShow=e?.collection?.onShow??null,this._onFinish=e?.collection?.onFinish??null,this._onAlways=e?.collection?.onAlways??null,this._onError=e?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=RewardAdNovelConfig.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(e){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let r="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,msg:r,errorCode:1e5,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:r,errorCode:1e5}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout){let t=e?.timeout??this._adTimeoutTime;this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),this._adTimeoutBeforeEnd({scene:e?.scene,timeout:t}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})},t)}}_adTimeoutBeforeEnd(e){return e}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearInterval(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}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._recovered=e?.recovered,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},recovered:e.recovered},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,o=e?.collection?.prelude,a=e?.recovered??this._recovered,l=e=>{this._clearAdTimeout(),this.adDestroy(),r?.(Object.assign({scene:i,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:i},e?.nextValue))},d=()=>{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:l,timeout:e?.options?.timeout}),this._adPreludeInterval({scene:i,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:i}),this._success=n,this._adShowSuccessAnalytics({scene:i,result:1,recovered:a}),this._onInnerAdShowSuccess({scene:i,result:1,recovered:a})}).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))?l({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:i,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
|
|
2
|
-
tt: {errMsg: ${e?.errMsg}, errorCode: ${e?.errorCode}}`,errorCode:1e5}},nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:i,result:1,frequency:this.novelConfig.frequency}),d()}).catch(e=>{this._adLoadFailureAnalytics({scene:i,msg:e?.errMsg,result:0}),l({scene:i,resolvedValue:{apiError:e},nextValue:null})}))})};d()}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=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,end_type:e.isEnded?"finished":"halfway"}),r=e=>{this.adDestroy(),this._resolve?.(Object.assign({},t,e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null},i=e=>{let r=Object.assign({},t,e);r?.isEnded?(this._outerFinishedCallback(r),this._onFinish?.(r)):(this._outerHalfwayCallback(r),this._onHalfway?.(r)),this._outerCloseCallback(r),this._onAlways?.(r)};this.adCloseLister(t,{conn:i,end:r})}adCloseLister(e,t){t?.conn?.(e),t?.end?.(e)}__adErrorLister__(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adErrorLister(e),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}adErrorLister(e){return e}__apiAdErrorLister__(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.apiAdErrorLister(e),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}apiAdErrorLister(e){return e}__adLoadLister__(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e})),this.adLoadLister(e)}adLoadLister(e){return e}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._recovered=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._recovered=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._recovered=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._recovered=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 src_RewardAdNovel=RewardAdNovel;class serializable_error_dist_e 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 InterstitialAdFather{static args=null;_logger=null;_initSign="";_preserveOnEnd=!1;_interstitialAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302,140502];constructor(e){this._logger=new logger_namespaceObject.Logger({prefix:"InterstitialAdFather",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._preserveOnEnd=e?.preserveOnEnd??!1}initialize(e,t){if(this._interstitialAd)return this._logger.warn("interstitialAd has been initialized"),t?.(this._interstitialAd),this;let r=Object.assign({},InterstitialAdFather.args,this._adConfig,e);if(!r.adUnitId)throw this._logger.error("interstitialAd args The adUnitId is required",r),new serializable_error_dist_e("[InterstitialAdFather] interstitialAd args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100003});let i=tt.createInterstitialAd(r);return this._interstitialAd=i,this.__ad__=i,t?.(this._interstitialAd),this}initialized(){return!!this._interstitialAd}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return InterstitialAdFather.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){this._interstitialAd&&!this._preserveOnEnd&&(this._interstitialAd.destroy(),this._interstitialAd=null)}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._interstitialAd&&this._interstitialAd.onClose(e)}offClose(e){this._interstitialAd&&this._interstitialAd.offClose(e)}show(){return this._interstitialAd?this._interstitialAd.show():Promise.reject({errMsg:"[InterstitialAdFather] can not show,interstitialAd is null",errorCode:120001})}load(){return this._interstitialAd?this._interstitialAd.load():Promise.reject({errMsg:"[InterstitialAdFather] can not load,interstitialAd is null",errorCode:120002})}onError(e){this._interstitialAd&&this._interstitialAd.onError(e)}offError(e){this._interstitialAd&&this._interstitialAd.offError(e)}onLoad(e){this._interstitialAd&&this._interstitialAd.onLoad(e)}offLoad(e){this._interstitialAd&&this._interstitialAd.offLoad(e)}placeholder(){return null}static buildArgs(e){e?.adUnitId||new logger_namespaceObject.Logger({prefix:"InterstitialAdFather",enable:!0}).error("interstitialAdParams.adUnitId is required"),InterstitialAdFather.args=e}static async executeWithManager(e,t){return e&&e instanceof InterstitialAdFather?core_namespaceObject.AdExecuteManager.getInstance().addTask(e,t):(new logger_namespaceObject.Logger({prefix:"InterstitialAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}const src_InterstitialAdFather=InterstitialAdFather;function functional_matchErrorWithKeywords(e,t){return!!t&&e.some(e=>RegExp(e,"i").test(t))}function functional_getAdSceneTextObj(e){return Object.entries(e).reduce((e,[t,r])=>(e[r]=Number(t),e),{})}const const_DEFAULT_SCENT_TYPE_OBJ={9999:"inner_default_other"},const_DEFAULT_SCENT_TEXT_OBJ=functional_getAdSceneTextObj(const_DEFAULT_SCENT_TYPE_OBJ),const_AD_TYPE_ENUM={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2},const_AD_TYPE_ENUM_REVERSE=Object.entries(const_AD_TYPE_ENUM).reduce((e,[t,r])=>(e[r]=t,e),{});class InterstitialAdNovel extends src_InterstitialAdFather{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=const_DEFAULT_SCENT_TEXT_OBJ.inner_default_other;_adTypeR=const_AD_TYPE_ENUM.AD_TYPE_INTERSTITIAL;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.adCloseLister.bind(this);bindAdErrorLister=this.adErrorLister.bind(this);bindAdLoadLister=this.adLoadLister.bind(this);bindApiAdErrorLister=this.apiAdErrorLister.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);constructor(e){super(e),this._logger=new logger_namespaceObject.Logger({prefix:"InterstitialAdNovel",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._adConfig=e?.adConfig??{},this._needEndOnTimeout=e?.needEndOnTimeout??!0,this._onHalfway=e?.collection?.onHalfway??null,this._onShow=e?.collection?.onShow??null,this._onFinish=e?.collection?.onFinish??null,this._onAlways=e?.collection?.onAlways??null,this._onError=e?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=InterstitialAdNovel_RewardAdNovelConfig.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let r="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,msg:r,errorCode:100001,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:r,errorCode:100001}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout&&(this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case, scene:",e?.scene),this._adShowFailureAnalytics({scene:e?.scene,msg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001}},nextValue:null})},this._adTimeoutTime))}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearTimeout(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}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??const_DEFAULT_SCENT_TEXT_OBJ.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,a=e=>{this._clearAdTimeout(),this.adDestroy(),r?.(Object.assign({scene:i,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:i},e?.nextValue))},l=()=>{this._scene=i,s?.({scene:i}),this._before=s,this._onShow?.({scene:i}),this._adShowBeforeAnalytics({scene:i}),this._resolve=r,this._next=t,this._setAdTimeout({scene:i,end:a}),this._adPreludeInterval({scene:i,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:i}),this._success=n,this._adShowSuccessAnalytics({scene:i,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:i,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),functional_matchErrorWithKeywords(this._ttErrorMsgs,e?.errMsg)||this._ttErrorCodes.includes(e?.errorCode))?a({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?a({scene:i,resolvedValue:null,nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:i,result:1}),l()}).catch(e=>{this._adLoadFailureAnalytics({scene:i,msg:e?.errMsg,result:0}),a({scene:i,resolvedValue:{apiError:e},nextValue:null})}))})};l()}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(e){this._alwaysCallback?.(e)}_outerHalfwayCallback(e){this._halfwayCallback?.(e)}_outerFinishedCallback(e){this._finishedCallback?.(e)}adCloseLister(){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:1});let e={scene:this._scene},t=e=>{this.adDestroy(),this._resolve?.(Object.assign({},{scene:this._scene,adTypeR:this._adTypeR},e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null};this._outerFinishedCallback(e),this._onFinish?.(e),this._outerHalfwayCallback(e),this._onHalfway?.(e),this._outerCloseCallback(e),this._onAlways?.(e),t({end_type:"finished"})}adErrorLister(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this._onError?.(e),0>=this.novelConfig.remain()&&(this.adDestroy(),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null)}apiAdErrorLister(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}adLoadLister(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e}))}adDestroy(){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy()}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy(),this._resolve=null,this._next=null,this._success=null,this._before=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offClose(this._bindShiftCloseLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offError(this._bindShiftErrorLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return InterstitialAdNovel.instance||(InterstitialAdNovel.instance=new InterstitialAdNovel(e)),InterstitialAdNovel.instance}static getInstance(){if(!InterstitialAdNovel.instance)throw Error("InterstitialAdNovel instance is not init");return InterstitialAdNovel.instance}static new(e){return new InterstitialAdNovel(e)}}class InterstitialAdNovel_RewardAdNovelConfig{frequency={total:0,current:0};constructor(e){this._init(e)}_init(e){this._adTimes(e)}_adTimes(e){this.frequency.total=e?.retry??4}reset(){this.frequency.current=0}updateRetry(){this.frequency.current=this.frequency.current+1}remain(){return this.frequency.total-this.frequency.current}static new(e){return new InterstitialAdNovel_RewardAdNovelConfig(e)}}const src_InterstitialAdNovel=InterstitialAdNovel;class dist_t{constructor(e={}){this.config={prefix:"storage_",expire:null,...e},this.logger=new logger_namespaceObject.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 dist_t(e)}}let dist_r=dist_t;class CountRecorder{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=dist_r.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)}}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 Storage{constructor(e={}){this.config={prefix:"storage_",expire:null,...e},this.logger=new logger_namespaceObject.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 src_Storage=Storage;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 PubSub{constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.off(e,t)}}off(e,t){if(this.events[e]){if(!t){this.events[e]=[];return}this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,...t){this.events[e]&&this.events[e].forEach(r=>{try{r(...t)}catch(t){console.error(`Error in event listener for ${e}:`,t)}})}once(e,t){let r=(...i)=>{t(...i),this.off(e,r)};this.on(e,r)}listenerCount(e){return this.events[e]?this.events[e].length:0}removeAllListeners(){this.events={}}}class AdAnalyticsJS{static instance=null;_logger=null;_initSign="";_needReport=!1;constructor(e){if(AdAnalyticsJS.instance)return AdAnalyticsJS.instance;this._logger=new logger_namespaceObject.Logger({prefix:"AdAnalyticsJS",enabled:!!(e?.log??!0)}),this._initSign=e?.sign??"",this._needReport=e?.needReport??!1,this._commonConfig=e?.commonConfig??null,AdAnalyticsJS.instance=this}initialize(e){return this._needReport?e:void this._logger.warn("needReport is false, do not report")}track(e,t,r){if(!this._needReport)return;if(!e)throw Error("eventName is required");let i=Object.assign({},this.getTrackCommonInfo(),t),s=r?.sign??"track";this._logger.log(`---------${s}----------:`,e,i),tt.reportAnalytics(e,i)}getCommonInfo(){return this._commonConfig??{}}getTrackCommonInfo(){return this._commonConfig??{}}identify(e,t){if(!e&&0!==e)throw Error("identify user_id is required");return this._commonConfig=Object.assign({},this._commonConfig,{__user_id:e},t),this}alias(){return null}pages(){return null}page(e,t){this.track(e,t,{sign:"page"})}cpage(e){return this.page("cpage",e)}placeholder(){return null}static build(e){return AdAnalyticsJS.instance||(AdAnalyticsJS.instance=new AdAnalyticsJS(e)),AdAnalyticsJS.instance}static getInstance(){if(!AdAnalyticsJS.instance)throw Error("AdAnalyticsJS instance is not init");return AdAnalyticsJS.instance}static new(e){return new AdAnalyticsJS(e)}}const src_AdAnalyticsJS=AdAnalyticsJS,packages_0=src_AdExecuteManager;for(var __rspack_i in exports.AdAnalyticsJS=__webpack_exports__.AdAnalyticsJS,exports.AdExecuteManager=__webpack_exports__.AdExecuteManager,exports.CountRecorder=__webpack_exports__.CountRecorder,exports.InterstitialAdDrama=__webpack_exports__.InterstitialAdDrama,exports.InterstitialAdFather=__webpack_exports__.InterstitialAdFather,exports.InterstitialAdNovel=__webpack_exports__.InterstitialAdNovel,exports.Logger=__webpack_exports__.Logger,exports.PubSub=__webpack_exports__.PubSub,exports.RewardAdDrama=__webpack_exports__.RewardAdDrama,exports.RewardAdFather=__webpack_exports__.RewardAdFather,exports.RewardAdNovel=__webpack_exports__.RewardAdNovel,exports.SerializableError=__webpack_exports__.SerializableError,exports.Storage=__webpack_exports__.Storage,exports.default=__webpack_exports__.default,__webpack_exports__)-1===["AdAnalyticsJS","AdExecuteManager","CountRecorder","InterstitialAdDrama","InterstitialAdFather","InterstitialAdNovel","Logger","PubSub","RewardAdDrama","RewardAdFather","RewardAdNovel","SerializableError","Storage","default"].indexOf(__rspack_i)&&(exports[__rspack_i]=__webpack_exports__[__rspack_i]);Object.defineProperty(exports,"__esModule",{value:!0});
|
|
1
|
+
"use strict";const __rslib_import_meta_url__="u"<typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,r)=>{for(var a in r)__webpack_require__.o(r,a)&&!__webpack_require__.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:r[a]})},__webpack_require__.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),__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__,{RewardAdFather:()=>ad_reward_namespaceObject.RewardAdFather,SerializableError:()=>serializable_error_namespaceObject.SerializableError,default:()=>packages_0,InterstitialAdNovel:()=>ad_interstitial_namespaceObject.InterstitialAdNovel,PubSub:()=>event_namespaceObject.PubSub,Storage:()=>storage_namespaceObject.Storage,CountRecorder:()=>count_recorder_namespaceObject.CountRecorder,RewardAdNovel:()=>ad_reward_namespaceObject.RewardAdNovel,AdAnalyticsJS:()=>analytics_namespaceObject.AdAnalyticsJS,InterstitialAdFather:()=>ad_interstitial_namespaceObject.InterstitialAdFather,InterstitialAdDrama:()=>ad_interstitial_namespaceObject.InterstitialAdNovel,AdExecuteManager:()=>core_namespaceObject.AdExecuteManager,Logger:()=>logger_namespaceObject.Logger,RewardAdDrama:()=>ad_reward_namespaceObject.RewardAdNovel});const core_namespaceObject=require("@ad-execute-manager/core"),ad_reward_namespaceObject=require("@ad-execute-manager/ad-reward"),ad_interstitial_namespaceObject=require("@ad-execute-manager/ad-interstitial"),count_recorder_namespaceObject=require("@ad-execute-manager/count-recorder"),serializable_error_namespaceObject=require("@ad-execute-manager/serializable-error"),storage_namespaceObject=require("@ad-execute-manager/storage"),logger_namespaceObject=require("@ad-execute-manager/logger"),event_namespaceObject=require("@ad-execute-manager/event"),analytics_namespaceObject=require("@ad-execute-manager/analytics"),packages_0=core_namespaceObject.AdExecuteManager;for(var __rspack_i in exports.AdAnalyticsJS=__webpack_exports__.AdAnalyticsJS,exports.AdExecuteManager=__webpack_exports__.AdExecuteManager,exports.CountRecorder=__webpack_exports__.CountRecorder,exports.InterstitialAdDrama=__webpack_exports__.InterstitialAdDrama,exports.InterstitialAdFather=__webpack_exports__.InterstitialAdFather,exports.InterstitialAdNovel=__webpack_exports__.InterstitialAdNovel,exports.Logger=__webpack_exports__.Logger,exports.PubSub=__webpack_exports__.PubSub,exports.RewardAdDrama=__webpack_exports__.RewardAdDrama,exports.RewardAdFather=__webpack_exports__.RewardAdFather,exports.RewardAdNovel=__webpack_exports__.RewardAdNovel,exports.SerializableError=__webpack_exports__.SerializableError,exports.Storage=__webpack_exports__.Storage,exports.default=__webpack_exports__.default,__webpack_exports__)-1===["AdAnalyticsJS","AdExecuteManager","CountRecorder","InterstitialAdDrama","InterstitialAdFather","InterstitialAdNovel","Logger","PubSub","RewardAdDrama","RewardAdFather","RewardAdNovel","SerializableError","Storage","default"].indexOf(__rspack_i)&&(exports[__rspack_i]=__webpack_exports__[__rspack_i]);Object.defineProperty(exports,"__esModule",{value:!0});
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
export default AdExecuteManager;
|
|
2
|
-
import AdExecuteManager from '
|
|
3
|
-
import RewardAdFather from '
|
|
4
|
-
import { SerializableError } from '
|
|
5
|
-
import { Logger } from '
|
|
6
|
-
import Storage from '
|
|
7
|
-
import { CountRecorder } from '
|
|
8
|
-
import AdAnalyticsJS from '
|
|
9
|
-
import RewardAdNovel from '
|
|
10
|
-
import InterstitialAdFather from '
|
|
11
|
-
import InterstitialAdNovel from '
|
|
12
|
-
import PubSub from '
|
|
2
|
+
import { AdExecuteManager } from '@ad-execute-manager/core';
|
|
3
|
+
import { RewardAdFather } from '@ad-execute-manager/ad-reward';
|
|
4
|
+
import { SerializableError } from '@ad-execute-manager/serializable-error';
|
|
5
|
+
import { Logger } from '@ad-execute-manager/logger';
|
|
6
|
+
import { Storage } from '@ad-execute-manager/storage';
|
|
7
|
+
import { CountRecorder } from '@ad-execute-manager/count-recorder';
|
|
8
|
+
import { AdAnalyticsJS } from '@ad-execute-manager/analytics';
|
|
9
|
+
import { RewardAdNovel } from '@ad-execute-manager/ad-reward';
|
|
10
|
+
import { InterstitialAdFather } from '@ad-execute-manager/ad-interstitial';
|
|
11
|
+
import { InterstitialAdNovel } from '@ad-execute-manager/ad-interstitial';
|
|
12
|
+
import { PubSub } from '@ad-execute-manager/event';
|
|
13
13
|
export { AdExecuteManager, RewardAdFather, SerializableError, Logger, Storage, CountRecorder, AdAnalyticsJS, RewardAdNovel, RewardAdNovel as RewardAdDrama, InterstitialAdFather, InterstitialAdNovel, InterstitialAdNovel as InterstitialAdDrama, PubSub };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{Logger as e}from"@ad-execute-manager/logger";import{AdExecuteManager as t}from"@ad-execute-manager/core";class r{static _instance=null;_taskStack=[];_currentBatchTasks=[];_isRunning=!1;_currentTask=null;_isForeground=!0;_appShowListener=null;_appHideListener=null;_enableVisibilityListener=!1;_maxRetryCount=1;_retryQueue=[];_errorRetryStrategy={timeout:!0,background:!0};constructor(t){this.logger=new e({prefix:"AdExecuteManager",enabled:!!t?.log}),t?.errorRetryStrategy&&(this._errorRetryStrategy=Object.assign({},this._errorRetryStrategy,t?.errorRetryStrategy)),this._enableVisibilityListener=t?.enableVisibilityListener,this._maxRetryCount=t?.maxRetryCount??1,this._enableVisibilityListener&&this._initVisibilityListener()}initialize(e){return this}static getInstance(e){return r._instance||(r._instance=new r(e)),r._instance}static build(e){return r._instance||(r._instance=new r(e)),r._instance}static new(e){return new r(e)}static getSafeInstance(){return r._instance?r._instance:(this.logger.error("AdExecuteManager实例不存在"),null)}_initVisibilityListener(){!("u"<typeof tt)&&tt.onAppShow&&tt.onAppHide?(this._appShowListener=()=>{this._isForeground=!0,this._handleAppShow()},this._appHideListener=()=>{this._isForeground=!1,this._handleAppHide()},tt.onAppShow(this._appShowListener),tt.onAppHide(this._appHideListener),this.logger.info("前后台监听器已初始化")):this.logger.warn("tt API不可用,无法监听前后台状态")}_handleAppHide(){if(this._isRunning&&this._currentBatchTasks.length>0){let e=this._currentBatchTasks.filter(e=>e.id!==this._currentTask?.id&&!e._isResolved&&!e._isRejected);e.length>0&&(this.logger.info(`将 ${e.length} 个未执行的任务放回任务栈,任务ID: ${e.map(e=>e.id).join(",")}`),this._taskStack=[...e,...this._taskStack],this._currentBatchTasks=this._currentBatchTasks.filter(t=>!e.some(e=>e.id===t.id)))}}_handleAppShow(){this._retryQueue.length>0&&(this.logger.info(`应用进入前台:优先执行重试队列,任务数: ${this._retryQueue.length}, 任务ID: ${this._retryQueue.map(e=>e.id).join(",")}`),this._taskStack=[...this._retryQueue,...this._taskStack],this._retryQueue=[]),this._taskStack.length>0&&!this._isRunning&&(this.logger.info(`应用进入前台:恢复待执行任务数: ${this._taskStack.length}, 任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._compose())}destroyVisibilityListener(){this._appShowListener&&"u">typeof tt&&tt.offAppShow&&(tt.offAppShow(this._appShowListener),this._appShowListener=null),this._appHideListener&&"u">typeof tt&&tt.offAppHide&&(tt.offAppHide(this._appHideListener),this._appHideListener=null),this.logger.info("前后台监听器已销毁")}enableVisibilityListener(){this._enableVisibilityListener||(this._enableVisibilityListener=!0,this._initVisibilityListener()),this.logger.info("前后台监听器已启用")}disableVisibilityListener(){this._enableVisibilityListener&&(this._enableVisibilityListener=!1,this.destroyVisibilityListener()),this.logger.info("前后台监听器已禁用")}isVisibilityListenerEnabled(){return this._enableVisibilityListener}addTask(e,t){return e&&"function"==typeof e.ad?new Promise((r,i)=>{let s={adInstance:e,options:t.options??{},callbackCollection:t.collection??{},resolve:r,reject:i,id:`ad_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,_isResolved:!1,_isRejected:!1,_retryCount:0,_retryMsg:"ok"};this._taskStack.push(s),this._isRunning||this._compose()}):(this.logger.error("无效的广告实例 请正确实现.ad方法"),Promise.reject(Error("无效的广告实例")))}_compose(){if(0===this._taskStack.length){this._isRunning=!1,this._currentTask=null;return}if(!this._isForeground){this.logger.info(`应用处于后台,暂停任务执行,任务ID: ${this._taskStack.map(e=>e.id).join(",")}`),this._isRunning=!1;return}this._isRunning=!0;let e=[...this._taskStack];this._taskStack=[],this._currentBatchTasks=e;let t=e.map(e=>async(t,r)=>{let{adInstance:i,options:s,callbackCollection:n,resolve:o,id:l,_retryCount:a,_retryMsg:h}=e,d={count:a,retry:a>0,message:h};if(e._isResolved||e._isRejected)return void await r(t);this._currentTask=e;try{let a=async e=>{await r(Object.assign({},t,e))},h=await i.initialize(s).ad({options:s,collection:n,recovered:d},a),c=Object.assign({id:l,recovered:d},h);if(this.logger.info(`任务执行成功,成功信息:${JSON.stringify(c)}`),function({apiError:e,configuredAdTimeout:t,errorRetryStrategy:r}){return!!(r?.timeout&&e?.errMsg&&"string"==typeof e.errMsg&&e.errMsg.startsWith("ad_show_timeout: normal")&&e?.timeout==t)||!!(r?.background&&e?.errMsg&&"string"==typeof e.errMsg&&(e.errMsg.startsWith("app in background is not support show ad")||e.errMsg.startsWith("other controller is presented")))}({apiError:c?.apiError,configuredAdTimeout:i._adTimeoutTime,errorRetryStrategy:this._errorRetryStrategy})&&!this._isForeground&&e._retryCount<this._maxRetryCount){e._retryCount++,e._retryMsg=c?.apiError?.errMsg||"unknown";let t=`任务 ${l} 在后台失败,加入重试队列 (即将第 ${e._retryCount} 次重试, 最大重试次数 ${this._maxRetryCount}, 重试原因: ${e._retryMsg})`;this.logger.warn(t),c.recovered.retry=!0,c.recovered.count=e._retryCount,c.recovered.message=e._retryMsg,e._isResolved=!1,e._isRejected=!1,this._retryQueue.push(e)}else e._isResolved=!0;o(c),i?.record(c)}catch(n){let s=Object.assign({id:l,apiError:n,recovered:d});this.logger.error(`任务执行失败, 继续下一个任务,错误信息:${JSON.stringify(s)}`),e._isRejected=!0;try{i?.clear()}catch(e){this.logger.error("clear error: ",JSON.stringify(Object.assign({id:l,apiError:e})))}o(s),i?.record(s),await r(t)}}),r={roundTasks:t.length};t.map(e=>(t,r)=>async i=>await e(Object.assign({},t,i),r)).reduce((e,t)=>(r,i)=>e(r,t(r,i)))(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,o=0===this._currentBatchTasks.length||this._currentBatchTasks.every(e=>e._isResolved||e._isRejected),l=0===this._retryQueue.length;i&&s&&n&&o&&l?(t&&clearTimeout(t),e()):t=setTimeout(r,500)};r()})}}let i=r;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 n{static args=null;_logger=null;_adTimeoutTime=8e3;_initSign="";_preserveOnEnd=!1;_rewardAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302];__bindAdErrorForeverHandler=this.__adErrorForeverHandler.bind(this);constructor(t){this._logger=new e({prefix:"RewardAdFather",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._preserveOnEnd=t?.preserveOnEnd??!1}initialize(e,t){if(this._rewardAd)return this._logger.warn("rewardAd has been initialized"),t?.(this._rewardAd),this;let r=Object.assign({},n.args,this._adConfig,e);if(!r.adUnitId)throw this._logger.error("reward args The adUnitId is required",r),new s("[RewardAdFather] reward args The adUnitId is required",{errMsg:"The adUnitId is required",errorCode:100002});let i=tt.createRewardedVideoAd(r);return this._logger.info("bindAdErrorForeverHandler at initialized:",e?.foreverErrorBind),e?.foreverErrorBind&&(i?.offError(this.__bindAdErrorForeverHandler),i?.onError(this.__bindAdErrorForeverHandler)),this._rewardAd=i,this.__ad__=i,t?.(this._rewardAd),this}initialized(){return!!this._rewardAd}__adErrorForeverHandler(e){this.adErrorForeverHandler(e)}adErrorForeverHandler(e){return null}async ad(e,t=null){throw Error("子类必须实现ad方法")}async addExecuteManager(e){let t=Object.assign({},this._adConfig,e?.options??{});return n.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(t){t?.adUnitId||new e({prefix:"RewardAdFather",enable:!0}).error("RewardParams.adUnitId is required"),n.args=t}static async executeWithManager(r,i){return r&&r instanceof n?t.getInstance().addTask(r,i):(new e({prefix:"RewardAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let o=n,l=Object.entries({9999:"inner_default_other"}).reduce((e,[t,r])=>(e[r]=Number(t),e),{}),a={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2};Object.entries(a).reduce((e,[t,r])=>(e[r]=t,e),{});class h extends o{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=l.inner_default_other;_adTypeR=a.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(t){super(t),this._logger=new e({prefix:"RewardAdNovel",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._needEndOnTimeout=t?.needEndOnTimeout??!0,this._onHalfway=t?.collection?.onHalfway??null,this._onShow=t?.collection?.onShow??null,this._onFinish=t?.collection?.onFinish??null,this._onAlways=t?.collection?.onAlways??null,this._onError=t?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=d.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(e){return null}_setAdTimeout(e){if(this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let r="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,msg:r,errorCode:1e5,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:r,errorCode:1e5}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout){let t=e?.timeout??this._adTimeoutTime;this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case,",`scene: ${e?.scene},timeout: ${t}`),this._adShowFailureAnalytics({scene:e?.scene,msg:"ad_show_timeout: normal",errorCode:1e5,result:0}),this._adTimeoutBeforeEnd({scene:e?.scene,timeout:t}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, reward ad, timeout: ${t}`,errorCode:1e5,timeout:t}},nextValue:null})},t)}}_adTimeoutBeforeEnd(e){return e}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearInterval(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}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._recovered=e?.recovered,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},recovered:e.recovered},t)})}_adInner(e,t=null){let r=e?.collection?.resolve,i=e?.options?.scene??this._scene??l.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,a=e?.recovered??this._recovered,h=e=>{this._clearAdTimeout(),this.adDestroy(),r?.(Object.assign({scene:i,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:i},e?.nextValue))},d=()=>{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:h,timeout:e?.options?.timeout}),this._adPreludeInterval({scene:i,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:i}),this._success=n,this._adShowSuccessAnalytics({scene:i,result:1,recovered:a}),this._onInnerAdShowSuccess({scene:i,result:1,recovered:a})}).catch(e=>{var t,r;(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:i,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),t=this._ttErrorMsgs,(r=e?.errMsg)&&t.some(e=>RegExp(e,"i").test(r))||this._ttErrorCodes.includes(e?.errorCode))?h({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?h({scene:i,resolvedValue:{apiError:{errMsg:`[RewardAdNovel]: no remain, remain: ${this.novelConfig.remain()}, retry: ${this.novelConfig.frequency.total},
|
|
2
|
-
tt: {errMsg: ${e?.errMsg}, errorCode: ${e?.errorCode}}`,errorCode:1e5}},nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:i,result:1,frequency:this.novelConfig.frequency}),d()}).catch(e=>{this._adLoadFailureAnalytics({scene:i,msg:e?.errMsg,result:0}),h({scene:i,resolvedValue:{apiError:e},nextValue:null})}))})};d()}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=Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR,end_type:e.isEnded?"finished":"halfway"}),r=e=>{this.adDestroy(),this._resolve?.(Object.assign({},t,e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null},i=e=>{let r=Object.assign({},t,e);r?.isEnded?(this._outerFinishedCallback(r),this._onFinish?.(r)):(this._outerHalfwayCallback(r),this._onHalfway?.(r)),this._outerCloseCallback(r),this._onAlways?.(r)};this.adCloseLister(t,{conn:i,end:r})}adCloseLister(e,t){t?.conn?.(e),t?.end?.(e)}__adErrorLister__(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adErrorLister(e),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}adErrorLister(e){return e}__apiAdErrorLister__(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.apiAdErrorLister(e),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}apiAdErrorLister(e){return e}__adLoadLister__(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e})),this.adLoadLister(e)}adLoadLister(e){return e}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._recovered=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._recovered=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._recovered=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._recovered=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 h.instance||(h.instance=new h(e)),h.instance}static getInstance(){if(!h.instance)throw Error("RewardAdNovel instance is not init");return h.instance}static new(e){return new h(e)}}class d{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 d(e)}}let c=h;class _ 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 u{static args=null;_logger=null;_initSign="";_preserveOnEnd=!1;_interstitialAd=null;__ad__=null;_ttErrorMsgs=["The adUnitId is closed","The adUnitId is prohibit","The adUnitId is invalid","The adUnitId is required","The adUnitId is empty","feature is not supported in app"];_ttErrorCodes=[139902,123302,140502];constructor(t){this._logger=new e({prefix:"InterstitialAdFather",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._preserveOnEnd=t?.preserveOnEnd??!1}initialize(e,t){if(this._interstitialAd)return this._logger.warn("interstitialAd has been initialized"),t?.(this._interstitialAd),this;let r=Object.assign({},u.args,this._adConfig,e);if(!r.adUnitId)throw this._logger.error("interstitialAd args The adUnitId is required",r),new _("[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 u.executeWithManager(this,Object.assign({},e,{options:t}))}destroy(){this._interstitialAd&&!this._preserveOnEnd&&(this._interstitialAd.destroy(),this._interstitialAd=null)}clear(){throw Error("子类必须实现clear方法")}record(e){return this}onClose(e){this._interstitialAd&&this._interstitialAd.onClose(e)}offClose(e){this._interstitialAd&&this._interstitialAd.offClose(e)}show(){return this._interstitialAd?this._interstitialAd.show():Promise.reject({errMsg:"[InterstitialAdFather] can not show,interstitialAd is null",errorCode:120001})}load(){return this._interstitialAd?this._interstitialAd.load():Promise.reject({errMsg:"[InterstitialAdFather] can not load,interstitialAd is null",errorCode:120002})}onError(e){this._interstitialAd&&this._interstitialAd.onError(e)}offError(e){this._interstitialAd&&this._interstitialAd.offError(e)}onLoad(e){this._interstitialAd&&this._interstitialAd.onLoad(e)}offLoad(e){this._interstitialAd&&this._interstitialAd.offLoad(e)}placeholder(){return null}static buildArgs(t){t?.adUnitId||new e({prefix:"InterstitialAdFather",enable:!0}).error("interstitialAdParams.adUnitId is required"),u.args=t}static async executeWithManager(r,i){return r&&r instanceof u?t.getInstance().addTask(r,i):(new e({prefix:"InterstitialAdFather",enable:!0}).error("executeWithManager - 无效的广告实例"),Promise.reject(Error("无效的广告实例")))}}let g=u,f=Object.entries({9999:"inner_default_other"}).reduce((e,[t,r])=>(e[r]=Number(t),e),{}),m={AD_TYPE_REWARD:1,AD_TYPE_INTERSTITIAL:2};Object.entries(m).reduce((e,[t,r])=>(e[r]=t,e),{});class y extends g{_onHalfway=null;_onShow=null;_onFinish=null;_onAlways=null;_onError=null;_logger=null;_initSign="";_alwaysCallback=null;_halfwayCallback=null;_finishedCallback=null;_resolve=null;_next=null;_scene=f.inner_default_other;_adTypeR=m.AD_TYPE_INTERSTITIAL;_adTimeout=null;_adTimeoutTime=8e3;_adBeforeShowTimer=null;_adBeforeShowTime=300;_adSpeedCloseTimer=null;_adSpeedCloseTime=5e3;_needEndOnTimeout=!0;_needSpeedEndOnTimeout=!1;bindAdCloseLister=this.adCloseLister.bind(this);bindAdErrorLister=this.adErrorLister.bind(this);bindAdLoadLister=this.adLoadLister.bind(this);bindApiAdErrorLister=this.apiAdErrorLister.bind(this);_bindShiftCloseLister=this._shiftCloseLister.bind(this);_bindShiftErrorLister=this._shiftErrorLister.bind(this);constructor(t){super(t),this._logger=new e({prefix:"InterstitialAdNovel",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._adConfig=t?.adConfig??{},this._needEndOnTimeout=t?.needEndOnTimeout??!0,this._onHalfway=t?.collection?.onHalfway??null,this._onShow=t?.collection?.onShow??null,this._onFinish=t?.collection?.onFinish??null,this._onAlways=t?.collection?.onAlways??null,this._onError=t?.collection?.onError??null}initialize(e,t){return super.initialize(e,t),this._initAdLister(),this._initNovelConfig(e),this}_initAdLister(){this.onClose(this.bindAdCloseLister),this.onError(this.bindAdErrorLister),this.onLoad(this.bindAdLoadLister),tt.onError(this.bindApiAdErrorLister)}_initNovelConfig(e){this.novelConfig=p.new({retry:e?.retry})}_onInnerExecuteBefore(){return null}_onInnerAdShowSuccess(){return null}_setAdTimeout(e){this._needSpeedEndOnTimeout&&(this._adSpeedCloseTimer=setTimeout(()=>{if("ios"==tt.getSystemInfoSync().platform){let t=()=>{tt.offAppShow(t),this._logger.warn("ad_show_timeout: ios platform close ad onAppShow, handling fallback ad case, scene:",e?.scene);let r="ad_show_timeout: ios platform close ad onAppShow";this._adShowFailureAnalytics({scene:e?.scene,msg:r,errorCode:100001,result:0}),this._adTimeout&&clearTimeout(this._adTimeout),e?.end({resolvedValue:{apiError:{errMsg:r,errorCode:100001}},nextValue:null})};tt.onAppShow(t)}clearTimeout(this._adSpeedCloseTimer)},this._adSpeedCloseTime)),this._needEndOnTimeout&&(this._adTimeout=setTimeout(()=>{this._logger.warn("Ad show timeout, handling fallback ad case, scene:",e?.scene),this._adShowFailureAnalytics({scene:e?.scene,msg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001,result:0}),e?.end({resolvedValue:{apiError:{errMsg:`ad_show_timeout: normal, interstitial ad, timeout: ${this._adTimeoutTime}`,errorCode:100001}},nextValue:null})},this._adTimeoutTime))}_adPreludeInterval(e){e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()}),this._adBeforeShowTimer=setInterval(()=>{e.prelude?.({scene:e?.scene,frequency:this._adBeforeShowTime,time:new Date().getTime()})},this._adBeforeShowTime)}_clearAdTimeout(){this._adTimeout&&(clearTimeout(this._adTimeout),this._adTimeout=null),this._adBeforeShowTimer&&(clearTimeout(this._adBeforeShowTimer),this._adBeforeShowTimer=null),this._adSpeedCloseTimer&&(clearTimeout(this._adSpeedCloseTimer),this._adSpeedCloseTimer=null)}_adShowBeforeAnalytics(e){return null}_adShowSuccessAnalytics(e){return null}_adShowFailureAnalytics(e){return null}_adLoadSuccessAnalytics(e){return null}_adLoadFailureAnalytics(e){return null}_adCloseSuccessAnalytics(e){return null}get rewardAd(){return this._rewardAd}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??f.inner_default_other,s=e?.collection?.before,n=e?.collection?.success,o=e?.collection?.prelude,l=e=>{this._clearAdTimeout(),this.adDestroy(),r?.(Object.assign({scene:i,adTypeR:this._adTypeR},e?.resolvedValue)),t?.(Object.assign({scene:i},e?.nextValue))},a=()=>{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:l}),this._adPreludeInterval({scene:i,prelude:o}),this.adShow().then(()=>{this._clearAdTimeout(),n?.({scene:i}),this._success=n,this._adShowSuccessAnalytics({scene:i,result:1}),this._onInnerAdShowSuccess()}).catch(e=>{var t,r;(this._clearAdTimeout(),this._adShowFailureAnalytics({scene:i,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),t=this._ttErrorMsgs,(r=e?.errMsg)&&t.some(e=>RegExp(e,"i").test(r))||this._ttErrorCodes.includes(e?.errorCode))?l({scene:i,resolvedValue:{apiError:e},nextValue:null}):0>=this.novelConfig.remain()?l({scene:i,resolvedValue:null,nextValue:null}):(this.novelConfig.updateRetry(),this.adLoad().then(()=>{this._adLoadSuccessAnalytics({scene:i,result:1}),a()}).catch(e=>{this._adLoadFailureAnalytics({scene:i,msg:e?.errMsg,result:0}),l({scene:i,resolvedValue:{apiError:e},nextValue:null})}))})};a()}adLoad(){return this.load()}adShow(){return this.show()}_outerCloseCallback(e){this._alwaysCallback?.(e)}_outerHalfwayCallback(e){this._halfwayCallback?.(e)}_outerFinishedCallback(e){this._finishedCallback?.(e)}adCloseLister(){this._clearAdTimeout(),this._adCloseSuccessAnalytics({scene:this._scene,ad_is_completed:1});let e={scene:this._scene},t=e=>{this.adDestroy(),this._resolve?.(Object.assign({},{scene:this._scene,adTypeR:this._adTypeR},e)),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null};this._outerFinishedCallback(e),this._onFinish?.(e),this._outerHalfwayCallback(e),this._onHalfway?.(e),this._outerCloseCallback(e),this._onAlways?.(e),t({end_type:"finished"})}adErrorLister(e){this._clearAdTimeout(),this._logger.error("adErrorLister",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this._onError?.(e),0>=this.novelConfig.remain()&&(this.adDestroy(),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null)}apiAdErrorLister(e){this._clearAdTimeout(),this._logger.error("API apiAdErrorLister:",JSON.stringify(e)),this._adShowFailureAnalytics({scene:this._scene,msg:e?.errMsg,errorCode:e?.errorCode,result:0}),this.adDestroy(),this._onError?.(e),this._resolve?.({apiError:e,scene:this._scene,adTypeR:this._adTypeR}),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}adLoadLister(e){this._adLoadSuccessAnalytics({scene:this._scene,result:1,msg:e?.errMsg}),this._logger.info("adLoadLister:",JSON.stringify({scene:this._scene,info:e}))}adDestroy(){this.offClose(this.bindAdCloseLister),this.offError(this.bindAdErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy()}clear(){this._clearAdTimeout(),this.offClose(this.bindAdCloseLister),this.offClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.destroy(),this._resolve=null,this._next=null,this._success=null,this._before=null}_shiftCloseLister(e){this._clearAdTimeout(),this.offError(this._bindShiftErrorLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offClose(this._bindShiftCloseLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}_shiftErrorLister(e){this._clearAdTimeout(),this.offClose(this._bindShiftCloseLister),this.offLoad(this.bindAdLoadLister),tt.offError(this.bindApiAdErrorLister),this._onHalfway=null,this._onFinish=null,this._onAlways=null,this._onShow=null,this._onError=null,this._alwaysCallback=null,this._halfwayCallback=null,this._finishedCallback=null,this.offError(this._bindShiftErrorLister),this.destroy(),this._resolve?.(Object.assign({},e,{scene:this._scene,adTypeR:this._adTypeR})),this._resolve=null,this._next?.(),this._next=null,this._success=null,this._before=null}shift(){this.offClose(this.bindAdCloseLister),this.onClose(this._bindShiftCloseLister),this.offError(this.bindAdErrorLister),this.onError(this._bindShiftErrorLister)}static build(e){return y.instance||(y.instance=new y(e)),y.instance}static getInstance(){if(!y.instance)throw Error("InterstitialAdNovel instance is not init");return y.instance}static new(e){return new y(e)}}class p{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 p(e)}}let w=y;class b{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,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 b(e)}}class A{_total=0;_local_sign="";_expire="today";constructor(e){if(this.storage=b.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 A(e)}}class C extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.stack=Error(e).stack,this.errMsg=t.errMsg,this.errorCode=t.errorCode,Object.defineProperty(this,"message",{enumerable:!0}),Object.defineProperty(this,"name",{enumerable:!0}),Object.defineProperty(this,"stack",{enumerable:!0}),Object.defineProperty(this,"errMsg",{enumerable:!0}),Object.defineProperty(this,"errorCode",{enumerable:!0})}toJSON(){return{name:this.name,message:this.message,stack:this.stack,errMsg:this.errMsg,errorCode:this.errorCode}}}class S{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,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 S(e)}}let T=S;class E{constructor(e={}){let{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 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(r=>{try{r(...t)}catch(t){console.error(`Error in event listener for ${e}:`,t)}})}once(e,t){let r=(...i)=>{t(...i),this.off(e,r)};this.on(e,r)}listenerCount(e){return this.events[e]?this.events[e].length:0}removeAllListeners(){this.events={}}}class k{static instance=null;_logger=null;_initSign="";_needReport=!1;constructor(t){if(k.instance)return k.instance;this._logger=new e({prefix:"AdAnalyticsJS",enabled:!!(t?.log??!0)}),this._initSign=t?.sign??"",this._needReport=t?.needReport??!1,this._commonConfig=t?.commonConfig??null,k.instance=this}initialize(e){return this._needReport?e:void this._logger.warn("needReport is false, do not report")}track(e,t,r){if(!this._needReport)return;if(!e)throw Error("eventName is required");let i=Object.assign({},this.getTrackCommonInfo(),t),s=r?.sign??"track";this._logger.log(`---------${s}----------:`,e,i),tt.reportAnalytics(e,i)}getCommonInfo(){return this._commonConfig??{}}getTrackCommonInfo(){return this._commonConfig??{}}identify(e,t){if(!e&&0!==e)throw Error("identify user_id is required");return this._commonConfig=Object.assign({},this._commonConfig,{__user_id:e},t),this}alias(){return null}pages(){return null}page(e,t){this.track(e,t,{sign:"page"})}cpage(e){return this.page("cpage",e)}placeholder(){return null}static build(e){return k.instance||(k.instance=new k(e)),k.instance}static getInstance(){if(!k.instance)throw Error("AdAnalyticsJS instance is not init");return k.instance}static new(e){return new k(e)}}let v=k,I=i;export{v as AdAnalyticsJS,i as AdExecuteManager,A as CountRecorder,w as InterstitialAdDrama,g as InterstitialAdFather,w as InterstitialAdNovel,E as Logger,L as PubSub,c as RewardAdDrama,o as RewardAdFather,c as RewardAdNovel,C as SerializableError,T as Storage,I as default};
|
|
1
|
+
import{AdExecuteManager as e}from"@ad-execute-manager/core";import{RewardAdFather as a,RewardAdNovel as r}from"@ad-execute-manager/ad-reward";import{InterstitialAdFather as t,InterstitialAdNovel as o}from"@ad-execute-manager/ad-interstitial";import{CountRecorder as d}from"@ad-execute-manager/count-recorder";import{SerializableError as m}from"@ad-execute-manager/serializable-error";import{Storage as i}from"@ad-execute-manager/storage";import{Logger as n}from"@ad-execute-manager/logger";import{PubSub as l}from"@ad-execute-manager/event";import{AdAnalyticsJS as c}from"@ad-execute-manager/analytics";let g=e;export{c as AdAnalyticsJS,e as AdExecuteManager,d as CountRecorder,o as InterstitialAdDrama,t as InterstitialAdFather,o as InterstitialAdNovel,n as Logger,l as PubSub,r as RewardAdDrama,a as RewardAdFather,r as RewardAdNovel,m as SerializableError,i as Storage,g as default};
|
|
@@ -80,14 +80,10 @@ export type CallbackCollection = {
|
|
|
80
80
|
* 半途退出广告外部回调
|
|
81
81
|
*/
|
|
82
82
|
halfway?: (ctx?: IExeCallbackArgs) => void;
|
|
83
|
-
/**
|
|
84
|
-
* 完成广告外部回调 不管看不看完
|
|
85
|
-
*/
|
|
86
|
-
complete?: (ctx?: IExeCallbackArgs) => void;
|
|
87
83
|
/**
|
|
88
84
|
* 取消广告外部回调
|
|
89
85
|
*/
|
|
90
|
-
|
|
86
|
+
cancel?: (ctx?: IExeCallbackArgs) => void;
|
|
91
87
|
/**
|
|
92
88
|
* 展示广告外部回调
|
|
93
89
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@singcl/ad-execute-manager",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.6",
|
|
4
4
|
"description": "A powerful and flexible ad execution management library for handling reward-based ads, interstitial ads, and other advertising formats in JavaScript applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -66,6 +66,13 @@
|
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
68
|
"@ad-execute-manager/core": "^2.0.2",
|
|
69
|
-
"@ad-execute-manager/logger": "^2.0.2"
|
|
69
|
+
"@ad-execute-manager/logger": "^2.0.2",
|
|
70
|
+
"@ad-execute-manager/ad-reward": "^2.0.2",
|
|
71
|
+
"@ad-execute-manager/ad-interstitial": "^2.0.2",
|
|
72
|
+
"@ad-execute-manager/count-recorder": "^2.0.2",
|
|
73
|
+
"@ad-execute-manager/serializable-error": "^2.0.2",
|
|
74
|
+
"@ad-execute-manager/storage": "^2.0.2",
|
|
75
|
+
"@ad-execute-manager/event": "^2.0.2",
|
|
76
|
+
"@ad-execute-manager/analytics": "^2.0.2"
|
|
70
77
|
}
|
|
71
78
|
}
|
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
export type IRewordAdConfig = {
|
|
2
|
-
/**
|
|
3
|
-
* 激励视频广告id - 必填
|
|
4
|
-
*/
|
|
5
|
-
adUnitId: string;
|
|
6
|
-
/**
|
|
7
|
-
* 是否开启进度提醒。开启时广告文案为「再看 n 个xxx」,关闭时为「再看 1 个xxx」。其中 n 表示用户当前还需额外观看广告的次数
|
|
8
|
-
*/
|
|
9
|
-
progressTip?: boolean | undefined;
|
|
10
|
-
/**
|
|
11
|
-
* - 再得广告的奖励文案,用户每看完一个广告都会展示,multiton 为 true 时必填。
|
|
12
|
-
* - 文案完整内容为「再看 1 个xxx」,其中 xxx 是 multitonRewardMsg 配置的文案内容,最大长度为 7,
|
|
13
|
-
* - 文案内容根据 multitonRewardMsg 的配置按顺序展示。若 multitonRewardMsg 长度小于 multitonRewardTimes ,
|
|
14
|
-
* - 则后续的激励再得广告文案取 multitonRewardMsg 数组最后一个。
|
|
15
|
-
*/
|
|
16
|
-
multitonRewardMsg?: Array<string> | undefined;
|
|
17
|
-
/**
|
|
18
|
-
* 是否开启激励再得广告
|
|
19
|
-
*/
|
|
20
|
-
multiton?: boolean | undefined;
|
|
21
|
-
/**
|
|
22
|
-
* 额外观看广告的次数,合法的数据范围为 1~4,multiton 为 true 时必填
|
|
23
|
-
*/
|
|
24
|
-
multitonRewardTimes?: number | undefined;
|
|
25
|
-
/**
|
|
26
|
-
* 场景值 - 自用参数,非tt API要求的参数
|
|
27
|
-
*/
|
|
28
|
-
scene?: number | undefined;
|
|
29
|
-
/**
|
|
30
|
-
* 广告超时时间 单位ms - 自用参数,非tt API要求的参数
|
|
31
|
-
*/
|
|
32
|
-
timeout?: number | undefined;
|
|
33
|
-
/**
|
|
34
|
-
* 重试次数 - 自用参数 ,非tt API要求的参数
|
|
35
|
-
*/
|
|
36
|
-
retry: number;
|
|
37
|
-
/**
|
|
38
|
-
* 是否绑定永远的错误事件 - 自用参数,非tt API要求的参数
|
|
39
|
-
*/
|
|
40
|
-
foreverErrorBind?: boolean | undefined;
|
|
41
|
-
};
|
|
42
|
-
export type InterstitialAdConfig = {
|
|
43
|
-
/**
|
|
44
|
-
* 单个广告单元的 id。可从「开放平台控制台-进入对应小程序-运营-商业化变现-广告管理」中获取 - 必填
|
|
45
|
-
*/
|
|
46
|
-
adUnitId: string;
|
|
47
|
-
/**
|
|
48
|
-
* 场景值 - 自用参数
|
|
49
|
-
*/
|
|
50
|
-
scene?: number | undefined;
|
|
51
|
-
};
|
|
52
|
-
export type IExeCallbackArgs = {
|
|
53
|
-
/**
|
|
54
|
-
* 广告执行场景
|
|
55
|
-
*/
|
|
56
|
-
scene: number;
|
|
57
|
-
/**
|
|
58
|
-
* 是否看完
|
|
59
|
-
*/
|
|
60
|
-
isEnded: boolean;
|
|
61
|
-
/**
|
|
62
|
-
* 完整观看次数
|
|
63
|
-
*/
|
|
64
|
-
count: number;
|
|
65
|
-
/**
|
|
66
|
-
* 剩余观看次数
|
|
67
|
-
*/
|
|
68
|
-
remain?: number;
|
|
69
|
-
};
|
|
70
|
-
export type CallbackCollection = {
|
|
71
|
-
/**
|
|
72
|
-
* 每次外部回调
|
|
73
|
-
*/
|
|
74
|
-
always?: (ctx?: IExeCallbackArgs) => void;
|
|
75
|
-
/**
|
|
76
|
-
* 完整看完广告外部回调 不管一个还是几个
|
|
77
|
-
*/
|
|
78
|
-
finished?: (ctx?: IExeCallbackArgs) => void;
|
|
79
|
-
/**
|
|
80
|
-
* 半途退出广告外部回调
|
|
81
|
-
*/
|
|
82
|
-
halfway?: (ctx?: IExeCallbackArgs) => void;
|
|
83
|
-
/**
|
|
84
|
-
* 完成广告外部回调 不管看不看完
|
|
85
|
-
*/
|
|
86
|
-
complete?: (ctx?: IExeCallbackArgs) => void;
|
|
87
|
-
/**
|
|
88
|
-
* 取消广告外部回调
|
|
89
|
-
*/
|
|
90
|
-
onCancel?: (ctx?: IExeCallbackArgs) => void;
|
|
91
|
-
/**
|
|
92
|
-
* 展示广告外部回调
|
|
93
|
-
*/
|
|
94
|
-
before?: (ctx?: IExeCallbackArgs) => void;
|
|
95
|
-
/**
|
|
96
|
-
* 展示广告成功外部回调
|
|
97
|
-
*/
|
|
98
|
-
success?: (ctx?: IExeCallbackArgs) => void;
|
|
99
|
-
/**
|
|
100
|
-
* 计时回调
|
|
101
|
-
*/
|
|
102
|
-
prelude?: (ctx?: unknown) => void;
|
|
103
|
-
};
|
|
104
|
-
export type RecoveredInfo = {
|
|
105
|
-
/**
|
|
106
|
-
* 恢复重试次数
|
|
107
|
-
*/
|
|
108
|
-
count: number;
|
|
109
|
-
/**
|
|
110
|
-
* 是否恢复重试
|
|
111
|
-
*/
|
|
112
|
-
retry: boolean;
|
|
113
|
-
/**
|
|
114
|
-
* 恢复重试原因
|
|
115
|
-
*/
|
|
116
|
-
message: string;
|
|
117
|
-
};
|
|
118
|
-
export type ICallbackArgs = {
|
|
119
|
-
/**
|
|
120
|
-
* 广告执行场景
|
|
121
|
-
*/
|
|
122
|
-
scene: number;
|
|
123
|
-
/**
|
|
124
|
-
* 是否看完
|
|
125
|
-
*/
|
|
126
|
-
isEnded: boolean;
|
|
127
|
-
/**
|
|
128
|
-
* 完整观看次数
|
|
129
|
-
*/
|
|
130
|
-
count: number;
|
|
131
|
-
/**
|
|
132
|
-
* 剩余观看次数
|
|
133
|
-
*/
|
|
134
|
-
remain?: number;
|
|
135
|
-
/**
|
|
136
|
-
* 执行下一个任务的回调函数,手动调用以继续执行流程[end]
|
|
137
|
-
*/
|
|
138
|
-
end?: () => void;
|
|
139
|
-
/**
|
|
140
|
-
* 执行下一个任务的回调函数, 手动调用以继续执行流程[circle]
|
|
141
|
-
*/
|
|
142
|
-
circle?: (args: {
|
|
143
|
-
ignoreRemain: boolean;
|
|
144
|
-
scene: number;
|
|
145
|
-
}) => void;
|
|
146
|
-
};
|
|
147
|
-
export type IConnection = {
|
|
148
|
-
/**
|
|
149
|
-
* 广告中途退出回调
|
|
150
|
-
*/
|
|
151
|
-
onHalfway?: (args: ICallbackArgs) => void;
|
|
152
|
-
/**
|
|
153
|
-
* 广告展示回调
|
|
154
|
-
*/
|
|
155
|
-
onShow?: (args: ICallbackArgs) => void;
|
|
156
|
-
/**
|
|
157
|
-
* 广告执行成功回调
|
|
158
|
-
*/
|
|
159
|
-
onFinish?: (args: ICallbackArgs) => void;
|
|
160
|
-
/**
|
|
161
|
-
* 广告执行失败回调
|
|
162
|
-
*/
|
|
163
|
-
onError?: (e: unknown) => void;
|
|
164
|
-
};
|
|
165
|
-
export type IConstructArgs = {
|
|
166
|
-
/**
|
|
167
|
-
* 初始化标识
|
|
168
|
-
*/
|
|
169
|
-
sign: string;
|
|
170
|
-
/**
|
|
171
|
-
* 是否开启日志
|
|
172
|
-
*/
|
|
173
|
-
log?: boolean | undefined;
|
|
174
|
-
/**
|
|
175
|
-
* 重试次数
|
|
176
|
-
*/
|
|
177
|
-
retry: number;
|
|
178
|
-
/**
|
|
179
|
-
* 是否保留tt激励视频广告实例
|
|
180
|
-
*/
|
|
181
|
-
preserveOnEnd: boolean;
|
|
182
|
-
/**
|
|
183
|
-
* 激励视频参数 (可选)
|
|
184
|
-
*/
|
|
185
|
-
adConfig?: IRewordAdConfig | undefined;
|
|
186
|
-
/**
|
|
187
|
-
* 回调集合
|
|
188
|
-
*/
|
|
189
|
-
collection?: IConnection | undefined;
|
|
190
|
-
};
|
|
191
|
-
/**
|
|
192
|
-
* 广告场景类型映射对象
|
|
193
|
-
*/
|
|
194
|
-
export type SceneTypeMap = {
|
|
195
|
-
readonly [x: number]: string;
|
|
196
|
-
};
|
|
197
|
-
/**
|
|
198
|
-
* 广告场景类型文本映射对象(反向映射)
|
|
199
|
-
*/
|
|
200
|
-
export type SceneTextMap = { readonly [K in SceneTypeMap[keyof SceneTypeMap]]: { [P in keyof SceneTypeMap]: SceneTypeMap[P] extends K ? P : never; }[keyof SceneTypeMap]; };
|
|
201
|
-
/**
|
|
202
|
-
* 场景值枚举 可持续添加
|
|
203
|
-
*/
|
|
204
|
-
export type RewardAdTriggerScene = keyof SceneTextMap;
|
|
205
|
-
/**
|
|
206
|
-
* 场景值枚举 可持续添加
|
|
207
|
-
*/
|
|
208
|
-
export type RewardAdTriggerSceneType = keyof SceneTypeMap;
|