@datarangers/sdk-javascript 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/plugin/ab.js CHANGED
@@ -1,930 +1 @@
1
- 'use strict';
2
-
3
- /******************************************************************************
4
- Copyright (c) Microsoft Corporation.
5
-
6
- Permission to use, copy, modify, and/or distribute this software for any
7
- purpose with or without fee is hereby granted.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
- PERFORMANCE OF THIS SOFTWARE.
16
- ***************************************************************************** */
17
-
18
- var __assign = function() {
19
- __assign = Object.assign || function __assign(t) {
20
- for (var s, i = 1, n = arguments.length; i < n; i++) {
21
- s = arguments[i];
22
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
-
29
- // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
30
- var STYLE_ID = '__rangers_ab_style__';
31
-
32
- function openOverlayer() {
33
- if (document.getElementById(STYLE_ID)) {
34
- return;
35
- }
36
-
37
- var css = 'body { opacity: 0 !important; }';
38
- var head = document.head || document.getElementsByTagName('head')[0];
39
- var style = document.createElement('style');
40
- style.id = STYLE_ID;
41
- style.type = 'text/css';
42
-
43
- if (style.styleSheet) {
44
- style.styleSheet.cssText = css;
45
- } else {
46
- style.appendChild(document.createTextNode(css));
47
- }
48
-
49
- head.appendChild(style);
50
- }
51
-
52
- function closeOverlayer() {
53
- var style = document.getElementById(STYLE_ID);
54
-
55
- if (style) {
56
- style.parentElement.removeChild(style);
57
- }
58
- }
59
-
60
- // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
61
- var AB_DOMAINS = {
62
- cn: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k',
63
- va: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k',
64
- sg: '1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k'
65
- };
66
-
67
- // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
68
- var Types;
69
-
70
- (function (Types) {
71
- Types["Init"] = "init";
72
- Types["Config"] = "config";
73
- Types["Start"] = "start";
74
- Types["Ready"] = "ready";
75
- Types["TokenComplete"] = "token-complete";
76
- Types["TokenStorage"] = "token-storage";
77
- Types["TokenFetch"] = "token-fetch";
78
- Types["TokenError"] = "token-error";
79
- Types["ConfigUuid"] = "config-uuid";
80
- Types["ConfigWebId"] = "config-webid";
81
- Types["ConfigDomain"] = "config-domain";
82
- Types["CustomWebId"] = "custom-webid";
83
- Types["AnonymousId"] = "anonymous-id";
84
- Types["TokenChange"] = "token-change";
85
- Types["TokenReset"] = "token-reset";
86
- Types["ConfigTransform"] = "config-transform";
87
- Types["EnvTransform"] = "env-transform";
88
- Types["SessionReset"] = "session-reset";
89
- Types["SessionResetTime"] = "session-reset-time";
90
- Types["Event"] = "event";
91
- Types["Events"] = "events";
92
- Types["EventNow"] = "event-now";
93
- Types["CleanEvents"] = "clean-events";
94
- Types["BeconEvent"] = "becon-event";
95
- Types["SubmitBefore"] = "submit-before";
96
- Types["SubmitScuess"] = "submit-scuess";
97
- Types["SubmitAfter"] = "submit-after";
98
- Types["SubmitError"] = "submit-error";
99
- Types["SubmitVerifyH"] = "submit-verify-h5";
100
- Types["Stay"] = "stay";
101
- Types["ResetStay"] = "reset-stay";
102
- Types["StayReady"] = "stay-ready";
103
- Types["SetStay"] = "set-stay";
104
- Types["RouteChange"] = "route-change";
105
- Types["RouteReady"] = "route-ready";
106
- Types["Ab"] = "ab";
107
- Types["AbVar"] = "ab-var";
108
- Types["AbAllVars"] = "ab-all-vars";
109
- Types["AbConfig"] = "ab-config";
110
- Types["AbExternalVersion"] = "ab-external-version";
111
- Types["AbVersionChangeOn"] = "ab-version-change-on";
112
- Types["AbVersionChangeOff"] = "ab-version-change-off";
113
- Types["AbOpenLayer"] = "ab-open-layer";
114
- Types["AbCloseLayer"] = "ab-close-layer";
115
- Types["AbReady"] = "ab-ready";
116
- Types["AbComplete"] = "ab-complete";
117
- Types["AbTimeout"] = "ab-timeout";
118
- Types["Profile"] = "profile";
119
- Types["ProfileSet"] = "profile-set";
120
- Types["ProfileSetOnce"] = "profile-set-once";
121
- Types["ProfileUnset"] = "profile-unset";
122
- Types["ProfileIncrement"] = "profile-increment";
123
- Types["ProfileAppend"] = "profile-append";
124
- Types["ProfileClear"] = "profile-clear";
125
- Types["TrackDuration"] = "track-duration";
126
- Types["TrackDurationStart"] = "track-duration-start";
127
- Types["TrackDurationEnd"] = "track-duration-end";
128
- Types["TrackDurationPause"] = "track-duration-pause";
129
- Types["TrackDurationResume"] = "tracl-duration-resume";
130
- Types["Autotrack"] = "autotrack";
131
- Types["AutotrackReady"] = "autotrack-ready";
132
- Types["CepReady"] = "cep-ready";
133
- Types["TracerReady"] = "tracer-ready";
134
- })(Types || (Types = {}));
135
-
136
- var DebuggerMesssge;
137
-
138
- (function (DebuggerMesssge) {
139
- DebuggerMesssge["DEBUGGER_MESSAGE"] = "debugger-message";
140
- DebuggerMesssge["DEBUGGER_MESSAGE_SDK"] = "debugger-message-sdk";
141
- DebuggerMesssge["DEBUGGER_MESSAGE_FETCH"] = "debugger-message-fetch";
142
- DebuggerMesssge["DEBUGGER_MESSAGE_FETCH_RESULT"] = "debugger-message-fetch-result";
143
- DebuggerMesssge["DEBUGGER_MESSAGE_EVENT"] = "debugger-message-event";
144
- DebuggerMesssge["DEVTOOL_WEB_READY"] = "devtool-web-ready";
145
- })(DebuggerMesssge || (DebuggerMesssge = {}));
146
-
147
- // Copyright 2022 Beijing Volcanoengine Technology Ltd. All Rights Reserved.
148
- // @ts-nocheck
149
- // @ts-nocheck
150
- var isObject = function isObject(obj) {
151
- return obj != null && Object.prototype.toString.call(obj) == '[object Object]';
152
- };
153
- (function () {
154
- var lastEventId = +Date.now() + Number(("" + Math.random()).slice(2, 8));
155
- return function () {
156
- lastEventId += 1;
157
- return lastEventId;
158
- };
159
- })();
160
- /* eslint-disable no-param-reassign */
161
-
162
- var decrypto = function decrypto(str, xor, hex) {
163
- if (typeof str !== 'string' || typeof xor !== 'number' || typeof hex !== 'number') {
164
- return;
165
- }
166
-
167
- var strCharList = [];
168
- var resultList = [];
169
- hex = hex <= 25 ? hex : hex % 25;
170
- var splitStr = String.fromCharCode(hex + 97);
171
- strCharList = str.split(splitStr);
172
-
173
- for (var i = 0; i < strCharList.length; i++) {
174
- var charCode = parseInt(strCharList[i], hex);
175
- charCode = charCode * 1 ^ xor;
176
- var strChar = String.fromCharCode(charCode);
177
- resultList.push(strChar);
178
- }
179
-
180
- var resultStr = resultList.join('');
181
- return resultStr;
182
- };
183
- var decodeUrl = function decodeUrl(string) {
184
- return decrypto(string, 64, 25);
185
- };
186
- var parseURL = function parseURL(url) {
187
- var a = document.createElement('a');
188
- a.href = url;
189
- return a;
190
- };
191
- var parseUrlQuery = function parseUrlQuery(url) {
192
- var queryObj = {};
193
-
194
- try {
195
- var queryString = parseURL(url).search;
196
- queryString = queryString.slice(1);
197
- queryString.split('&').forEach(function (keyValue) {
198
- var _keyValue = keyValue.split('=');
199
-
200
- var key;
201
- var value;
202
-
203
- if (_keyValue.length) {
204
- key = _keyValue[0];
205
- value = _keyValue[1];
206
- }
207
-
208
- try {
209
- queryObj[key] = decodeURIComponent(typeof value === 'undefined' ? '' : value);
210
- } catch (e) {
211
- queryObj[key] = value;
212
- }
213
- });
214
- } catch (e) {}
215
-
216
- return queryObj;
217
- };
218
-
219
- var CallbackType;
220
-
221
- (function (CallbackType) {
222
- CallbackType[CallbackType["Var"] = 0] = "Var";
223
- CallbackType[CallbackType["All"] = 1] = "All";
224
- })(CallbackType || (CallbackType = {}));
225
-
226
- var STORAGE_EXPRIRE = 1 * 30 * 24 * 60 * 60 * 1000;
227
- var API = '/service/2/abtest_config/';
228
-
229
- var Ab =
230
- /** @class */
231
- function () {
232
- function Ab() {
233
- this.fetchStatus = 'no';
234
- this.refreshFetchStatus = 'complete';
235
- this.versions = [];
236
- this.extVersions = [];
237
- this.mulilinkVersions = [];
238
- this.enable_multilink = false;
239
- this.enable_ab_visual = false;
240
- this.editMode = false;
241
- this.callbacks = [];
242
- this.data = null;
243
- this.changeListener = new Map();
244
- this.readyStatus = false;
245
- this.exposureCache = [];
246
- }
247
-
248
- Ab.prototype.apply = function (collect, config) {
249
- var _this = this;
250
-
251
- this.collect = collect;
252
- this.config = config;
253
- if (!this.config.enable_ab_test) return;
254
- var enable_multilink = config.enable_multilink,
255
- ab_channel_domain = config.ab_channel_domain,
256
- enable_ab_visual = config.enable_ab_visual,
257
- ab_cross = config.ab_cross,
258
- ab_cookie_domain = config.ab_cookie_domain,
259
- disable_ab_reset = config.disable_ab_reset;
260
- var abDomain = ab_channel_domain || decodeUrl(AB_DOMAINS[config.channel || 'cn']);
261
- var _a = collect.adapters,
262
- storage = _a.storage,
263
- fetch = _a.fetch;
264
- this.cacheStorgae = new storage(false);
265
- this.fetch = fetch;
266
- this.enable_multilink = enable_multilink;
267
- this.enable_ab_visual = enable_ab_visual;
268
- this.abKey = "__tea_sdk_ab_version_" + config.app_id;
269
- this.ab_cross = ab_cross;
270
- this.ab_cookie_domain = ab_cookie_domain || '';
271
- this.fetchUrl = "" + abDomain + API;
272
- this.reportUrl = "" + collect.configManager.getUrl('event');
273
- this.exposureLimit = config.exposure_limit || 20;
274
- this.ab_batch_time = config.ab_batch_time || 500;
275
- var Types = this.collect.Types;
276
- this.types = Types;
277
- this.collect.on(Types.TokenChange, function (tokenInfo) {
278
- if (disable_ab_reset) return;
279
- if (tokenInfo.type !== 'uuid') return;
280
- if (!_this.readyStatus) return;
281
-
282
- _this.clearCache();
283
-
284
- _this.fetchAB();
285
- });
286
- this.collect.on(Types.TokenReset, function () {
287
- if (disable_ab_reset) return;
288
- if (!_this.readyStatus) return;
289
-
290
- _this.clearCache();
291
-
292
- _this.fetchAB();
293
- });
294
- this.collect.on(Types.AbVar, function (_a) {
295
- var name = _a.name,
296
- defaultValue = _a.defaultValue,
297
- callback = _a.callback;
298
-
299
- _this.getVar(name, defaultValue, callback);
300
- });
301
- this.collect.on(Types.AbAllVars, function (callback) {
302
- _this.getAllVars(callback);
303
- });
304
- this.collect.on(Types.AbConfig, function (_a) {
305
- var params = _a.params,
306
- callback = _a.callback;
307
-
308
- _this.getABconfig(params, callback);
309
- });
310
- this.collect.on(Types.AbExternalVersion, function (vids) {
311
- _this.setExternalAbVersion(vids);
312
- });
313
- this.collect.on(Types.AbOpenLayer, function () {
314
- _this.openOverlayer();
315
- });
316
- this.collect.on(Types.AbCloseLayer, function () {
317
- _this.closeOverlayer();
318
- });
319
- this.collect.on(Types.AbVersionChangeOn, function (cb) {
320
- _this.changeListener.set(cb, cb);
321
- });
322
- this.collect.on(Types.AbVersionChangeOff, function (cb) {
323
- if (_this.changeListener.get(cb)) {
324
- _this.changeListener["delete"](cb);
325
- }
326
- });
327
- this.loadMode();
328
- (this.enable_ab_visual || this.enable_multilink) && this.openOverlayer(this.config.multilink_timeout_ms || 500);
329
- this.checkLocal();
330
- this.ready('ab');
331
-
332
- if (!this.readyStatus) {
333
- this.fetchAB();
334
- this.readyStatus = true;
335
- }
336
-
337
- this.collect.emit(Types.AbReady);
338
- };
339
-
340
- Ab.prototype.ready = function (name) {
341
- var _this = this;
342
-
343
- this.collect.set(name);
344
-
345
- if (this.collect.hook._hooksCache.hasOwnProperty(name)) {
346
- var emits = this.collect.hook._hooksCache[name];
347
- if (!Object.keys(emits).length) return;
348
-
349
- var _loop_1 = function _loop_1(key) {
350
- if (emits[key].length) {
351
- emits[key].forEach(function (item) {
352
- _this.collect.hook.emit(key, item);
353
- });
354
- }
355
- };
356
-
357
- for (var key in emits) {
358
- _loop_1(key);
359
- }
360
- }
361
- };
362
-
363
- Ab.prototype.loadMode = function () {// const name = getIframeUrl();
364
- // let editMode = '';
365
- // if (name) {
366
- // const { scenario, href } = name;
367
- // if (scenario) {
368
- // this.editMode = true;
369
- // editMode = scenario;
370
- // } else if (
371
- // href &&
372
- // (href.indexOf('datatester') !== -1 ||
373
- // href.indexOf('visual-editor') !== -1)
374
- // ) {
375
- // this.editMode = true;
376
- // editMode = 'visual-editor';
377
- // }
378
- // }
379
- // if (this.enable_ab_visual) {
380
- // readyToLoadEditor(this.collect, this.config);
381
- // if (editMode === 'visual-editor') {
382
- // this.collect.destoryInstace();
383
- // return;
384
- // }
385
- // }
386
- // if (this.enable_multilink) {
387
- // loadMuiltlink(this.collect, this.config);
388
- // }
389
- };
390
-
391
- Ab.prototype.checkLocal = function () {
392
- var _a = this.getABCache(),
393
- ab_version = _a.ab_version,
394
- ab_ext_version = _a.ab_ext_version,
395
- ab_version_multilink = _a.ab_version_multilink,
396
- data = _a.data;
397
-
398
- var mulilinkUrlVid = this.checkFromUrl();
399
-
400
- if (mulilinkUrlVid) {
401
- this.mulilinkVersions.push(mulilinkUrlVid);
402
- } else {
403
- this.mulilinkVersions = ab_version_multilink || [];
404
- }
405
-
406
- this.extVersions = ab_ext_version || [];
407
- this.versions = ab_version || [];
408
- this.data = data;
409
- var vids = this.versions.concat(this.extVersions);
410
-
411
- if (this.enable_multilink) {
412
- vids = vids.concat(this.mulilinkVersions);
413
- }
414
-
415
- this.configVersions(vids.join(','));
416
- };
417
-
418
- Ab.prototype.checkFromUrl = function () {
419
- var urlQueryObj = parseUrlQuery(window.location.href);
420
-
421
- if (urlQueryObj && urlQueryObj['vid']) {
422
- return urlQueryObj['vid'];
423
- }
424
-
425
- return '';
426
- };
427
-
428
- Ab.prototype.updateVersions = function () {
429
- var versions = this.extVersions.length ? this.versions.concat(this.extVersions) : this.versions;
430
-
431
- if (this.enable_multilink) {
432
- versions = versions.concat(this.mulilinkVersions);
433
- }
434
-
435
- this.configVersions(versions.join(','));
436
- this.updateABCache();
437
- this.changeListener.size > 0 && this.changeListener.forEach(function (listener) {
438
- if (typeof listener === 'function') {
439
- listener(versions);
440
- }
441
- });
442
- };
443
-
444
- Ab.prototype.configVersions = function (vids) {
445
- this.collect.configManager.setAbVersion(vids);
446
- };
447
-
448
- Ab.prototype.getVar = function (name, defaultValue, callback) {
449
- if (!name) {
450
- throw new Error('variable must not be empty');
451
- }
452
-
453
- if (defaultValue === undefined) {
454
- throw new Error('variable no default value');
455
- }
456
-
457
- if (typeof callback !== 'function') {
458
- throw new Error('callback must be a function');
459
- }
460
-
461
- var callbackObj = {
462
- name: name,
463
- defaultValue: defaultValue,
464
- callback: callback,
465
- type: CallbackType.Var
466
- };
467
-
468
- if (this.fetchStatus === 'complete' && this.refreshFetchStatus === 'complete') {
469
- this.getRealVar(callbackObj, name);
470
- } else {
471
- this.callbacks.push(callbackObj);
472
- }
473
- };
474
-
475
- Ab.prototype.getRealVar = function (item, key) {
476
- var name = item.name,
477
- defaultValue = item.defaultValue,
478
- callback = item.callback;
479
- var data = this.data;
480
-
481
- if (!data) {
482
- callback(defaultValue);
483
- return;
484
- }
485
-
486
- if (isObject(data[name])) {
487
- var vid = data[name].vid;
488
-
489
- if (key === '$ab_url') {
490
- if (!this.mulilinkVersions.includes(vid)) {
491
- this.mulilinkVersions.push(vid);
492
- }
493
- } else {
494
- if (!this.versions.includes(vid)) {
495
- this.versions.push(vid);
496
- }
497
- }
498
-
499
- this.updateVersions();
500
- this.fechEvent(vid, key, defaultValue);
501
- callback(data[name].val);
502
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
503
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
504
- secType: 'AB',
505
- info: "SDK \u66DD\u5149\u4E86\u5B9E\u9A8C" + name,
506
- level: 'info',
507
- time: Date.now(),
508
- data: data[name]
509
- });
510
- return;
511
- }
512
-
513
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
514
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
515
- secType: 'AB',
516
- info: 'SDK 调用getVar',
517
- level: 'info',
518
- time: Date.now(),
519
- data: defaultValue
520
- });
521
- callback(defaultValue);
522
- };
523
-
524
- Ab.prototype.getAllVars = function (callback) {
525
- if (typeof callback !== 'function') {
526
- throw new Error('callback must be a function');
527
- }
528
-
529
- var callbackObj = {
530
- callback: callback,
531
- type: CallbackType.All
532
- };
533
-
534
- if (this.fetchStatus === 'complete' && this.refreshFetchStatus === 'complete') {
535
- this.getRealAllVars(callbackObj);
536
- } else {
537
- this.callbacks.push(callbackObj);
538
- }
539
- };
540
-
541
- Ab.prototype.getRealAllVars = function (item) {
542
- var callback = item.callback;
543
- callback(this.data ? JSON.parse(JSON.stringify(this.data)) : {});
544
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
545
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
546
- secType: 'AB',
547
- info: 'SDK 调用getAllVars',
548
- level: 'info',
549
- time: Date.now(),
550
- data: this.data
551
- });
552
- };
553
-
554
- Ab.prototype.fechEvent = function (vid, key, ab_url) {
555
- try {
556
- if (this.config.disable_track_event) return;
557
- if (!vid) return;
558
-
559
- var _a = this.collect.configManager.get(),
560
- header = _a.header,
561
- user = _a.user;
562
-
563
- var cache = this.getABCache();
564
- if (cache && cache.uuid && cache.uuid !== user.user_unique_id) return;
565
- var event_1 = {
566
- event: 'abtest_exposure',
567
- ab_sdk_version: "" + vid,
568
- params: JSON.stringify({
569
- app_id: this.config.appId,
570
- ab_url: key === '$ab_url' ? ab_url : window.location.href
571
- }),
572
- local_time_ms: Date.now()
573
- };
574
- header['custom'] = JSON.stringify(header['custom']);
575
- var abData = {
576
- events: [event_1],
577
- user: user,
578
- header: header
579
- };
580
-
581
- if (key === '$ab_url') {
582
- if (window.navigator.sendBeacon) {
583
- window.navigator.sendBeacon(this.reportUrl, JSON.stringify([abData]));
584
- } else {
585
- this.reportExposure(abData);
586
- }
587
- } else {
588
- this.reportExposure(abData);
589
- }
590
- } catch (e) {
591
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
592
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
593
- info: '发生了异常',
594
- level: 'error',
595
- time: Date.now(),
596
- data: e.message
597
- });
598
- }
599
- };
600
-
601
- Ab.prototype.reportExposure = function (abData) {
602
- var _this = this;
603
-
604
- this.exposureCache.push(abData);
605
-
606
- if (this.reportTimeout) {
607
- clearTimeout(this.reportTimeout);
608
- }
609
-
610
- if (this.exposureCache.length >= this.exposureLimit) {
611
- this.report();
612
- } else {
613
- this.reportTimeout = setTimeout(function () {
614
- _this.report();
615
-
616
- clearTimeout(_this.reportTimeout);
617
- }, this.ab_batch_time);
618
- }
619
- };
620
-
621
- Ab.prototype.report = function () {
622
- var _this = this;
623
-
624
- var encodeData = this.collect.cryptoData(this.exposureCache);
625
- this.fetch(this.reportUrl, encodeData, 100000, false, function () {}, function () {}, '', 'POST', this.config.enable_encryption, this.config.encryption_header);
626
- this.exposureCache.forEach(function (item) {
627
- _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
628
- type: DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,
629
- info: '埋点上报成功',
630
- time: Date.now(),
631
- data: [item],
632
- code: 200,
633
- status: 'success'
634
- });
635
- });
636
- this.exposureCache = [];
637
- };
638
-
639
- Ab.prototype.setExternalAbVersion = function (vid) {
640
- this.extVersions = [vid];
641
- this.updateVersions();
642
- };
643
-
644
- Ab.prototype.getABconfig = function (params, callback) {
645
- var keys = Object.keys(params);
646
-
647
- if (keys && keys.length) {
648
- this.collect.configManager.set(params);
649
- }
650
-
651
- this.fetchAB(callback);
652
- };
653
-
654
- Ab.prototype.get = function (key) {
655
- if (this.ab_cross) {
656
- var ab_cookie = this.cacheStorgae.getCookie(key, this.ab_cookie_domain);
657
- return ab_cookie ? JSON.parse(ab_cookie) : null;
658
- } else {
659
- return this.cacheStorgae.getItem(key);
660
- }
661
- };
662
-
663
- Ab.prototype.set = function (key, data) {
664
- if (this.ab_cross) {
665
- this.cacheStorgae.setCookie(key, data, STORAGE_EXPRIRE, this.ab_cookie_domain);
666
- } else {
667
- this.cacheStorgae.setItem(key, data);
668
- }
669
-
670
- this.collect.configManager.setAbCache(data);
671
- };
672
-
673
- Ab.prototype.getABCache = function (key) {
674
- var data = {
675
- ab_version: [],
676
- ab_ext_version: [],
677
- ab_version_multilink: [],
678
- data: null,
679
- timestamp: +new Date(),
680
- uuid: ''
681
- };
682
- data = this.get(this.abKey) || data;
683
-
684
- if (Date.now() - data.timestamp >= STORAGE_EXPRIRE) {
685
- this.cacheStorgae.removeItem(this.abKey);
686
- return null;
687
- }
688
-
689
- if (key) {
690
- return data[key];
691
- }
692
-
693
- return data;
694
- };
695
-
696
- Ab.prototype.updateABCache = function () {
697
- var cache = this.getABCache();
698
- cache.ab_version_multilink = this.mulilinkVersions;
699
- cache.ab_ext_version = this.extVersions;
700
- cache.ab_version = this.versions;
701
- cache.timestamp = Date.now();
702
- this.set(this.abKey, cache);
703
- };
704
-
705
- Ab.prototype.setAbCache = function (uuid) {
706
- var cache = this.getABCache();
707
- cache.data = this.data;
708
- cache.uuid = uuid;
709
- cache.timestamp = Date.now();
710
- this.set(this.abKey, cache);
711
- };
712
-
713
- Ab.prototype.clearCache = function () {
714
- this.refreshFetchStatus = 'ing';
715
- this.data = {};
716
- this.extVersions = [];
717
- this.mulilinkVersions = [];
718
- this.versions = [];
719
- this.collect.configManager.clearAbCache();
720
- };
721
-
722
- Ab.prototype.openOverlayer = function (timeout) {
723
- var _this = this;
724
-
725
- openOverlayer();
726
-
727
- if (timeout) {
728
- var layer_1 = setTimeout(function () {
729
- _this.closeOverlayer();
730
-
731
- clearTimeout(layer_1);
732
- }, timeout);
733
- }
734
- };
735
-
736
- Ab.prototype.closeOverlayer = function () {
737
- closeOverlayer();
738
- };
739
-
740
- Ab.prototype.fetchComplete = function (abData, uuid) {
741
- var _this = this;
742
-
743
- if (abData && Object.prototype.toString.call(abData) == '[object Object]') {
744
- this.data = abData;
745
- this.setAbCache(uuid);
746
- var versions_1 = [];
747
- Object.keys(abData).forEach(function (key) {
748
- var vid = abData[key].vid;
749
-
750
- if (vid) {
751
- versions_1.push(vid);
752
- }
753
- });
754
- this.versions = this.versions.filter(function (vid) {
755
- return versions_1.includes(vid);
756
- });
757
- var $ab_url = abData.$ab_url,
758
- $ab_modification = abData.$ab_modification;
759
-
760
- if ($ab_modification && $ab_modification.val && this.enable_ab_visual) {
761
- if (this.collect.destroyInstance) return;
762
- this.getVar('$ab_modification', window.location.href, function () {
763
- // loadVisual($ab_modification.val);
764
- _this.closeOverlayer();
765
- });
766
- } else if ($ab_url && this.enable_multilink) {
767
- this.mulilinkVersions = this.mulilinkVersions.filter(function (vid) {
768
- return versions_1.includes(vid);
769
- });
770
- var val_1 = $ab_url.val,
771
- vid_1 = $ab_url.vid;
772
-
773
- if (val_1 && vid_1) {
774
- this.getVar('$ab_url', val_1, function () {
775
- if (_this.editMode) return;
776
-
777
- if (val_1 !== window.location.href) {
778
- setTimeout(function () {
779
- if (_this.collect.destroyInstance) return;
780
- var jump = "" + val_1;
781
- jump = jump.indexOf('http') === -1 ? "https://" + jump : jump;
782
- var newhost = parseURL(jump).host;
783
-
784
- try {
785
- var urlObj = new URL(jump);
786
-
787
- if (newhost !== location.host) {
788
- // 跳转的是一个新域名
789
- urlObj.searchParams.append('vid', vid_1);
790
- } else {
791
- // 不同的域名不能replace
792
- window.history.replaceState('', '', jump);
793
- }
794
-
795
- window.location.href = urlObj.href;
796
- } catch (e) {
797
- window.location.href = jump;
798
- }
799
- }, 100);
800
- } else {
801
- _this.closeOverlayer();
802
- }
803
- });
804
- }
805
- }
806
-
807
- this.updateVersions();
808
- } else {
809
- this.closeOverlayer();
810
- }
811
-
812
- this.callbacks.forEach(function (item) {
813
- return _this[item.type === CallbackType.Var ? 'getRealVar' : 'getRealAllVars'](item, '');
814
- });
815
- this.callbacks = [];
816
- };
817
-
818
- Ab.prototype.fetchAB = function (callback) {
819
- var _this = this;
820
-
821
- var env = this.collect.configManager.get();
822
- var header = env.header,
823
- user = env.user;
824
-
825
- if (this.config.enable_anonymousid) {
826
- delete user.web_id;
827
- }
828
-
829
- var fetchUuid = user.user_unique_id;
830
- var requestBody = {
831
- header: __assign({
832
- aid: this.config.app_id
833
- }, user || {}, header || {}, {
834
- ab_sdk_version: this.collect.configManager.getAbVersion(),
835
- ab_url: window.location.href
836
- })
837
- };
838
- this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
839
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
840
- info: 'SDK 发起AB实验请求',
841
- level: 'info',
842
- logType: 'fetch',
843
- time: Date.now(),
844
- data: requestBody
845
- });
846
- var cryptoData = this.collect.cryptoData(requestBody);
847
- this.fetch(this.fetchUrl, cryptoData, this.config.ab_timeout || 3000, false, function (response) {
848
- _this.fetchStatus = 'complete';
849
- _this.refreshFetchStatus = 'complete'; // let aa = {
850
- // message: "success",
851
- // data: {
852
- // abcdefg: { val: "gss", vid: "11407" },
853
- // erf: { val: 'name', vid: "22" },
854
- // hhhhh: { val: 'age', vid: "33" },
855
- // juuioh: { val: 'sex', vid: "44" },
856
- // $ab_url: { val: 'http://0.0.0.0:8898/index_cdn_5.html?s=2', vid: '0000' }
857
- // }
858
- // }
859
- // if (env.user.user_unique_id === 'bbbb') {
860
- // aa.data.abcdefg.vid = '11408'
861
- // } else if (env.user.user_unique_id === 'cccc') {
862
- // aa.data.abcdefg.vid = '11409'
863
- // }
864
-
865
- var data = response.data,
866
- message = response.message; // 解析出code
867
-
868
- if (message === 'success') {
869
- _this.fetchComplete(data, fetchUuid);
870
-
871
- callback && callback(data);
872
- } else {
873
- _this.fetchComplete(null, fetchUuid);
874
-
875
- callback && callback(null);
876
- }
877
-
878
- _this.collect.emit(_this.types.AbComplete, data);
879
-
880
- _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
881
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
882
- secType: 'AB',
883
- info: 'AB实验请求成功',
884
- level: 'info',
885
- logType: 'fetch',
886
- time: Date.now(),
887
- data: data
888
- });
889
- }, function () {
890
- _this.fetchStatus = 'complete';
891
- _this.refreshFetchStatus = 'complete';
892
-
893
- _this.fetchComplete(null, fetchUuid);
894
-
895
- callback && callback(null);
896
-
897
- _this.collect.emit(_this.types.AbTimeout);
898
-
899
- _this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE, {
900
- type: DebuggerMesssge.DEBUGGER_MESSAGE_SDK,
901
- secType: 'AB',
902
- info: 'AB实验请求网络异常',
903
- level: 'error',
904
- logType: 'fetch',
905
- time: Date.now()
906
- });
907
- }, '', '', this.config.enable_encryption, this.config.encryption_header);
908
- };
909
-
910
- Ab.prototype.filterUrl = function (url) {
911
- try {
912
- var _reg = '';
913
-
914
- if (url.indexOf('&multilink=true') !== -1) {
915
- _reg = '&multilink=true[\x00-\xff]*';
916
- } else if (url.indexOf('?multilink=true') !== -1) {
917
- _reg = '\\?multilink=true[\x00-\xff]*';
918
- }
919
-
920
- var reg = new RegExp(_reg, 'g');
921
- url = url.replace(reg, '');
922
- } catch (e) {}
923
-
924
- return url;
925
- };
926
-
927
- return Ab;
928
- }();
929
-
930
- module.exports = Ab;
1
+ "use strict";var e=function(){return e=Object.assign||function(e){for(var t,o=1,i=arguments.length;o<i;o++)for(var n in t=arguments[o])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},e.apply(this,arguments)},t="__rangers_ab_style__";var o,i,n={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"};!function(e){e.Init="init",e.Config="config",e.Start="start",e.Ready="ready",e.TokenComplete="token-complete",e.TokenStorage="token-storage",e.TokenFetch="token-fetch",e.TokenError="token-error",e.ConfigUuid="config-uuid",e.ConfigWebId="config-webid",e.ConfigDomain="config-domain",e.CustomWebId="custom-webid",e.AnonymousId="anonymous-id",e.TokenChange="token-change",e.TokenReset="token-reset",e.ConfigTransform="config-transform",e.EnvTransform="env-transform",e.SessionReset="session-reset",e.SessionResetTime="session-reset-time",e.Event="event",e.Events="events",e.EventNow="event-now",e.CleanEvents="clean-events",e.BeconEvent="becon-event",e.SubmitBefore="submit-before",e.SubmitScuess="submit-scuess",e.SubmitSuccess="submit-success",e.SubmitAfter="submit-after",e.SubmitError="submit-error",e.SubmitVerifyH="submit-verify-h5",e.Stay="stay",e.ResetStay="reset-stay",e.StayReady="stay-ready",e.SetStay="set-stay",e.RouteChange="route-change",e.RouteReady="route-ready",e.Ab="ab",e.AbVar="ab-var",e.AbAllVars="ab-all-vars",e.AbConfig="ab-config",e.AbExternalVersion="ab-external-version",e.AbVersionChangeOn="ab-version-change-on",e.AbVersionChangeOff="ab-version-change-off",e.AbOpenLayer="ab-open-layer",e.AbCloseLayer="ab-close-layer",e.AbReady="ab-ready",e.AbComplete="ab-complete",e.AbTimeout="ab-timeout",e.Profile="profile",e.ProfileSet="profile-set",e.ProfileSetOnce="profile-set-once",e.ProfileUnset="profile-unset",e.ProfileIncrement="profile-increment",e.ProfileAppend="profile-append",e.ProfileClear="profile-clear",e.TrackDuration="track-duration",e.TrackDurationStart="track-duration-start",e.TrackDurationEnd="track-duration-end",e.TrackDurationPause="track-duration-pause",e.TrackDurationResume="tracl-duration-resume",e.Autotrack="autotrack",e.AutotrackReady="autotrack-ready",e.CustomHeader="custom-request-header",e.TracerReady="tracer-ready"}(o||(o={})),function(e){e.DEBUGGER_MESSAGE="debugger-message",e.DEBUGGER_MESSAGE_SDK="debugger-message-sdk",e.DEBUGGER_MESSAGE_FETCH="debugger-message-fetch",e.DEBUGGER_MESSAGE_FETCH_RESULT="debugger-message-fetch-result",e.DEBUGGER_MESSAGE_EVENT="debugger-message-event",e.DEVTOOL_WEB_READY="devtool-web-ready"}(i||(i={}));Date.now(),Number((""+Math.random()).slice(2,8));var r=function(e){return function(e,t,o){if("string"==typeof e&&"number"==typeof t&&"number"==typeof o){var i,n=[];o=o<=25?o:o%25;var r=String.fromCharCode(o+97);i=e.split(r);for(var a=0;a<i.length;a++){var s=parseInt(i[a],o);s=1*s^t;var c=String.fromCharCode(s);n.push(c)}return n.join("")}}(e,64,25)},a=function(e){var t=document.createElement("a");return t.href=e,t};var s,c=function(e,t){return e(t={exports:{}},t.exports),t.exports}(function(e,t){var o;o=function(){function e(){for(var e=0,t={};e<arguments.length;e++){var o=arguments[e];for(var i in o)t[i]=o[i]}return t}function t(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function o(i){function n(){}function r(t,o,r){if("undefined"!=typeof document){"number"==typeof(r=e({path:"/"},n.defaults,r)).expires&&(r.expires=new Date(1*new Date+864e5*r.expires)),r.expires=r.expires?r.expires.toUTCString():"";try{var a=JSON.stringify(o);/^[\{\[]/.test(a)&&(o=a)}catch(e){}o=i.write?i.write(o,t):encodeURIComponent(String(o)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),t=encodeURIComponent(String(t)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var s="";for(var c in r)r[c]&&(s+="; "+c,!0!==r[c]&&(s+="="+r[c].split(";")[0]));return document.cookie=t+"="+o+s}}function a(e,o){if("undefined"!=typeof document){for(var n={},r=document.cookie?document.cookie.split("; "):[],a=0;a<r.length;a++){var s=r[a].split("="),c=s.slice(1).join("=");o||'"'!==c.charAt(0)||(c=c.slice(1,-1));try{var l=t(s[0]);if(c=(i.read||i)(c,l)||t(c),o)try{c=JSON.parse(c)}catch(e){}if(n[l]=c,e===l)break}catch(e){}}return e?n[e]:n}}return n.set=r,n.get=function(e){return a(e,!1)},n.getJSON=function(e){return a(e,!0)},n.remove=function(t,o){r(t,"",e(o,{expires:-1}))},n.defaults={},n.withConverter=o,n}(function(){})},e.exports=o()}),l=function(){function e(){this.cache={}}return e.prototype.setItem=function(e,t){this.cache[e]=t},e.prototype.getItem=function(e){return this.cache[e]},e.prototype.removeItem=function(e){this.cache[e]=void 0},e}(),h=function(){function e(){this.support=this.isSupportLS()}return e.prototype.isSupportLS=function(){try{return localStorage.setItem("_applogtest-test-key","hi"),localStorage.getItem("_applogtest-test-key"),localStorage.removeItem("_applogtest-test-key"),!0}catch(e){return!1}},e.prototype.getItem=function(e){try{var t=localStorage.getItem(e),o=t;try{t&&"string"==typeof t&&(o=JSON.parse(t))}catch(e){}return o||{}}catch(e){}return{}},e.prototype.setItem=function(e,t){try{var o="string"==typeof t?t:JSON.stringify(t);localStorage.setItem(e,o)}catch(e){}},e.prototype.removeItem=function(e){try{localStorage.removeItem(e)}catch(e){}},e}(),u=function(){function e(){this.support=this.isSupportSession()}return e.prototype.isSupportSession=function(){try{return sessionStorage.setItem("_applogtest-test-key","hi"),sessionStorage.getItem("_applogtest-test-key"),sessionStorage.removeItem("_applogtest-test-key"),!0}catch(e){return!1}},e.prototype.getItem=function(e){try{var t=sessionStorage.getItem(e),o=t;try{t&&"string"==typeof t&&(o=JSON.parse(t))}catch(e){}return o||{}}catch(e){}return{}},e.prototype.setItem=function(e,t){try{var o="string"==typeof t?t:JSON.stringify(t);sessionStorage.setItem(e,o)}catch(e){}},e.prototype.removeItem=function(e){try{sessionStorage.removeItem(e)}catch(e){}},e}(),p=function(){function e(){this.defaultExpireTime=6048e5,this.local=new h,this.session=new u,this.cache=new l}return e.prototype.getLocalItem=function(e){return this.local.getItem(e)},e.prototype.setLocalItem=function(e,t){this.local.setItem(e,t)},e.prototype.removeLocalItem=function(e){this.local.removeItem(e)},e.prototype.getSessionItem=function(e){return this.session.getItem(e)},e.prototype.setSessionItem=function(e,t){this.session.setItem(e,t)},e.prototype.removeSessionItem=function(e){this.session.removeItem(e)},e.prototype.getCacheItem=function(e){return this.cache.getItem(e)},e.prototype.setCacheItem=function(e,t){this.cache.setItem(e,t)},e.prototype.removeCacheItem=function(e){this.cache.removeItem(e)},e.prototype.getCookie=function(e,t){try{return c.get(e)}catch(e){return""}},e.prototype.setCookie=function(e,t,o,i){void 0===o&&(o=this.defaultExpireTime);try{var n=i||document.domain,r=+new Date+o;c.set(e,t,{expires:new Date(r),path:"/",domain:n})}catch(e){}},e.prototype.removeCookie=function(e,t){try{c.remove(e,{path:"/",domain:t||""})}catch(e){}},e}();!function(e){e[e.Var=0]="Var",e[e.All=1]="All"}(s||(s={}));var f=2592e6,m=function(){function o(){this.fetchStatus="no",this.refreshFetchStatus="complete",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data=null,this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[]}return o.prototype.apply=function(e,t){var o=this;if(this.collect=e,this.config=t,this.config.enable_ab_test){var i=t.enable_multilink,a=t.ab_channel_domain,s=t.enable_ab_visual,c=t.ab_cross,l=t.ab_cookie_domain,h=t.disable_ab_reset,u=a||r(n[t.channel||"cn"]);this.cacheStorgae=new p,this.enable_multilink=i,this.enable_ab_visual=s,this.abKey="__tea_sdk_ab_version_"+t.app_id,this.ab_cross=c,this.ab_cookie_domain=l||"",this.fetchUrl=u+"/service/2/abtest_config/",this.reportUrl=""+e.configManager.getUrl("event"),this.exposureLimit=t.exposure_limit||20,this.ab_batch_time=t.ab_batch_time||500;var f=this.collect.Types;this.types=f,this.collect.on(f.TokenChange,function(e){h||"uuid"===e.type&&o.readyStatus&&(o.clearCache(),o.fetchAB())}),this.collect.on(f.TokenReset,function(){h||o.readyStatus&&(o.clearCache(),o.fetchAB())}),this.collect.on(f.AbVar,function(e){var t=e.name,i=e.defaultValue,n=e.callback;o.getVar(t,i,n)}),this.collect.on(f.AbAllVars,function(e){o.getAllVars(e)}),this.collect.on(f.AbConfig,function(e){var t=e.params,i=e.callback;o.getABconfig(t,i)}),this.collect.on(f.AbExternalVersion,function(e){o.setExternalAbVersion(e)}),this.collect.on(f.AbOpenLayer,function(){o.openOverlayer()}),this.collect.on(f.AbCloseLayer,function(){o.closeOverlayer()}),this.collect.on(f.AbVersionChangeOn,function(e){o.changeListener.set(e,e)}),this.collect.on(f.AbVersionChangeOff,function(e){o.changeListener.get(e)&&o.changeListener.delete(e)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(this.fetchAB(),this.readyStatus=!0),this.collect.emit(f.AbReady)}},o.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var o=this.collect.hook._hooksCache[e];if(!Object.keys(o).length)return;var i=function(e){o[e].length&&o[e].forEach(function(o){t.collect.hook.emit(e,o)})};for(var n in o)i(n)}},o.prototype.loadMode=function(){},o.prototype.checkLocal=function(){var e=this.getABCache(),t=e.ab_version,o=e.ab_ext_version,i=e.ab_version_multilink,n=e.data,r=this.checkFromUrl();r?this.mulilinkVersions.push(r):this.mulilinkVersions=i||[],this.extVersions=o||[],this.versions=t||[],this.data=n;var a=this.versions.concat(this.extVersions);this.enable_multilink&&(a=a.concat(this.mulilinkVersions)),this.configVersions(a.join(","))},o.prototype.checkFromUrl=function(){var e=function(e){var t={};try{var o=a(e).search;(o=o.slice(1)).split("&").forEach(function(e){var o,i,n=e.split("=");n.length&&(o=n[0],i=n[1]);try{t[o]=decodeURIComponent(void 0===i?"":i)}catch(e){t[o]=i}})}catch(e){}return t}(window.location.href);return e&&e.vid?e.vid:""},o.prototype.updateVersions=function(){var e=this.extVersions.length?this.versions.concat(this.extVersions):this.versions;this.enable_multilink&&(e=e.concat(this.mulilinkVersions)),this.configVersions(e.join(",")),this.updateABCache(),this.changeListener.size>0&&this.changeListener.forEach(function(t){"function"==typeof t&&t(e)})},o.prototype.configVersions=function(e){this.collect.configManager.setAbVersion(e)},o.prototype.getVar=function(e,t,o){if(!e)throw new Error("variable must not be empty");if(void 0===t)throw new Error("variable no default value");if("function"!=typeof o)throw new Error("callback must be a function");var i={name:e,defaultValue:t,callback:o,type:s.Var};"complete"===this.fetchStatus&&"complete"===this.refreshFetchStatus?this.getRealVar(i,e):this.callbacks.push(i)},o.prototype.getRealVar=function(e,t){var o=e.name,n=e.defaultValue,r=e.callback,a=this.data;if(a){if(null!=(c=a[o])&&"[object Object]"==Object.prototype.toString.call(c)){var s=a[o].vid;return"$ab_url"===t?this.mulilinkVersions.includes(s)||this.mulilinkVersions.push(s):this.versions.includes(s)||this.versions.push(s),this.updateVersions(),this.fechEvent(s,t,n),r(a[o].val),void this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 曝光了实验"+o,level:"info",time:Date.now(),data:a[o]})}var c;this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用getVar",level:"info",time:Date.now(),data:n}),r(n)}else r(n)},o.prototype.getAllVars=function(e){if("function"!=typeof e)throw new Error("callback must be a function");var t={callback:e,type:s.All};"complete"===this.fetchStatus&&"complete"===this.refreshFetchStatus?this.getRealAllVars(t):this.callbacks.push(t)},o.prototype.getRealAllVars=function(e){(0,e.callback)(this.data?JSON.parse(JSON.stringify(this.data)):{}),this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用getAllVars",level:"info",time:Date.now(),data:this.data})},o.prototype.fechEvent=function(e,t,o){try{if(this.config.disable_track_event)return;if(!e)return;var n=this.collect.configManager.get(),r=n.header,a=n.user,s=this.getABCache();if(s&&s.uuid&&s.uuid!==a.user_unique_id)return;var c={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:"$ab_url"===t?o:window.location.href}),local_time_ms:Date.now()};r.custom=JSON.stringify(r.custom);var l={events:[c],user:a,header:r};"$ab_url"===t&&window.navigator.sendBeacon?window.navigator.sendBeacon(this.reportUrl,JSON.stringify([l])):this.reportExposure(l)}catch(e){this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:e.message})}},o.prototype.reportExposure=function(e){var t=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report():this.reportTimeout=setTimeout(function(){t.report(),clearTimeout(t.reportTimeout)},this.ab_batch_time)},o.prototype.report=function(){var e=this,t=this.collect.cryptoData(this.exposureCache);this.collect.requestManager.useRequest({url:this.reportUrl,data:t,timeout:1e5,useBeacon:!1,encryption:this.config.enable_encryption,encryption_header:this.config.encryption_header,zip:!0,type:"event"}),this.exposureCache.forEach(function(t){e.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:[t],code:200,status:"success"})}),this.exposureCache=[]},o.prototype.setExternalAbVersion=function(e){this.extVersions=[e],this.updateVersions()},o.prototype.getABconfig=function(e,t){var o=Object.keys(e);o&&o.length&&this.collect.configManager.set(e),this.fetchAB(t)},o.prototype.get=function(e){if(this.ab_cross){var t=this.cacheStorgae.getCookie(e,this.ab_cookie_domain);return t?JSON.parse(t):null}return this.cacheStorgae.getLocalItem(e)},o.prototype.set=function(e,t){this.ab_cross?this.cacheStorgae.setCookie(e,t,f,this.ab_cookie_domain):this.cacheStorgae.setLocalItem(e,t),this.collect.configManager.setAbCache(t)},o.prototype.getABCache=function(e){var t={ab_version:[],ab_ext_version:[],ab_version_multilink:[],data:null,timestamp:+new Date,uuid:""};return t=this.get(this.abKey)||t,Date.now()-t.timestamp>=f?(this.cacheStorgae.removeLocalItem(this.abKey),null):e?t[e]:t},o.prototype.updateABCache=function(){var e=this.getABCache();e.ab_version_multilink=this.mulilinkVersions,e.ab_ext_version=this.extVersions,e.ab_version=this.versions,e.timestamp=Date.now(),this.set(this.abKey,e)},o.prototype.setAbCache=function(e){var t=this.getABCache();t.data=this.data,t.uuid=e,t.timestamp=Date.now(),this.set(this.abKey,t)},o.prototype.clearCache=function(){this.refreshFetchStatus="ing",this.data={},this.extVersions=[],this.mulilinkVersions=[],this.versions=[],this.collect.configManager.clearAbCache()},o.prototype.openOverlayer=function(e){var o=this;if(function(){if(!document.getElementById(t)){var e="body { opacity: 0 !important; }",o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.id=t,i.type="text/css",i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e)),o.appendChild(i)}}(),e)var i=setTimeout(function(){o.closeOverlayer(),clearTimeout(i)},e)},o.prototype.closeOverlayer=function(){var e;(e=document.getElementById(t))&&e.parentElement.removeChild(e)},o.prototype.fetchComplete=function(e,t){var o=this;if(e&&"[object Object]"==Object.prototype.toString.call(e)){this.data=e,this.setAbCache(t);var i=[];Object.keys(e).forEach(function(t){var o=e[t].vid;o&&i.push(o)}),this.versions=this.versions.filter(function(e){return i.includes(e)});var n=e.$ab_url,r=e.$ab_modification;if(r&&r.val&&this.enable_ab_visual){if(this.collect.destroyInstance)return;this.getVar("$ab_modification",window.location.href,function(){o.closeOverlayer()})}else if(n&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(e){return i.includes(e)});var c=n.val,l=n.vid;c&&l&&this.getVar("$ab_url",c,function(){o.editMode||(c!==window.location.href?setTimeout(function(){if(!o.collect.destroyInstance){var e=""+c;e=-1===e.indexOf("http")?"https://"+e:e;var t=a(e).host;try{var i=new URL(e);t!==location.host?i.searchParams.append("vid",l):window.history.replaceState("","",e),window.location.href=i.href}catch(t){window.location.href=e}}},100):o.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbacks.forEach(function(e){return o[e.type===s.Var?"getRealVar":"getRealAllVars"](e,"")}),this.callbacks=[]},o.prototype.fetchAB=function(t){var o=this,n=this.collect.configManager.get(),r=n.header,a=n.user;this.config.enable_anonymousid&&delete a.web_id;var s=a.user_unique_id,c={header:e({aid:this.config.app_id},a||{},r||{},{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})},l=this.collect.cryptoData(c);this.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,info:"SDK 发起AB实验请求",level:"info",logType:"fetch",time:Date.now(),data:c,infoType:"sdk"}),this.collect.requestManager.useRequest({url:this.fetchUrl,data:l,success:function(e){o.fetchStatus="complete",o.refreshFetchStatus="complete";var n=e.data;"success"===e.message?(o.fetchComplete(n,s),t&&t(n)):(o.fetchComplete(null,s),t&&t(null)),o.collect.emit(o.types.AbComplete,n),o.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求成功",level:"info",logType:"fetch",time:Date.now(),data:n,infoType:"sdk"})},fail:function(){o.fetchStatus="complete",o.refreshFetchStatus="complete",o.fetchComplete(null,s),t&&t(null),o.collect.emit(o.types.AbTimeout),o.collect.emit(i.DEBUGGER_MESSAGE,{type:i.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求网络异常",level:"error",logType:"fetch",time:Date.now(),infoType:"sdk"})},timeout:this.config.ab_timeout||1e4,encryption:this.config.enable_encryption,encryption_header:this.config.encryption_header})},o.prototype.filterUrl=function(e){try{var t="";-1!==e.indexOf("&multilink=true")?t="&multilink=true[\0-ÿ]*":-1!==e.indexOf("?multilink=true")&&(t="\\?multilink=true[\0-ÿ]*");var o=new RegExp(t,"g");e=e.replace(o,"")}catch(e){}return e},o}();module.exports=m;