@whitesev/utils 2.6.8 → 2.7.0

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/index.amd.js CHANGED
@@ -226,6 +226,273 @@ define((function () { 'use strict';
226
226
  }
227
227
  }
228
228
 
229
+ const TryCatch = function (...args) {
230
+ /* 定义变量和函数 */
231
+ let callbackFunction = null;
232
+ let context = null;
233
+ let handleError = (error) => { };
234
+ let defaultDetails = {
235
+ log: true,
236
+ };
237
+ const TryCatchCore = {
238
+ /**
239
+ *
240
+ * @param paramDetails 配置
241
+ * @returns
242
+ */
243
+ config(paramDetails) {
244
+ defaultDetails = Object.assign(defaultDetails, paramDetails);
245
+ return TryCatchCore;
246
+ },
247
+ /**
248
+ * 处理错误
249
+ * @param handler
250
+ */
251
+ error(handler) {
252
+ // @ts-ignore
253
+ handleError = handler;
254
+ return TryCatchCore;
255
+ },
256
+ /**
257
+ * 执行传入的函数并捕获其可能抛出的错误,并通过传入的错误处理函数进行处理。
258
+ * @param callback 待执行函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
259
+ * @param __context__ 待执行函数的作用域,用于apply指定
260
+ * @returns 如果函数有返回值,则返回该返回值;否则返回 tryCatchObj 函数以支持链式调用。
261
+ * @throws {Error} 如果传入参数不符合要求,则会抛出相应类型的错误。
262
+ */
263
+ run(callback, __context__) {
264
+ callbackFunction = callback;
265
+ context = __context__ || this;
266
+ let result = executeTryCatch(callbackFunction, handleError, context);
267
+ // @ts-ignore
268
+ return result !== void 0 ? result : TryCatchCore;
269
+ },
270
+ };
271
+ /**
272
+ * 执行传入的函数并捕获其可能抛出的错误,并通过传入的错误处理函数进行处理。
273
+ * @param callback - 待执行函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
274
+ * @param handleErrorFunc - 错误处理函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
275
+ * @param funcThis - 待执行函数的作用域,用于apply指定
276
+ * @returns 如果函数有返回值,则返回该返回值;否则返回 undefined。
277
+ */
278
+ function executeTryCatch(callback, handleErrorFunc, funcThis) {
279
+ let result = void 0;
280
+ try {
281
+ if (typeof callback === "string") {
282
+ result = new Function(callback).apply(funcThis, args);
283
+ }
284
+ else {
285
+ result = callback.apply(funcThis, args);
286
+ }
287
+ }
288
+ catch (error) {
289
+ if (defaultDetails.log) {
290
+ callback = callback;
291
+ console.log(`%c ${callback?.name ? callback?.name : callback + "出现错误"} `, "color: #f20000");
292
+ console.log(`%c 错误原因:${error}`, "color: #f20000");
293
+ console.trace(callback);
294
+ }
295
+ if (handleErrorFunc) {
296
+ if (typeof handleErrorFunc === "string") {
297
+ result = new Function(handleErrorFunc).apply(funcThis, [
298
+ ...args,
299
+ error,
300
+ ]);
301
+ }
302
+ else {
303
+ result = handleErrorFunc.apply(funcThis, [...args, error]);
304
+ }
305
+ }
306
+ }
307
+ return result;
308
+ }
309
+ return TryCatchCore;
310
+ };
311
+
312
+ class CommonUtil {
313
+ assign(target = {}, source = {}, isAdd = false) {
314
+ let UtilsContext = this;
315
+ if (Array.isArray(source)) {
316
+ let canTraverse = source.filter((item) => {
317
+ return typeof item === "object";
318
+ });
319
+ if (!canTraverse.length) {
320
+ return source;
321
+ }
322
+ }
323
+ if (source == null) {
324
+ return target;
325
+ }
326
+ if (target == null) {
327
+ target = {};
328
+ }
329
+ if (isAdd) {
330
+ for (const sourceKeyName in source) {
331
+ const targetKeyName = sourceKeyName;
332
+ let targetValue = target[targetKeyName];
333
+ let sourceValue = source[sourceKeyName];
334
+ if (typeof sourceValue === "object" &&
335
+ sourceValue != null &&
336
+ sourceKeyName in target &&
337
+ !UtilsContext.isDOM(sourceValue)) {
338
+ /* 源端的值是object类型,且不是元素节点 */
339
+ target[sourceKeyName] = UtilsContext.assign(targetValue, sourceValue, isAdd);
340
+ continue;
341
+ }
342
+ target[sourceKeyName] = sourceValue;
343
+ }
344
+ }
345
+ else {
346
+ for (const targetKeyName in target) {
347
+ if (targetKeyName in source) {
348
+ let targetValue = target[targetKeyName];
349
+ let sourceValue = source[targetKeyName];
350
+ if (typeof sourceValue === "object" &&
351
+ sourceValue != null &&
352
+ !UtilsContext.isDOM(sourceValue) &&
353
+ Object.keys(sourceValue).length) {
354
+ /* 源端的值是object类型,且不是元素节点 */
355
+ target[targetKeyName] = UtilsContext.assign(targetValue, sourceValue, isAdd);
356
+ continue;
357
+ }
358
+ /* 直接赋值 */
359
+ target[targetKeyName] = sourceValue;
360
+ }
361
+ }
362
+ }
363
+ return target;
364
+ }
365
+ isNull(...args) {
366
+ let result = true;
367
+ let checkList = [...args];
368
+ for (const objItem of checkList) {
369
+ let itemResult = false;
370
+ if (objItem === null || objItem === undefined) {
371
+ itemResult = true;
372
+ }
373
+ else {
374
+ switch (typeof objItem) {
375
+ case "object":
376
+ if (typeof objItem[Symbol.iterator] === "function") {
377
+ /* 可迭代 */
378
+ itemResult = objItem.length === 0;
379
+ }
380
+ else {
381
+ itemResult = Object.keys(objItem).length === 0;
382
+ }
383
+ break;
384
+ case "number":
385
+ itemResult = objItem === 0;
386
+ break;
387
+ case "string":
388
+ itemResult =
389
+ objItem.trim() === "" ||
390
+ objItem === "null" ||
391
+ objItem === "undefined";
392
+ break;
393
+ case "boolean":
394
+ itemResult = !objItem;
395
+ break;
396
+ case "function":
397
+ let funcStr = objItem.toString().replace(/\s/g, "");
398
+ /* 排除()=>{}、(xxx="")=>{}、function(){}、function(xxx=""){} */
399
+ itemResult = Boolean(funcStr.match(/^\(.*?\)=>\{\}$|^function.*?\(.*?\)\{\}$/));
400
+ break;
401
+ }
402
+ }
403
+ result = result && itemResult;
404
+ }
405
+ return result;
406
+ }
407
+ /**
408
+ * 判断对象是否是元素
409
+ * @param target
410
+ * @returns
411
+ * + true 是元素
412
+ * + false 不是元素
413
+ * @example
414
+ * Utils.isDOM(document.querySelector("a"))
415
+ * > true
416
+ */
417
+ isDOM(target) {
418
+ return target instanceof Node;
419
+ }
420
+ isNotNull(...args) {
421
+ let UtilsContext = this;
422
+ return !UtilsContext.isNull.apply(this, args);
423
+ }
424
+ deepClone(obj) {
425
+ let UtilsContext = this;
426
+ if (obj === void 0)
427
+ return void 0;
428
+ if (obj === null)
429
+ return null;
430
+ let clone = obj instanceof Array ? [] : {};
431
+ for (const [key, value] of Object.entries(obj)) {
432
+ clone[key] =
433
+ typeof value === "object" ? UtilsContext.deepClone(value) : value;
434
+ }
435
+ return clone;
436
+ }
437
+ /**
438
+ * 覆盖对象中的函数this指向
439
+ * @param target 需要覆盖的对象
440
+ * @param [objectThis] 覆盖的this指向,如果为传入,则默认为对象本身
441
+ */
442
+ coverObjectFunctionThis(target, objectThis) {
443
+ if (typeof target !== "object" || target === null) {
444
+ throw new Error("target must be object");
445
+ }
446
+ objectThis = objectThis || target;
447
+ Object.keys(target).forEach((key) => {
448
+ if (typeof target[key] === "function") {
449
+ target[key] = target[key].bind(objectThis);
450
+ }
451
+ });
452
+ }
453
+ toJSON(data, errorCallBack) {
454
+ let result = {};
455
+ if (typeof data === "object") {
456
+ return data;
457
+ }
458
+ TryCatch()
459
+ .config({ log: false })
460
+ .error((error) => {
461
+ TryCatch()
462
+ .error(() => {
463
+ try {
464
+ result = new Function("return " + data)();
465
+ }
466
+ catch (error2) {
467
+ if (typeof errorCallBack === "function") {
468
+ errorCallBack(error2);
469
+ }
470
+ }
471
+ })
472
+ .run(() => {
473
+ if (data &&
474
+ /^[\],:{}\s]*$/.test(data
475
+ .replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
476
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
477
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
478
+ result = new Function("return " + data)();
479
+ }
480
+ else {
481
+ if (typeof errorCallBack === "function") {
482
+ errorCallBack(new Error("target is not a JSON"));
483
+ }
484
+ }
485
+ });
486
+ })
487
+ .run(() => {
488
+ data = data.trim();
489
+ result = JSON.parse(data);
490
+ });
491
+ return result;
492
+ }
493
+ }
494
+ let commonUtil = new CommonUtil();
495
+
229
496
  class UtilsGMCookie {
230
497
  windowApi = {
231
498
  window: window,
@@ -254,7 +521,7 @@ define((function () { 'use strict';
254
521
  throw new TypeError("Utils.GMCookie.get 参数cookieName 必须为字符串");
255
522
  }
256
523
  let cookies = this.getCookiesList();
257
- let findValue = undefined;
524
+ let findValue = void 0;
258
525
  for (const cookieItem of cookies) {
259
526
  let item = cookieItem.trim();
260
527
  let itemSplit = item.split("=");
@@ -298,7 +565,7 @@ define((function () { 'use strict';
298
565
  name: "",
299
566
  path: "/",
300
567
  };
301
- defaultOption = utils.assign(defaultOption, option);
568
+ defaultOption = commonUtil.assign(defaultOption, option);
302
569
  let cookies = this.getCookiesList();
303
570
  cookies.forEach((item) => {
304
571
  item = item.trim();
@@ -349,7 +616,7 @@ define((function () { 'use strict';
349
616
  name: "",
350
617
  path: "/",
351
618
  };
352
- defaultOption = utils.assign(defaultOption, option);
619
+ defaultOption = commonUtil.assign(defaultOption, option);
353
620
  let cookies = this.getCookiesList();
354
621
  cookies.forEach((item) => {
355
622
  item = item.trim();
@@ -398,7 +665,7 @@ define((function () { 'use strict';
398
665
  */
399
666
  expirationDate: Math.floor(Date.now()) + 60 * 60 * 24 * 30,
400
667
  };
401
- defaultOption = utils.assign(defaultOption, option);
668
+ defaultOption = commonUtil.assign(defaultOption, option);
402
669
  let life = defaultOption.expirationDate
403
670
  ? defaultOption.expirationDate
404
671
  : Math.floor(Date.now()) + 60 * 60 * 24 * 30;
@@ -408,7 +675,7 @@ define((function () { 'use strict';
408
675
  ";expires=" +
409
676
  new Date(life).toGMTString() +
410
677
  "; path=/";
411
- if (utils.isNotNull(defaultOption.domain)) {
678
+ if (commonUtil.isNull(defaultOption.domain)) {
412
679
  cookieStr += "; domain=" + defaultOption.domain;
413
680
  }
414
681
  this.windowApi.document.cookie = cookieStr;
@@ -436,9 +703,9 @@ define((function () { 'use strict';
436
703
  path: "/",
437
704
  firstPartyDomain: "",
438
705
  };
439
- defaultOption = utils.assign(defaultOption, option);
706
+ defaultOption = commonUtil.assign(defaultOption, option);
440
707
  let cookieStr = `${defaultOption.name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${defaultOption.path}`;
441
- if (utils.isNotNull(defaultOption.firstPartyDomain)) {
708
+ if (commonUtil.isNull(defaultOption.firstPartyDomain)) {
442
709
  cookieStr += `; domain=${defaultOption.firstPartyDomain};`;
443
710
  }
444
711
  this.windowApi.document.cookie = cookieStr;
@@ -478,189 +745,189 @@ define((function () { 'use strict';
478
745
  }
479
746
  }
480
747
 
748
+ // ==UserScript==
481
749
  // @name ajaxHooker
482
750
  // @author cxxjackie
483
- // @version 1.4.4
484
- // @updateLog 修复头条、抖音部分站点下this引用错误的问题。
751
+ // @version 1.4.6
485
752
  // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
753
+ // @license GNU LGPL-3.0
754
+ // ==/UserScript==
486
755
 
487
- const AjaxHooker = function () {
488
- return (function () {
489
- const version = "1.4.4";
490
- const hookInst = {
491
- hookFns: [],
492
- filters: [],
493
- };
494
- const win = window.unsafeWindow || document.defaultView || window;
495
- let winAh = win.__ajaxHooker;
496
- const resProto = win.Response.prototype;
497
- const xhrResponses = ["response", "responseText", "responseXML"];
498
- const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
499
- const fetchInitProps = [
500
- "method",
501
- "headers",
502
- "body",
503
- "mode",
504
- "credentials",
505
- "cache",
506
- "redirect",
507
- "referrer",
508
- "referrerPolicy",
509
- "integrity",
510
- "keepalive",
511
- "signal",
512
- "priority",
513
- ];
514
- const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
515
- const getType = {}.toString.call.bind({}.toString);
516
- const getDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
517
- const emptyFn = () => {};
518
- const errorFn = (e) => console.error(e);
519
- function isThenable(obj) {
520
- return (
521
- obj &&
522
- ["object", "function"].includes(typeof obj) &&
523
- typeof obj.then === "function"
524
- );
525
- }
526
- function catchError(fn, ...args) {
527
- try {
528
- const result = fn(...args);
529
- if (isThenable(result)) return result.then(null, errorFn);
530
- return result;
531
- } catch (err) {
532
- console.error(err);
533
- }
534
- }
535
- function defineProp(obj, prop, getter, setter) {
536
- Object.defineProperty(obj, prop, {
537
- configurable: true,
538
- enumerable: true,
539
- get: getter,
540
- set: setter,
541
- });
542
- }
543
- function readonly(obj, prop, value = obj[prop]) {
544
- defineProp(obj, prop, () => value, emptyFn);
545
- }
546
- function writable(obj, prop, value = obj[prop]) {
547
- Object.defineProperty(obj, prop, {
548
- configurable: true,
549
- enumerable: true,
550
- writable: true,
551
- value: value,
552
- });
756
+ const ajaxHooker = function () {
757
+ const version = "1.4.6";
758
+ const hookInst = {
759
+ hookFns: [],
760
+ filters: [],
761
+ };
762
+ const win = window.unsafeWindow || document.defaultView || window;
763
+ let winAh = win.__ajaxHooker;
764
+ const resProto = win.Response.prototype;
765
+ const xhrResponses = ["response", "responseText", "responseXML"];
766
+ const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
767
+ const fetchInitProps = [
768
+ "method",
769
+ "headers",
770
+ "body",
771
+ "mode",
772
+ "credentials",
773
+ "cache",
774
+ "redirect",
775
+ "referrer",
776
+ "referrerPolicy",
777
+ "integrity",
778
+ "keepalive",
779
+ "signal",
780
+ "priority",
781
+ ];
782
+ const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
783
+ const getType = {}.toString.call.bind({}.toString);
784
+ const getDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
785
+ const emptyFn = () => {};
786
+ const errorFn = (e) => console.error(e);
787
+ function isThenable(obj) {
788
+ return (
789
+ obj &&
790
+ ["object", "function"].includes(typeof obj) &&
791
+ typeof obj.then === "function"
792
+ );
793
+ }
794
+ function catchError(fn, ...args) {
795
+ try {
796
+ const result = fn(...args);
797
+ if (isThenable(result)) return result.then(null, errorFn);
798
+ return result;
799
+ } catch (err) {
800
+ console.error(err);
553
801
  }
554
- function parseHeaders(obj) {
555
- const headers = {};
556
- switch (getType(obj)) {
557
- case "[object String]":
558
- for (const line of obj.trim().split(/[\r\n]+/)) {
559
- const [header, value] = line.split(/\s*:\s*/);
560
- if (!header) break;
561
- const lheader = header.toLowerCase();
562
- headers[lheader] =
563
- lheader in headers ? `${headers[lheader]}, ${value}` : value;
564
- }
565
- break;
566
- case "[object Headers]":
567
- for (const [key, val] of obj) {
568
- headers[key] = val;
569
- }
570
- break;
571
- case "[object Object]":
572
- return { ...obj };
573
- }
574
- return headers;
802
+ }
803
+ function defineProp(obj, prop, getter, setter) {
804
+ Object.defineProperty(obj, prop, {
805
+ configurable: true,
806
+ enumerable: true,
807
+ get: getter,
808
+ set: setter,
809
+ });
810
+ }
811
+ function readonly(obj, prop, value = obj[prop]) {
812
+ defineProp(obj, prop, () => value, emptyFn);
813
+ }
814
+ function writable(obj, prop, value = obj[prop]) {
815
+ Object.defineProperty(obj, prop, {
816
+ configurable: true,
817
+ enumerable: true,
818
+ writable: true,
819
+ value: value,
820
+ });
821
+ }
822
+ function parseHeaders(obj) {
823
+ const headers = {};
824
+ switch (getType(obj)) {
825
+ case "[object String]":
826
+ for (const line of obj.trim().split(/[\r\n]+/)) {
827
+ const [header, value] = line.split(/(?<=^[^:]+)\s*:\s*/);
828
+ if (!value) continue;
829
+ const lheader = header.toLowerCase();
830
+ headers[lheader] =
831
+ lheader in headers ? `${headers[lheader]}, ${value}` : value;
832
+ }
833
+ break;
834
+ case "[object Headers]":
835
+ for (const [key, val] of obj) {
836
+ headers[key] = val;
837
+ }
838
+ break;
839
+ case "[object Object]":
840
+ return { ...obj };
841
+ }
842
+ return headers;
843
+ }
844
+ function stopImmediatePropagation() {
845
+ this.ajaxHooker_isStopped = true;
846
+ }
847
+ class SyncThenable {
848
+ then(fn) {
849
+ fn && fn();
850
+ return new SyncThenable();
851
+ }
852
+ }
853
+ class AHRequest {
854
+ constructor(request) {
855
+ this.request = request;
856
+ this.requestClone = { ...this.request };
575
857
  }
576
- function stopImmediatePropagation() {
577
- this.ajaxHooker_isStopped = true;
858
+ shouldFilter(filters) {
859
+ const { type, url, method, async } = this.request;
860
+ return (
861
+ filters.length &&
862
+ !filters.find((obj) => {
863
+ switch (true) {
864
+ case obj.type && obj.type !== type:
865
+ case getType(obj.url) === "[object String]" &&
866
+ !url.includes(obj.url):
867
+ case getType(obj.url) === "[object RegExp]" && !obj.url.test(url):
868
+ case obj.method &&
869
+ obj.method.toUpperCase() !== method.toUpperCase():
870
+ case "async" in obj && obj.async !== async:
871
+ return false;
872
+ }
873
+ return true;
874
+ })
875
+ );
578
876
  }
579
- class SyncThenable {
580
- then(fn) {
581
- fn && fn();
877
+ waitForRequestKeys() {
878
+ const requestKeys = ["url", "method", "abort", "headers", "data"];
879
+ if (!this.request.async) {
880
+ win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
881
+ if (this.shouldFilter(filters)) return;
882
+ hookFns.forEach((fn) => {
883
+ if (getType(fn) === "[object Function]")
884
+ catchError(fn, this.request);
885
+ });
886
+ requestKeys.forEach((key) => {
887
+ if (isThenable(this.request[key]))
888
+ this.request[key] = this.requestClone[key];
889
+ });
890
+ });
582
891
  return new SyncThenable();
583
892
  }
893
+ const promises = [];
894
+ win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
895
+ if (this.shouldFilter(filters)) return;
896
+ promises.push(
897
+ Promise.all(hookFns.map((fn) => catchError(fn, this.request))).then(
898
+ () =>
899
+ Promise.all(
900
+ requestKeys.map((key) =>
901
+ Promise.resolve(this.request[key]).then(
902
+ (val) => (this.request[key] = val),
903
+ () => (this.request[key] = this.requestClone[key])
904
+ )
905
+ )
906
+ )
907
+ )
908
+ );
909
+ });
910
+ return Promise.all(promises);
584
911
  }
585
- class AHRequest {
586
- constructor(request) {
587
- this.request = request;
588
- this.requestClone = { ...this.request };
589
- }
590
- shouldFilter(filters) {
591
- const { type, url, method, async } = this.request;
592
- return (
593
- filters.length &&
594
- !filters.find((obj) => {
595
- switch (true) {
596
- case obj.type && obj.type !== type:
597
- case getType(obj.url) === "[object String]" &&
598
- !url.includes(obj.url):
599
- case getType(obj.url) === "[object RegExp]" && !obj.url.test(url):
600
- case obj.method &&
601
- obj.method.toUpperCase() !== method.toUpperCase():
602
- case "async" in obj && obj.async !== async:
603
- return false;
912
+ waitForResponseKeys(response) {
913
+ const responseKeys =
914
+ this.request.type === "xhr" ? xhrResponses : fetchResponses;
915
+ if (!this.request.async) {
916
+ if (getType(this.request.response) === "[object Function]") {
917
+ catchError(this.request.response, response);
918
+ responseKeys.forEach((key) => {
919
+ if (
920
+ "get" in getDescriptor(response, key) ||
921
+ isThenable(response[key])
922
+ ) {
923
+ delete response[key];
604
924
  }
605
- return true;
606
- })
607
- );
608
- }
609
- waitForRequestKeys() {
610
- const requestKeys = ["url", "method", "abort", "headers", "data"];
611
- if (!this.request.async) {
612
- win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
613
- if (this.shouldFilter(filters)) return;
614
- hookFns.forEach((fn) => {
615
- if (getType(fn) === "[object Function]")
616
- catchError(fn, this.request);
617
- });
618
- requestKeys.forEach((key) => {
619
- if (isThenable(this.request[key]))
620
- this.request[key] = this.requestClone[key];
621
- });
622
925
  });
623
- return new SyncThenable();
624
926
  }
625
- const promises = [];
626
- win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
627
- if (this.shouldFilter(filters)) return;
628
- promises.push(
629
- Promise.all(hookFns.map((fn) => catchError(fn, this.request))).then(
630
- () =>
631
- Promise.all(
632
- requestKeys.map((key) =>
633
- Promise.resolve(this.request[key]).then(
634
- (val) => (this.request[key] = val),
635
- () => (this.request[key] = this.requestClone[key])
636
- )
637
- )
638
- )
639
- )
640
- );
641
- });
642
- return Promise.all(promises);
927
+ return new SyncThenable();
643
928
  }
644
- waitForResponseKeys(response) {
645
- const responseKeys =
646
- this.request.type === "xhr" ? xhrResponses : fetchResponses;
647
- if (!this.request.async) {
648
- if (getType(this.request.response) === "[object Function]") {
649
- catchError(this.request.response, response);
650
- responseKeys.forEach((key) => {
651
- if (
652
- "get" in getDescriptor(response, key) ||
653
- isThenable(response[key])
654
- ) {
655
- delete response[key];
656
- }
657
- });
658
- }
659
- return new SyncThenable();
660
- }
661
- return Promise.resolve(
662
- catchError(this.request.response, response)
663
- ).then(() =>
929
+ return Promise.resolve(catchError(this.request.response, response)).then(
930
+ () =>
664
931
  Promise.all(
665
932
  responseKeys.map((key) => {
666
933
  const descriptor = getDescriptor(response, key);
@@ -674,424 +941,406 @@ define((function () { 'use strict';
674
941
  }
675
942
  })
676
943
  )
677
- );
678
- }
944
+ );
679
945
  }
680
- const proxyHandler = {
681
- get(target, prop) {
682
- const descriptor = getDescriptor(target, prop);
683
- if (
684
- descriptor &&
685
- !descriptor.configurable &&
686
- !descriptor.writable &&
687
- !descriptor.get
688
- )
689
- return target[prop];
690
- const ah = target.__ajaxHooker;
691
- if (ah && ah.proxyProps) {
692
- if (prop in ah.proxyProps) {
693
- const pDescriptor = ah.proxyProps[prop];
694
- if ("get" in pDescriptor) return pDescriptor.get();
695
- if (typeof pDescriptor.value === "function")
696
- return pDescriptor.value.bind(ah);
697
- return pDescriptor.value;
698
- }
699
- if (typeof target[prop] === "function")
700
- return target[prop].bind(target);
701
- }
946
+ }
947
+ const proxyHandler = {
948
+ get(target, prop) {
949
+ const descriptor = getDescriptor(target, prop);
950
+ if (
951
+ descriptor &&
952
+ !descriptor.configurable &&
953
+ !descriptor.writable &&
954
+ !descriptor.get
955
+ )
702
956
  return target[prop];
703
- },
704
- set(target, prop, value) {
705
- const descriptor = getDescriptor(target, prop);
706
- if (
707
- descriptor &&
708
- !descriptor.configurable &&
709
- !descriptor.writable &&
710
- !descriptor.set
711
- )
712
- return true;
713
- const ah = target.__ajaxHooker;
714
- if (ah && ah.proxyProps && prop in ah.proxyProps) {
957
+ const ah = target.__ajaxHooker;
958
+ if (ah && ah.proxyProps) {
959
+ if (prop in ah.proxyProps) {
715
960
  const pDescriptor = ah.proxyProps[prop];
716
- pDescriptor.set
717
- ? pDescriptor.set(value)
718
- : (pDescriptor.value = value);
719
- } else {
720
- target[prop] = value;
721
- }
722
- return true;
723
- },
724
- };
725
- class XhrHooker {
726
- constructor(xhr) {
727
- const ah = this;
728
- Object.assign(ah, {
729
- originalXhr: xhr,
730
- proxyXhr: new Proxy(xhr, proxyHandler),
731
- resThenable: new SyncThenable(),
732
- proxyProps: {},
733
- proxyEvents: {},
734
- });
735
- xhr.addEventListener("readystatechange", (e) => {
736
- if (
737
- ah.proxyXhr.readyState === 4 &&
738
- ah.request &&
739
- typeof ah.request.response === "function"
740
- ) {
741
- const response = {
742
- finalUrl: ah.proxyXhr.responseURL,
743
- status: ah.proxyXhr.status,
744
- responseHeaders: parseHeaders(
745
- ah.proxyXhr.getAllResponseHeaders()
746
- ),
747
- };
748
- const tempValues = {};
749
- for (const key of xhrResponses) {
750
- try {
751
- tempValues[key] = ah.originalXhr[key];
752
- } catch (err) {}
753
- defineProp(
754
- response,
755
- key,
756
- () => {
757
- return (response[key] = tempValues[key]);
758
- },
759
- (val) => {
760
- delete response[key];
761
- response[key] = val;
762
- }
763
- );
764
- }
765
- ah.resThenable = new AHRequest(ah.request)
766
- .waitForResponseKeys(response)
767
- .then(() => {
768
- for (const key of xhrResponses) {
769
- ah.proxyProps[key] = {
770
- get: () => {
771
- if (!(key in response)) response[key] = tempValues[key];
772
- return response[key];
773
- },
774
- };
775
- }
776
- });
777
- }
778
- ah.dispatchEvent(e);
779
- });
780
- xhr.addEventListener("load", (e) => ah.dispatchEvent(e));
781
- xhr.addEventListener("loadend", (e) => ah.dispatchEvent(e));
782
- for (const evt of xhrAsyncEvents) {
783
- const onEvt = "on" + evt;
784
- ah.proxyProps[onEvt] = {
785
- get: () => ah.proxyEvents[onEvt] || null,
786
- set: (val) => ah.addEvent(onEvt, val),
787
- };
788
- }
789
- for (const method of [
790
- "setRequestHeader",
791
- "addEventListener",
792
- "removeEventListener",
793
- "open",
794
- "send",
795
- ]) {
796
- ah.proxyProps[method] = { value: ah[method] };
797
- }
798
- }
799
- toJSON() {} // Converting circular structure to JSON
800
- addEvent(type, event) {
801
- if (type.startsWith("on")) {
802
- this.proxyEvents[type] = typeof event === "function" ? event : null;
803
- } else {
804
- if (typeof event === "object" && event !== null)
805
- event = event.handleEvent;
806
- if (typeof event !== "function") return;
807
- this.proxyEvents[type] = this.proxyEvents[type] || new Set();
808
- this.proxyEvents[type].add(event);
961
+ if ("get" in pDescriptor) return pDescriptor.get();
962
+ if (typeof pDescriptor.value === "function")
963
+ return pDescriptor.value.bind(ah);
964
+ return pDescriptor.value;
809
965
  }
966
+ if (typeof target[prop] === "function")
967
+ return target[prop].bind(target);
810
968
  }
811
- removeEvent(type, event) {
812
- if (type.startsWith("on")) {
813
- this.proxyEvents[type] = null;
814
- } else {
815
- if (typeof event === "object" && event !== null)
816
- event = event.handleEvent;
817
- this.proxyEvents[type] && this.proxyEvents[type].delete(event);
818
- }
969
+ return target[prop];
970
+ },
971
+ set(target, prop, value) {
972
+ const descriptor = getDescriptor(target, prop);
973
+ if (
974
+ descriptor &&
975
+ !descriptor.configurable &&
976
+ !descriptor.writable &&
977
+ !descriptor.set
978
+ )
979
+ return true;
980
+ const ah = target.__ajaxHooker;
981
+ if (ah && ah.proxyProps && prop in ah.proxyProps) {
982
+ const pDescriptor = ah.proxyProps[prop];
983
+ pDescriptor.set ? pDescriptor.set(value) : (pDescriptor.value = value);
984
+ } else {
985
+ target[prop] = value;
819
986
  }
820
- dispatchEvent(e) {
821
- e.stopImmediatePropagation = stopImmediatePropagation;
822
- defineProp(e, "target", () => this.proxyXhr);
823
- defineProp(e, "currentTarget", () => this.proxyXhr);
824
- this.proxyEvents[e.type] &&
825
- this.proxyEvents[e.type].forEach((fn) => {
826
- this.resThenable.then(
827
- () => !e.ajaxHooker_isStopped && fn.call(this.proxyXhr, e)
987
+ return true;
988
+ },
989
+ };
990
+ class XhrHooker {
991
+ constructor(xhr) {
992
+ const ah = this;
993
+ Object.assign(ah, {
994
+ originalXhr: xhr,
995
+ proxyXhr: new Proxy(xhr, proxyHandler),
996
+ resThenable: new SyncThenable(),
997
+ proxyProps: {},
998
+ proxyEvents: {},
999
+ });
1000
+ xhr.addEventListener("readystatechange", (e) => {
1001
+ if (
1002
+ ah.proxyXhr.readyState === 4 &&
1003
+ ah.request &&
1004
+ typeof ah.request.response === "function"
1005
+ ) {
1006
+ const response = {
1007
+ finalUrl: ah.proxyXhr.responseURL,
1008
+ status: ah.proxyXhr.status,
1009
+ responseHeaders: parseHeaders(ah.proxyXhr.getAllResponseHeaders()),
1010
+ };
1011
+ const tempValues = {};
1012
+ for (const key of xhrResponses) {
1013
+ try {
1014
+ tempValues[key] = ah.originalXhr[key];
1015
+ } catch (err) {}
1016
+ defineProp(
1017
+ response,
1018
+ key,
1019
+ () => {
1020
+ return (response[key] = tempValues[key]);
1021
+ },
1022
+ (val) => {
1023
+ delete response[key];
1024
+ response[key] = val;
1025
+ }
828
1026
  );
829
- });
830
- if (e.ajaxHooker_isStopped) return;
831
- const onEvent = this.proxyEvents["on" + e.type];
832
- onEvent && this.resThenable.then(onEvent.bind(this.proxyXhr, e));
1027
+ }
1028
+ ah.resThenable = new AHRequest(ah.request)
1029
+ .waitForResponseKeys(response)
1030
+ .then(() => {
1031
+ for (const key of xhrResponses) {
1032
+ ah.proxyProps[key] = {
1033
+ get: () => {
1034
+ if (!(key in response)) response[key] = tempValues[key];
1035
+ return response[key];
1036
+ },
1037
+ };
1038
+ }
1039
+ });
1040
+ }
1041
+ ah.dispatchEvent(e);
1042
+ });
1043
+ xhr.addEventListener("load", (e) => ah.dispatchEvent(e));
1044
+ xhr.addEventListener("loadend", (e) => ah.dispatchEvent(e));
1045
+ for (const evt of xhrAsyncEvents) {
1046
+ const onEvt = "on" + evt;
1047
+ ah.proxyProps[onEvt] = {
1048
+ get: () => ah.proxyEvents[onEvt] || null,
1049
+ set: (val) => ah.addEvent(onEvt, val),
1050
+ };
833
1051
  }
834
- setRequestHeader(header, value) {
835
- this.originalXhr.setRequestHeader(header, value);
836
- if (!this.request) return;
837
- const headers = this.request.headers;
838
- headers[header] =
839
- header in headers ? `${headers[header]}, ${value}` : value;
1052
+ for (const method of [
1053
+ "setRequestHeader",
1054
+ "addEventListener",
1055
+ "removeEventListener",
1056
+ "open",
1057
+ "send",
1058
+ ]) {
1059
+ ah.proxyProps[method] = { value: ah[method] };
840
1060
  }
841
- addEventListener(...args) {
842
- if (xhrAsyncEvents.includes(args[0])) {
843
- this.addEvent(args[0], args[1]);
844
- } else {
845
- this.originalXhr.addEventListener(...args);
846
- }
1061
+ }
1062
+ toJSON() {} // Converting circular structure to JSON
1063
+ addEvent(type, event) {
1064
+ if (type.startsWith("on")) {
1065
+ this.proxyEvents[type] = typeof event === "function" ? event : null;
1066
+ } else {
1067
+ if (typeof event === "object" && event !== null)
1068
+ event = event.handleEvent;
1069
+ if (typeof event !== "function") return;
1070
+ this.proxyEvents[type] = this.proxyEvents[type] || new Set();
1071
+ this.proxyEvents[type].add(event);
847
1072
  }
848
- removeEventListener(...args) {
849
- if (xhrAsyncEvents.includes(args[0])) {
850
- this.removeEvent(args[0], args[1]);
851
- } else {
852
- this.originalXhr.removeEventListener(...args);
853
- }
1073
+ }
1074
+ removeEvent(type, event) {
1075
+ if (type.startsWith("on")) {
1076
+ this.proxyEvents[type] = null;
1077
+ } else {
1078
+ if (typeof event === "object" && event !== null)
1079
+ event = event.handleEvent;
1080
+ this.proxyEvents[type] && this.proxyEvents[type].delete(event);
854
1081
  }
855
- open(method, url, async = true, ...args) {
856
- this.request = {
857
- type: "xhr",
858
- url: url.toString(),
859
- method: method.toUpperCase(),
860
- abort: false,
861
- headers: {},
862
- data: null,
863
- response: null,
864
- async: !!async,
865
- };
866
- this.openArgs = args;
867
- this.resThenable = new SyncThenable();
868
- [
869
- "responseURL",
870
- "readyState",
871
- "status",
872
- "statusText",
873
- ...xhrResponses,
874
- ].forEach((key) => {
875
- delete this.proxyProps[key];
1082
+ }
1083
+ dispatchEvent(e) {
1084
+ e.stopImmediatePropagation = stopImmediatePropagation;
1085
+ defineProp(e, "target", () => this.proxyXhr);
1086
+ defineProp(e, "currentTarget", () => this.proxyXhr);
1087
+ this.proxyEvents[e.type] &&
1088
+ this.proxyEvents[e.type].forEach((fn) => {
1089
+ this.resThenable.then(
1090
+ () => !e.ajaxHooker_isStopped && fn.call(this.proxyXhr, e)
1091
+ );
876
1092
  });
877
- return this.originalXhr.open(method, url, async, ...args);
1093
+ if (e.ajaxHooker_isStopped) return;
1094
+ const onEvent = this.proxyEvents["on" + e.type];
1095
+ onEvent && this.resThenable.then(onEvent.bind(this.proxyXhr, e));
1096
+ }
1097
+ setRequestHeader(header, value) {
1098
+ this.originalXhr.setRequestHeader(header, value);
1099
+ if (!this.request) return;
1100
+ const headers = this.request.headers;
1101
+ headers[header] =
1102
+ header in headers ? `${headers[header]}, ${value}` : value;
1103
+ }
1104
+ addEventListener(...args) {
1105
+ if (xhrAsyncEvents.includes(args[0])) {
1106
+ this.addEvent(args[0], args[1]);
1107
+ } else {
1108
+ this.originalXhr.addEventListener(...args);
878
1109
  }
879
- send(data) {
880
- const ah = this;
881
- const xhr = ah.originalXhr;
882
- const request = ah.request;
883
- if (!request) return xhr.send(data);
884
- request.data = data;
885
- new AHRequest(request).waitForRequestKeys().then(() => {
886
- if (request.abort) {
887
- if (typeof request.response === "function") {
888
- Object.assign(ah.proxyProps, {
889
- responseURL: { value: request.url },
890
- readyState: { value: 4 },
891
- status: { value: 200 },
892
- statusText: { value: "OK" },
893
- });
894
- xhrAsyncEvents.forEach((evt) =>
895
- xhr.dispatchEvent(new Event(evt))
896
- );
897
- }
898
- } else {
899
- xhr.open(
900
- request.method,
901
- request.url,
902
- request.async,
903
- ...ah.openArgs
904
- );
905
- for (const header in request.headers) {
906
- xhr.setRequestHeader(header, request.headers[header]);
907
- }
908
- xhr.send(request.data);
909
- }
910
- });
1110
+ }
1111
+ removeEventListener(...args) {
1112
+ if (xhrAsyncEvents.includes(args[0])) {
1113
+ this.removeEvent(args[0], args[1]);
1114
+ } else {
1115
+ this.originalXhr.removeEventListener(...args);
911
1116
  }
912
1117
  }
913
- function fakeXHR() {
914
- const xhr = new winAh.realXHR();
915
- if ("__ajaxHooker" in xhr)
916
- console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
917
- xhr.__ajaxHooker = new XhrHooker(xhr);
918
- return xhr.__ajaxHooker.proxyXhr;
1118
+ open(method, url, async = true, ...args) {
1119
+ this.request = {
1120
+ type: "xhr",
1121
+ url: url.toString(),
1122
+ method: method.toUpperCase(),
1123
+ abort: false,
1124
+ headers: {},
1125
+ data: null,
1126
+ response: null,
1127
+ async: !!async,
1128
+ };
1129
+ this.openArgs = args;
1130
+ this.resThenable = new SyncThenable();
1131
+ [
1132
+ "responseURL",
1133
+ "readyState",
1134
+ "status",
1135
+ "statusText",
1136
+ ...xhrResponses,
1137
+ ].forEach((key) => {
1138
+ delete this.proxyProps[key];
1139
+ });
1140
+ return this.originalXhr.open(method, url, async, ...args);
919
1141
  }
920
- fakeXHR.prototype = win.XMLHttpRequest.prototype;
921
- Object.keys(win.XMLHttpRequest).forEach(
922
- (key) => (fakeXHR[key] = win.XMLHttpRequest[key])
923
- );
924
- function fakeFetch(url, options = {}) {
925
- if (!url) return winAh.realFetch.call(win, url, options);
926
- return new Promise(async (resolve, reject) => {
927
- const init = {};
928
- if (getType(url) === "[object Request]") {
929
- for (const prop of fetchInitProps) init[prop] = url[prop];
930
- if (url.body) init.body = await url.arrayBuffer();
931
- url = url.url;
932
- }
933
- url = url.toString();
934
- Object.assign(init, options);
935
- init.method = init.method || "GET";
936
- init.headers = init.headers || {};
937
- const request = {
938
- type: "fetch",
939
- url: url,
940
- method: init.method.toUpperCase(),
941
- abort: false,
942
- headers: parseHeaders(init.headers),
943
- data: init.body,
944
- response: null,
945
- async: true,
946
- };
947
- const req = new AHRequest(request);
948
- await req.waitForRequestKeys();
1142
+ send(data) {
1143
+ const ah = this;
1144
+ const xhr = ah.originalXhr;
1145
+ const request = ah.request;
1146
+ if (!request) return xhr.send(data);
1147
+ request.data = data;
1148
+ new AHRequest(request).waitForRequestKeys().then(() => {
949
1149
  if (request.abort) {
950
1150
  if (typeof request.response === "function") {
951
- const response = {
952
- finalUrl: request.url,
953
- status: 200,
954
- responseHeaders: {},
955
- };
956
- await req.waitForResponseKeys(response);
957
- const key = fetchResponses.find((k) => k in response);
958
- let val = response[key];
959
- if (key === "json" && typeof val === "object") {
960
- val = catchError(JSON.stringify.bind(JSON), val);
961
- }
962
- const res = new Response(val, {
963
- status: 200,
964
- statusText: "OK",
1151
+ Object.assign(ah.proxyProps, {
1152
+ responseURL: { value: request.url },
1153
+ readyState: { value: 4 },
1154
+ status: { value: 200 },
1155
+ statusText: { value: "OK" },
965
1156
  });
966
- defineProp(res, "type", () => "basic");
967
- defineProp(res, "url", () => request.url);
968
- resolve(res);
969
- } else {
970
- reject(new DOMException("aborted", "AbortError"));
1157
+ xhrAsyncEvents.forEach((evt) => xhr.dispatchEvent(new Event(evt)));
971
1158
  }
972
- return;
973
- }
974
- init.method = request.method;
975
- init.headers = request.headers;
976
- init.body = request.data;
977
- winAh.realFetch.call(win, request.url, init).then((res) => {
978
- if (typeof request.response === "function") {
979
- const response = {
980
- finalUrl: res.url,
981
- status: res.status,
982
- responseHeaders: parseHeaders(res.headers),
983
- };
984
- fetchResponses.forEach(
985
- (key) =>
986
- (res[key] = function () {
987
- if (key in response) return Promise.resolve(response[key]);
988
- return resProto[key].call(this).then((val) => {
989
- response[key] = val;
990
- return req
991
- .waitForResponseKeys(response)
992
- .then(() => (key in response ? response[key] : val));
993
- });
994
- })
995
- );
1159
+ } else {
1160
+ xhr.open(request.method, request.url, request.async, ...ah.openArgs);
1161
+ for (const header in request.headers) {
1162
+ xhr.setRequestHeader(header, request.headers[header]);
996
1163
  }
997
- resolve(res);
998
- }, reject);
1164
+ xhr.send(request.data);
1165
+ }
999
1166
  });
1000
1167
  }
1001
- function fakeFetchClone() {
1002
- const descriptors = Object.getOwnPropertyDescriptors(this);
1003
- const res = winAh.realFetchClone.call(this);
1004
- Object.defineProperties(res, descriptors);
1005
- return res;
1006
- }
1007
- winAh = win.__ajaxHooker = winAh || {
1008
- version,
1009
- fakeXHR,
1010
- fakeFetch,
1011
- fakeFetchClone,
1012
- realXHR: win.XMLHttpRequest,
1013
- realFetch: win.fetch,
1014
- realFetchClone: resProto.clone,
1015
- hookInsts: new Set(),
1016
- };
1017
- if (winAh.version !== version)
1168
+ }
1169
+ function fakeXHR() {
1170
+ const xhr = new winAh.realXHR();
1171
+ if ("__ajaxHooker" in xhr)
1018
1172
  console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1019
- win.XMLHttpRequest = winAh.fakeXHR;
1020
- win.fetch = winAh.fakeFetch;
1021
- resProto.clone = winAh.fakeFetchClone;
1022
- winAh.hookInsts.add(hookInst);
1023
- // 针对头条、抖音 secsdk.umd.js 的兼容性处理
1024
- class AHFunction {
1025
- call(thisArg, ...args) {
1026
- if (
1027
- thisArg &&
1028
- thisArg.__ajaxHooker &&
1029
- thisArg.__ajaxHooker.proxyXhr === thisArg
1030
- ) {
1031
- thisArg = thisArg.__ajaxHooker.originalXhr;
1173
+ xhr.__ajaxHooker = new XhrHooker(xhr);
1174
+ return xhr.__ajaxHooker.proxyXhr;
1175
+ }
1176
+ fakeXHR.prototype = win.XMLHttpRequest.prototype;
1177
+ Object.keys(win.XMLHttpRequest).forEach(
1178
+ (key) => (fakeXHR[key] = win.XMLHttpRequest[key])
1179
+ );
1180
+ function fakeFetch(url, options = {}) {
1181
+ if (!url) return winAh.realFetch.call(win, url, options);
1182
+ return new Promise(async (resolve, reject) => {
1183
+ const init = {};
1184
+ if (getType(url) === "[object Request]") {
1185
+ for (const prop of fetchInitProps) init[prop] = url[prop];
1186
+ if (url.body) init.body = await url.arrayBuffer();
1187
+ url = url.url;
1188
+ }
1189
+ url = url.toString();
1190
+ Object.assign(init, options);
1191
+ init.method = init.method || "GET";
1192
+ init.headers = init.headers || {};
1193
+ const request = {
1194
+ type: "fetch",
1195
+ url: url,
1196
+ method: init.method.toUpperCase(),
1197
+ abort: false,
1198
+ headers: parseHeaders(init.headers),
1199
+ data: init.body,
1200
+ response: null,
1201
+ async: true,
1202
+ };
1203
+ const req = new AHRequest(request);
1204
+ await req.waitForRequestKeys();
1205
+ if (request.abort) {
1206
+ if (typeof request.response === "function") {
1207
+ const response = {
1208
+ finalUrl: request.url,
1209
+ status: 200,
1210
+ responseHeaders: {},
1211
+ };
1212
+ await req.waitForResponseKeys(response);
1213
+ const key = fetchResponses.find((k) => k in response);
1214
+ let val = response[key];
1215
+ if (key === "json" && typeof val === "object") {
1216
+ val = catchError(JSON.stringify.bind(JSON), val);
1217
+ }
1218
+ const res = new Response(val, {
1219
+ status: 200,
1220
+ statusText: "OK",
1221
+ });
1222
+ defineProp(res, "type", () => "basic");
1223
+ defineProp(res, "url", () => request.url);
1224
+ resolve(res);
1225
+ } else {
1226
+ reject(new DOMException("aborted", "AbortError"));
1032
1227
  }
1033
- return Reflect.apply(this, thisArg, args);
1228
+ return;
1034
1229
  }
1035
- apply(thisArg, args) {
1036
- if (
1037
- thisArg &&
1038
- thisArg.__ajaxHooker &&
1039
- thisArg.__ajaxHooker.proxyXhr === thisArg
1040
- ) {
1041
- thisArg = thisArg.__ajaxHooker.originalXhr;
1230
+ init.method = request.method;
1231
+ init.headers = request.headers;
1232
+ init.body = request.data;
1233
+ winAh.realFetch.call(win, request.url, init).then((res) => {
1234
+ if (typeof request.response === "function") {
1235
+ const response = {
1236
+ finalUrl: res.url,
1237
+ status: res.status,
1238
+ responseHeaders: parseHeaders(res.headers),
1239
+ };
1240
+ fetchResponses.forEach(
1241
+ (key) =>
1242
+ (res[key] = function () {
1243
+ if (key in response) return Promise.resolve(response[key]);
1244
+ return resProto[key].call(this).then((val) => {
1245
+ response[key] = val;
1246
+ return req
1247
+ .waitForResponseKeys(response)
1248
+ .then(() => (key in response ? response[key] : val));
1249
+ });
1250
+ })
1251
+ );
1042
1252
  }
1043
- return Reflect.apply(this, thisArg, args || []);
1253
+ resolve(res);
1254
+ }, reject);
1255
+ });
1256
+ }
1257
+ function fakeFetchClone() {
1258
+ const descriptors = Object.getOwnPropertyDescriptors(this);
1259
+ const res = winAh.realFetchClone.call(this);
1260
+ Object.defineProperties(res, descriptors);
1261
+ return res;
1262
+ }
1263
+ winAh = win.__ajaxHooker = winAh || {
1264
+ version,
1265
+ fakeXHR,
1266
+ fakeFetch,
1267
+ fakeFetchClone,
1268
+ realXHR: win.XMLHttpRequest,
1269
+ realFetch: win.fetch,
1270
+ realFetchClone: resProto.clone,
1271
+ hookInsts: new Set(),
1272
+ };
1273
+ if (winAh.version !== version)
1274
+ console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1275
+ win.XMLHttpRequest = winAh.fakeXHR;
1276
+ win.fetch = winAh.fakeFetch;
1277
+ resProto.clone = winAh.fakeFetchClone;
1278
+ winAh.hookInsts.add(hookInst);
1279
+ // 针对头条、抖音 secsdk.umd.js 的兼容性处理
1280
+ class AHFunction extends Function {
1281
+ call(thisArg, ...args) {
1282
+ if (
1283
+ thisArg &&
1284
+ thisArg.__ajaxHooker &&
1285
+ thisArg.__ajaxHooker.proxyXhr === thisArg
1286
+ ) {
1287
+ thisArg = thisArg.__ajaxHooker.originalXhr;
1044
1288
  }
1289
+ return Reflect.apply(this, thisArg, args);
1045
1290
  }
1046
- function hookSecsdk(csrf) {
1047
- Object.setPrototypeOf(
1048
- csrf.nativeXMLHttpRequestSetRequestHeader,
1049
- AHFunction.prototype
1050
- );
1051
- Object.setPrototypeOf(
1052
- csrf.nativeXMLHttpRequestOpen,
1053
- AHFunction.prototype
1054
- );
1055
- Object.setPrototypeOf(
1056
- csrf.nativeXMLHttpRequestSend,
1057
- AHFunction.prototype
1058
- );
1291
+ apply(thisArg, args) {
1292
+ if (
1293
+ thisArg &&
1294
+ thisArg.__ajaxHooker &&
1295
+ thisArg.__ajaxHooker.proxyXhr === thisArg
1296
+ ) {
1297
+ thisArg = thisArg.__ajaxHooker.originalXhr;
1298
+ }
1299
+ return Reflect.apply(this, thisArg, args || []);
1059
1300
  }
1060
- if (win.secsdk) {
1061
- if (win.secsdk.csrf && win.secsdk.csrf.nativeXMLHttpRequestOpen)
1062
- hookSecsdk(win.secsdk.csrf);
1063
- } else {
1064
- defineProp(win, "secsdk", emptyFn, (secsdk) => {
1065
- delete win.secsdk;
1066
- win.secsdk = secsdk;
1067
- defineProp(secsdk, "csrf", emptyFn, (csrf) => {
1068
- delete secsdk.csrf;
1069
- secsdk.csrf = csrf;
1070
- if (csrf.nativeXMLHttpRequestOpen) hookSecsdk(csrf);
1071
- });
1301
+ }
1302
+ function hookSecsdk(csrf) {
1303
+ Object.setPrototypeOf(
1304
+ csrf.nativeXMLHttpRequestSetRequestHeader,
1305
+ AHFunction.prototype
1306
+ );
1307
+ Object.setPrototypeOf(csrf.nativeXMLHttpRequestOpen, AHFunction.prototype);
1308
+ Object.setPrototypeOf(csrf.nativeXMLHttpRequestSend, AHFunction.prototype);
1309
+ }
1310
+ if (win.secsdk) {
1311
+ if (win.secsdk.csrf && win.secsdk.csrf.nativeXMLHttpRequestOpen)
1312
+ hookSecsdk(win.secsdk.csrf);
1313
+ } else {
1314
+ defineProp(win, "secsdk", emptyFn, (secsdk) => {
1315
+ delete win.secsdk;
1316
+ win.secsdk = secsdk;
1317
+ defineProp(secsdk, "csrf", emptyFn, (csrf) => {
1318
+ delete secsdk.csrf;
1319
+ secsdk.csrf = csrf;
1320
+ if (csrf.nativeXMLHttpRequestOpen) hookSecsdk(csrf);
1072
1321
  });
1073
- }
1074
- return {
1075
- hook: (fn) => hookInst.hookFns.push(fn),
1076
- filter: (arr) => {
1077
- if (Array.isArray(arr)) hookInst.filters = arr;
1078
- },
1079
- protect: () => {
1080
- readonly(win, "XMLHttpRequest", winAh.fakeXHR);
1081
- readonly(win, "fetch", winAh.fakeFetch);
1082
- readonly(resProto, "clone", winAh.fakeFetchClone);
1083
- },
1084
- unhook: () => {
1085
- winAh.hookInsts.delete(hookInst);
1086
- if (!winAh.hookInsts.size) {
1087
- writable(win, "XMLHttpRequest", winAh.realXHR);
1088
- writable(win, "fetch", winAh.realFetch);
1089
- writable(resProto, "clone", winAh.realFetchClone);
1090
- delete win.__ajaxHooker;
1091
- }
1092
- },
1093
- };
1094
- })();
1322
+ });
1323
+ }
1324
+ return {
1325
+ hook: (fn) => hookInst.hookFns.push(fn),
1326
+ filter: (arr) => {
1327
+ if (Array.isArray(arr)) hookInst.filters = arr;
1328
+ },
1329
+ protect: () => {
1330
+ readonly(win, "XMLHttpRequest", winAh.fakeXHR);
1331
+ readonly(win, "fetch", winAh.fakeFetch);
1332
+ readonly(resProto, "clone", winAh.fakeFetchClone);
1333
+ },
1334
+ unhook: () => {
1335
+ winAh.hookInsts.delete(hookInst);
1336
+ if (!winAh.hookInsts.size) {
1337
+ writable(win, "XMLHttpRequest", winAh.realXHR);
1338
+ writable(win, "fetch", winAh.realFetch);
1339
+ writable(resProto, "clone", winAh.realFetchClone);
1340
+ delete win.__ajaxHooker;
1341
+ }
1342
+ },
1343
+ };
1095
1344
  };
1096
1345
 
1097
1346
  // ==UserScript==
@@ -1623,7 +1872,7 @@ define((function () { 'use strict';
1623
1872
  menuOptions = [menuOptions];
1624
1873
  }
1625
1874
  for (let index = 0; index < menuOptions.length; index++) {
1626
- let cloneMenuOptionData = utils.deepClone(menuOptions[index].data);
1875
+ let cloneMenuOptionData = commonUtil.deepClone(menuOptions[index].data);
1627
1876
  const { showText, clickCallBack } = this.handleMenuData(cloneMenuOptionData);
1628
1877
  let menuId = that.context.GM_Api.registerMenuCommand(showText, clickCallBack);
1629
1878
  menuOptions[index].id = menuId;
@@ -1795,14 +2044,14 @@ define((function () { 'use strict';
1795
2044
  const option = menuOption[index];
1796
2045
  this.MenuHandle.$data.data.push({
1797
2046
  data: option,
1798
- id: undefined,
2047
+ id: void 0,
1799
2048
  });
1800
2049
  }
1801
2050
  }
1802
2051
  else {
1803
2052
  this.MenuHandle.$data.data.push({
1804
2053
  data: menuOption,
1805
- id: undefined,
2054
+ id: void 0,
1806
2055
  });
1807
2056
  }
1808
2057
  }
@@ -2025,16 +2274,12 @@ define((function () { 'use strict';
2025
2274
  return "";
2026
2275
  }
2027
2276
  try {
2028
- eval("_context[_funcName] = function " +
2029
- _funcName +
2030
- "(){\n" +
2031
- "let args = Array.prototype.slice.call(arguments,0);\n" +
2032
- "let obj = this;\n" +
2033
- "hookFunc.apply(obj,args);\n" +
2034
- "return _context['realFunc_" +
2035
- _funcName +
2036
- "'].apply(obj,args);\n" +
2037
- "};");
2277
+ new Function("_context", "_funcName", "hookFunc", `_context[_funcName] = function ${_funcName}() {
2278
+ let args = Array.prototype.slice.call(arguments, 0);
2279
+ let obj = this;
2280
+ hookFunc.apply(obj, args);
2281
+ return _context['realFunc_${_funcName}'].apply(obj, args);
2282
+ };`)(_context, _funcName, hookFunc);
2038
2283
  _context[_funcName].prototype.isHooked = true;
2039
2284
  return true;
2040
2285
  }
@@ -2294,14 +2539,14 @@ define((function () { 'use strict';
2294
2539
  if (typeof args[1] === "object") {
2295
2540
  /* 处理第二个参数details */
2296
2541
  let optionArg = args[1];
2297
- utils.assign(option, optionArg, true);
2542
+ commonUtil.assign(option, optionArg, true);
2298
2543
  option.url = url;
2299
2544
  }
2300
2545
  }
2301
2546
  else {
2302
2547
  /* 传入的是配置 */
2303
2548
  let optionArg = args[0];
2304
- utils.assign(option, optionArg, true);
2549
+ commonUtil.assign(option, optionArg, true);
2305
2550
  }
2306
2551
  return option;
2307
2552
  },
@@ -2334,7 +2579,7 @@ define((function () { 'use strict';
2334
2579
  responseType: userRequestOption.responseType ||
2335
2580
  this.context.#defaultRequestOption.responseType,
2336
2581
  /* 对象使用深拷贝 */
2337
- headers: utils.deepClone(this.context.#defaultRequestOption.headers),
2582
+ headers: commonUtil.deepClone(this.context.#defaultRequestOption.headers),
2338
2583
  data: userRequestOption.data || this.context.#defaultRequestOption.data,
2339
2584
  redirect: userRequestOption.redirect ||
2340
2585
  this.context.#defaultRequestOption.redirect,
@@ -2347,7 +2592,7 @@ define((function () { 'use strict';
2347
2592
  revalidate: userRequestOption.revalidate ||
2348
2593
  this.context.#defaultRequestOption.revalidate,
2349
2594
  /* 对象使用深拷贝 */
2350
- context: utils.deepClone(userRequestOption.context ||
2595
+ context: commonUtil.deepClone(userRequestOption.context ||
2351
2596
  this.context.#defaultRequestOption.context),
2352
2597
  overrideMimeType: userRequestOption.overrideMimeType ||
2353
2598
  this.context.#defaultRequestOption.overrideMimeType,
@@ -2355,7 +2600,7 @@ define((function () { 'use strict';
2355
2600
  this.context.#defaultRequestOption.anonymous,
2356
2601
  fetch: userRequestOption.fetch || this.context.#defaultRequestOption.fetch,
2357
2602
  /* 对象使用深拷贝 */
2358
- fetchInit: utils.deepClone(this.context.#defaultRequestOption.fetchInit),
2603
+ fetchInit: commonUtil.deepClone(this.context.#defaultRequestOption.fetchInit),
2359
2604
  allowInterceptConfig: {
2360
2605
  beforeRequest: this.context.#defaultRequestOption
2361
2606
  .allowInterceptConfig.beforeRequest,
@@ -2581,12 +2826,12 @@ define((function () { 'use strict';
2581
2826
  Object.keys(option).forEach((keyName) => {
2582
2827
  if (option[keyName] == null ||
2583
2828
  (option[keyName] instanceof Function &&
2584
- utils.isNull(option[keyName]))) {
2829
+ commonUtil.isNull(option[keyName]))) {
2585
2830
  Reflect.deleteProperty(option, keyName);
2586
2831
  return;
2587
2832
  }
2588
2833
  });
2589
- if (utils.isNull(option.url)) {
2834
+ if (commonUtil.isNull(option.url)) {
2590
2835
  throw new TypeError(`Utils.Httpx 参数 url不符合要求: ${option.url}`);
2591
2836
  }
2592
2837
  return option;
@@ -2785,10 +3030,10 @@ define((function () { 'use strict';
2785
3030
  /* X浏览器会因为设置了responseType导致不返回responseText */
2786
3031
  let originResponse = argsResult[0];
2787
3032
  /* responseText为空,response不为空的情况 */
2788
- if (utils.isNull(originResponse["responseText"]) &&
2789
- utils.isNotNull(originResponse["response"])) {
3033
+ if (commonUtil.isNull(originResponse["responseText"]) &&
3034
+ commonUtil.isNotNull(originResponse["response"])) {
2790
3035
  if (typeof originResponse["response"] === "object") {
2791
- utils.tryCatch().run(() => {
3036
+ TryCatch().run(() => {
2792
3037
  originResponse["responseText"] = JSON.stringify(originResponse["response"]);
2793
3038
  });
2794
3039
  }
@@ -2805,7 +3050,7 @@ define((function () { 'use strict';
2805
3050
  // 自定义个新的response
2806
3051
  let httpxResponse = httpxResponseText;
2807
3052
  if (details.responseType === "json") {
2808
- httpxResponse = utils.toJSON(httpxResponseText);
3053
+ httpxResponse = commonUtil.toJSON(httpxResponseText);
2809
3054
  }
2810
3055
  else if (details.responseType === "document") {
2811
3056
  let parser = new DOMParser();
@@ -2949,13 +3194,13 @@ define((function () { 'use strict';
2949
3194
  status: fetchResponse.status,
2950
3195
  statusText: fetchResponse.statusText,
2951
3196
  // @ts-ignore
2952
- response: undefined,
3197
+ response: void 0,
2953
3198
  responseFetchHeaders: fetchResponse.headers,
2954
3199
  responseHeaders: "",
2955
3200
  // @ts-ignore
2956
- responseText: undefined,
3201
+ responseText: void 0,
2957
3202
  responseType: option.responseType,
2958
- responseXML: undefined,
3203
+ responseXML: void 0,
2959
3204
  };
2960
3205
  Object.assign(httpxResponse, option.context || {});
2961
3206
  // 把headers转为字符串
@@ -3015,7 +3260,7 @@ define((function () { 'use strict';
3015
3260
  (typeof fetchResponseType === "string" &&
3016
3261
  fetchResponseType.includes("application/json"))) {
3017
3262
  // response返回格式是JSON格式
3018
- response = utils.toJSON(responseText);
3263
+ response = commonUtil.toJSON(responseText);
3019
3264
  }
3020
3265
  else if (option.responseType === "document" ||
3021
3266
  option.responseType == null) {
@@ -3067,30 +3312,30 @@ define((function () { 'use strict';
3067
3312
  * 默认配置
3068
3313
  */
3069
3314
  #defaultRequestOption = {
3070
- url: undefined,
3315
+ url: void 0,
3071
3316
  timeout: 5000,
3072
3317
  async: false,
3073
- responseType: undefined,
3074
- headers: undefined,
3075
- data: undefined,
3076
- redirect: undefined,
3077
- cookie: undefined,
3078
- cookiePartition: undefined,
3079
- binary: undefined,
3080
- nocache: undefined,
3081
- revalidate: undefined,
3082
- context: undefined,
3083
- overrideMimeType: undefined,
3084
- anonymous: undefined,
3085
- fetch: undefined,
3086
- fetchInit: undefined,
3318
+ responseType: void 0,
3319
+ headers: void 0,
3320
+ data: void 0,
3321
+ redirect: void 0,
3322
+ cookie: void 0,
3323
+ cookiePartition: void 0,
3324
+ binary: void 0,
3325
+ nocache: void 0,
3326
+ revalidate: void 0,
3327
+ context: void 0,
3328
+ overrideMimeType: void 0,
3329
+ anonymous: void 0,
3330
+ fetch: void 0,
3331
+ fetchInit: void 0,
3087
3332
  allowInterceptConfig: {
3088
3333
  beforeRequest: true,
3089
3334
  afterResponseSuccess: true,
3090
3335
  afterResponseError: true,
3091
3336
  },
3092
- user: undefined,
3093
- password: undefined,
3337
+ user: void 0,
3338
+ password: void 0,
3094
3339
  onabort() { },
3095
3340
  onerror() { },
3096
3341
  ontimeout() { },
@@ -3102,7 +3347,7 @@ define((function () { 'use strict';
3102
3347
  /**
3103
3348
  * `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
3104
3349
  */
3105
- baseURL: undefined,
3350
+ baseURL: void 0,
3106
3351
  /**
3107
3352
  * 当前使用请求时,输出请求的配置,一般用于DEBUG|DEV
3108
3353
  */
@@ -3116,7 +3361,7 @@ define((function () { 'use strict';
3116
3361
  if (typeof option.xmlHttpRequest !== "function") {
3117
3362
  console.warn("[Httpx-constructor] 未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,将默认使用window.fetch");
3118
3363
  }
3119
- utils.coverObjectFunctionThis(this);
3364
+ commonUtil.coverObjectFunctionThis(this);
3120
3365
  this.interceptors.request.context = this;
3121
3366
  this.interceptors.response.context = this;
3122
3367
  this.config(option);
@@ -3129,8 +3374,8 @@ define((function () { 'use strict';
3129
3374
  if (typeof option.xmlHttpRequest === "function") {
3130
3375
  this.GM_Api.xmlHttpRequest = option.xmlHttpRequest;
3131
3376
  }
3132
- this.#defaultRequestOption = utils.assign(this.#defaultRequestOption, option);
3133
- this.#defaultInitOption = utils.assign(this.#defaultInitOption, option);
3377
+ this.#defaultRequestOption = commonUtil.assign(this.#defaultRequestOption, option);
3378
+ this.#defaultInitOption = commonUtil.assign(this.#defaultInitOption, option);
3134
3379
  }
3135
3380
  /**
3136
3381
  * 拦截器
@@ -3507,7 +3752,7 @@ define((function () { 'use strict';
3507
3752
  success: false,
3508
3753
  code: that.#statusCode.getFailed.code,
3509
3754
  msg: that.#statusCode.getFailed.msg,
3510
- data: undefined,
3755
+ data: void 0,
3511
3756
  });
3512
3757
  }
3513
3758
  else {
@@ -3517,7 +3762,7 @@ define((function () { 'use strict';
3517
3762
  let result = target.result;
3518
3763
  /* result 返回的是 {key: string, value: any} */
3519
3764
  /* 键值对存储 */
3520
- let data = result ? result.value : undefined;
3765
+ let data = result ? result.value : void 0;
3521
3766
  if (data == null) {
3522
3767
  resolve({
3523
3768
  success: true,
@@ -3544,7 +3789,7 @@ define((function () { 'use strict';
3544
3789
  success: false,
3545
3790
  code: that.#statusCode.getFailed.code,
3546
3791
  msg: that.#statusCode.getFailed.msg,
3547
- data: undefined,
3792
+ data: void 0,
3548
3793
  event: event,
3549
3794
  });
3550
3795
  };
@@ -3694,7 +3939,7 @@ define((function () { 'use strict';
3694
3939
  #flag = false;
3695
3940
  #delayTime = 0;
3696
3941
  #callback;
3697
- #context;
3942
+ #timeId = void 0;
3698
3943
  lock;
3699
3944
  unlock;
3700
3945
  run;
@@ -3704,23 +3949,22 @@ define((function () { 'use strict';
3704
3949
  this.#callback = callback;
3705
3950
  if (typeof context === "number") {
3706
3951
  this.#delayTime = context;
3707
- this.#context = utils;
3708
3952
  }
3709
3953
  else {
3710
3954
  this.#delayTime = delayTime;
3711
- this.#context = context;
3712
3955
  }
3713
3956
  /**
3714
3957
  * 锁
3715
3958
  */
3716
3959
  this.lock = function () {
3717
3960
  that.#flag = true;
3961
+ clearTimeout(that.#timeId);
3718
3962
  };
3719
3963
  /**
3720
3964
  * 解锁
3721
3965
  */
3722
3966
  this.unlock = function () {
3723
- utils.workerSetTimeout(() => {
3967
+ that.#timeId = setTimeout(() => {
3724
3968
  that.#flag = false;
3725
3969
  }, that.#delayTime);
3726
3970
  };
@@ -3738,7 +3982,7 @@ define((function () { 'use strict';
3738
3982
  return;
3739
3983
  }
3740
3984
  that.lock();
3741
- await that.#callback.apply(that.#context, args);
3985
+ await that.#callback.apply(this, args);
3742
3986
  that.unlock();
3743
3987
  };
3744
3988
  }
@@ -4026,7 +4270,7 @@ define((function () { 'use strict';
4026
4270
  * @param paramConfig 配置信息
4027
4271
  */
4028
4272
  constructor(paramConfig) {
4029
- this.#config = utils.assign(this.#config, paramConfig);
4273
+ this.#config = commonUtil.assign(this.#config, paramConfig);
4030
4274
  if (!(this.#config.canvasNode instanceof HTMLCanvasElement)) {
4031
4275
  throw new Error("Utils.Progress 参数 canvasNode 必须是 HTMLCanvasElement");
4032
4276
  }
@@ -4078,97 +4322,12 @@ define((function () { 'use strict';
4078
4322
  let txt = parseInt(this.#config.progress.toString()) + "%";
4079
4323
  this.#ctx.font = this.#config.fontSize + "px SimHei";
4080
4324
  /* 获取文本宽度 */
4081
- let w = this.#ctx.measureText(txt).width;
4082
- let h = this.#config.fontSize / 2;
4083
- this.#ctx.fillStyle = this.#config.textColor;
4084
- this.#ctx.fillText(txt, this.#width / 2 - w / 2, this.#height / 2 + h / 2);
4085
- }
4086
- }
4087
-
4088
- const TryCatch = function (...args) {
4089
- /* 定义变量和函数 */
4090
- let callbackFunction = null;
4091
- let context = null;
4092
- let handleError = (error) => { };
4093
- let defaultDetails = {
4094
- log: true,
4095
- };
4096
- const TryCatchCore = {
4097
- /**
4098
- *
4099
- * @param paramDetails 配置
4100
- * @returns
4101
- */
4102
- config(paramDetails) {
4103
- defaultDetails = utils.assign(defaultDetails, paramDetails);
4104
- return TryCatchCore;
4105
- },
4106
- /**
4107
- * 处理错误
4108
- * @param handler
4109
- */
4110
- error(handler) {
4111
- // @ts-ignore
4112
- handleError = handler;
4113
- return TryCatchCore;
4114
- },
4115
- /**
4116
- * 执行传入的函数并捕获其可能抛出的错误,并通过传入的错误处理函数进行处理。
4117
- * @param callback 待执行函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
4118
- * @param __context__ 待执行函数的作用域,用于apply指定
4119
- * @returns 如果函数有返回值,则返回该返回值;否则返回 tryCatchObj 函数以支持链式调用。
4120
- * @throws {Error} 如果传入参数不符合要求,则会抛出相应类型的错误。
4121
- */
4122
- run(callback, __context__) {
4123
- callbackFunction = callback;
4124
- context = __context__ || this;
4125
- let result = executeTryCatch(callbackFunction, handleError, context);
4126
- // @ts-ignore
4127
- return result !== undefined ? result : TryCatchCore;
4128
- },
4129
- };
4130
- /**
4131
- * 执行传入的函数并捕获其可能抛出的错误,并通过传入的错误处理函数进行处理。
4132
- * @param callback - 待执行函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
4133
- * @param handleErrorFunc - 错误处理函数,可以是 function 或者 string 类型。如果是 string 类型,则会被当做代码进行执行。
4134
- * @param funcThis - 待执行函数的作用域,用于apply指定
4135
- * @returns 如果函数有返回值,则返回该返回值;否则返回 undefined。
4136
- */
4137
- function executeTryCatch(callback, handleErrorFunc, funcThis) {
4138
- let result = undefined;
4139
- try {
4140
- if (typeof callback === "string") {
4141
- (function () {
4142
- eval(callback);
4143
- }).apply(funcThis, args);
4144
- }
4145
- else {
4146
- result = callback.apply(funcThis, args);
4147
- }
4148
- }
4149
- catch (error) {
4150
- if (defaultDetails.log) {
4151
- callback = callback;
4152
- console.log(`%c ${callback?.name ? callback?.name : callback + "出现错误"} `, "color: #f20000");
4153
- console.log(`%c 错误原因:${error}`, "color: #f20000");
4154
- console.trace(callback);
4155
- }
4156
- if (handleErrorFunc) {
4157
- if (typeof handleErrorFunc === "string") {
4158
- result = function () {
4159
- return eval(handleErrorFunc);
4160
- // @ts-ignore
4161
- }.apply(funcThis, [...args, error]);
4162
- }
4163
- else {
4164
- result = handleErrorFunc.apply(funcThis, [...args, error]);
4165
- }
4166
- }
4167
- }
4168
- return result;
4325
+ let w = this.#ctx.measureText(txt).width;
4326
+ let h = this.#config.fontSize / 2;
4327
+ this.#ctx.fillStyle = this.#config.textColor;
4328
+ this.#ctx.fillText(txt, this.#width / 2 - w / 2, this.#height / 2 + h / 2);
4169
4329
  }
4170
- return TryCatchCore;
4171
- };
4330
+ }
4172
4331
 
4173
4332
  class UtilsDictionary {
4174
4333
  items = {};
@@ -4203,7 +4362,7 @@ define((function () { 'use strict';
4203
4362
  */
4204
4363
  getStartsWith(key) {
4205
4364
  let allKeys = this.keys();
4206
- let result = undefined;
4365
+ let result = void 0;
4207
4366
  for (const keyName of allKeys) {
4208
4367
  if (String(keyName).startsWith(String(key))) {
4209
4368
  result = this.get(keyName);
@@ -4218,7 +4377,7 @@ define((function () { 'use strict';
4218
4377
  * @param val 值,默认为""
4219
4378
  */
4220
4379
  set(key, val) {
4221
- if (key === undefined) {
4380
+ if (key === void 0) {
4222
4381
  throw new Error("Utils.Dictionary().set 参数 key 不能为空");
4223
4382
  }
4224
4383
  Reflect.set(this.items, key, val);
@@ -4285,7 +4444,7 @@ define((function () { 'use strict';
4285
4444
  * @param data 需要合并的字典
4286
4445
  */
4287
4446
  concat(data) {
4288
- this.items = utils.assign(this.items, data.getItems());
4447
+ this.items = commonUtil.assign(this.items, data.getItems());
4289
4448
  }
4290
4449
  forEach(callbackfn) {
4291
4450
  for (const key in this.getItems()) {
@@ -4844,7 +5003,7 @@ define((function () { 'use strict';
4844
5003
 
4845
5004
  const loadOrReturnBroker = createLoadOrReturnBroker(load, worker);
4846
5005
  const clearInterval = (timerId) => loadOrReturnBroker().clearInterval(timerId);
4847
- const clearTimeout = (timerId) => loadOrReturnBroker().clearTimeout(timerId);
5006
+ const clearTimeout$1 = (timerId) => loadOrReturnBroker().clearTimeout(timerId);
4848
5007
  const setInterval = (...args) => loadOrReturnBroker().setInterval(...args);
4849
5008
  const setTimeout$1 = (...args) => loadOrReturnBroker().setTimeout(...args);
4850
5009
 
@@ -5246,13 +5405,194 @@ define((function () { 'use strict';
5246
5405
  }
5247
5406
  }
5248
5407
 
5408
+ class DOMUtils {
5409
+ windowApi;
5410
+ constructor(option) {
5411
+ this.windowApi = new WindowApi(option);
5412
+ }
5413
+ selector(selector, parent) {
5414
+ return this.selectorAll(selector, parent)[0];
5415
+ }
5416
+ selectorAll(selector, parent) {
5417
+ const context = this;
5418
+ parent = parent || context.windowApi.document;
5419
+ selector = selector.trim();
5420
+ if (selector.match(/[^\s]{1}:empty$/gi)) {
5421
+ // empty 语法
5422
+ selector = selector.replace(/:empty$/gi, "");
5423
+ return Array.from(parent.querySelectorAll(selector)).filter(($ele) => {
5424
+ return $ele?.innerHTML?.trim() === "";
5425
+ });
5426
+ }
5427
+ else if (selector.match(/[^\s]{1}:contains\("(.*)"\)$/i) ||
5428
+ selector.match(/[^\s]{1}:contains\('(.*)'\)$/i)) {
5429
+ // contains 语法
5430
+ let textMatch = selector.match(/:contains\(("|')(.*)("|')\)$/i);
5431
+ let text = textMatch[2];
5432
+ selector = selector.replace(/:contains\(("|')(.*)("|')\)$/gi, "");
5433
+ return Array.from(parent.querySelectorAll(selector)).filter(($ele) => {
5434
+ // @ts-ignore
5435
+ return ($ele?.textContent || $ele?.innerText)?.includes(text);
5436
+ });
5437
+ }
5438
+ else if (selector.match(/[^\s]{1}:regexp\("(.*)"\)$/i) ||
5439
+ selector.match(/[^\s]{1}:regexp\('(.*)'\)$/i)) {
5440
+ // regexp 语法
5441
+ let textMatch = selector.match(/:regexp\(("|')(.*)("|')\)$/i);
5442
+ let pattern = textMatch[2];
5443
+ let flagMatch = pattern.match(/("|'),[\s]*("|')([igm]{0,3})$/i);
5444
+ let flags = "";
5445
+ if (flagMatch) {
5446
+ pattern = pattern.replace(/("|'),[\s]*("|')([igm]{0,3})$/gi, "");
5447
+ flags = flagMatch[3];
5448
+ }
5449
+ let regexp = new RegExp(pattern, flags);
5450
+ selector = selector.replace(/:regexp\(("|')(.*)("|')\)$/gi, "");
5451
+ return Array.from(parent.querySelectorAll(selector)).filter(($ele) => {
5452
+ // @ts-ignore
5453
+ return Boolean(($ele?.textContent || $ele?.innerText)?.match(regexp));
5454
+ });
5455
+ }
5456
+ else {
5457
+ // 普通语法
5458
+ return Array.from(parent.querySelectorAll(selector));
5459
+ }
5460
+ }
5461
+ /**
5462
+ * 匹配元素,可使用以下的额外语法
5463
+ *
5464
+ * + :contains([text]) 作用: 找到包含指定文本内容的指定元素
5465
+ * + :empty 作用:找到既没有文本内容也没有子元素的指定元素
5466
+ * + :regexp([text]) 作用: 找到符合正则表达式的内容的指定元素
5467
+ * @param $el 元素
5468
+ * @param selector 选择器
5469
+ * @example
5470
+ * DOMUtils.matches("div:contains('测试')")
5471
+ * > true
5472
+ * @example
5473
+ * DOMUtils.matches("div:empty")
5474
+ * > true
5475
+ * @example
5476
+ * DOMUtils.matches("div:regexp('^xxxx$')")
5477
+ * > true
5478
+ * @example
5479
+ * DOMUtils.matches("div:regexp(/^xxx/ig)")
5480
+ * > false
5481
+ */
5482
+ matches($el, selector) {
5483
+ selector = selector.trim();
5484
+ if ($el == null) {
5485
+ return false;
5486
+ }
5487
+ if (selector.match(/[^\s]{1}:empty$/gi)) {
5488
+ // empty 语法
5489
+ selector = selector.replace(/:empty$/gi, "");
5490
+ return $el.matches(selector) && $el?.innerHTML?.trim() === "";
5491
+ }
5492
+ else if (selector.match(/[^\s]{1}:contains\("(.*)"\)$/i) ||
5493
+ selector.match(/[^\s]{1}:contains\('(.*)'\)$/i)) {
5494
+ // contains 语法
5495
+ let textMatch = selector.match(/:contains\(("|')(.*)("|')\)$/i);
5496
+ let text = textMatch[2];
5497
+ selector = selector.replace(/:contains\(("|')(.*)("|')\)$/gi, "");
5498
+ // @ts-ignore
5499
+ let content = $el?.textContent || $el?.innerText;
5500
+ if (typeof content !== "string") {
5501
+ content = "";
5502
+ }
5503
+ return $el.matches(selector) && content?.includes(text);
5504
+ }
5505
+ else if (selector.match(/[^\s]{1}:regexp\("(.*)"\)$/i) ||
5506
+ selector.match(/[^\s]{1}:regexp\('(.*)'\)$/i)) {
5507
+ // regexp 语法
5508
+ let textMatch = selector.match(/:regexp\(("|')(.*)("|')\)$/i);
5509
+ let pattern = textMatch[2];
5510
+ let flagMatch = pattern.match(/("|'),[\s]*("|')([igm]{0,3})$/i);
5511
+ let flags = "";
5512
+ if (flagMatch) {
5513
+ pattern = pattern.replace(/("|'),[\s]*("|')([igm]{0,3})$/gi, "");
5514
+ flags = flagMatch[3];
5515
+ }
5516
+ let regexp = new RegExp(pattern, flags);
5517
+ selector = selector.replace(/:regexp\(("|')(.*)("|')\)$/gi, "");
5518
+ // @ts-ignore
5519
+ let content = $el?.textContent || $el?.innerText;
5520
+ if (typeof content !== "string") {
5521
+ content = "";
5522
+ }
5523
+ return $el.matches(selector) && Boolean(content?.match(regexp));
5524
+ }
5525
+ else {
5526
+ // 普通语法
5527
+ return $el.matches(selector);
5528
+ }
5529
+ }
5530
+ closest($el, selector) {
5531
+ selector = selector.trim();
5532
+ if (selector.match(/[^\s]{1}:empty$/gi)) {
5533
+ // empty 语法
5534
+ selector = selector.replace(/:empty$/gi, "");
5535
+ let $closest = $el?.closest(selector);
5536
+ if ($closest && $closest?.innerHTML?.trim() === "") {
5537
+ return $closest;
5538
+ }
5539
+ return null;
5540
+ }
5541
+ else if (selector.match(/[^\s]{1}:contains\("(.*)"\)$/i) ||
5542
+ selector.match(/[^\s]{1}:contains\('(.*)'\)$/i)) {
5543
+ // contains 语法
5544
+ let textMatch = selector.match(/:contains\(("|')(.*)("|')\)$/i);
5545
+ let text = textMatch[2];
5546
+ selector = selector.replace(/:contains\(("|')(.*)("|')\)$/gi, "");
5547
+ let $closest = $el?.closest(selector);
5548
+ if ($closest) {
5549
+ // @ts-ignore
5550
+ let content = $el?.textContent || $el?.innerText;
5551
+ if (typeof content === "string" && content.includes(text)) {
5552
+ return $closest;
5553
+ }
5554
+ }
5555
+ return null;
5556
+ }
5557
+ else if (selector.match(/[^\s]{1}:regexp\("(.*)"\)$/i) ||
5558
+ selector.match(/[^\s]{1}:regexp\('(.*)'\)$/i)) {
5559
+ // regexp 语法
5560
+ let textMatch = selector.match(/:regexp\(("|')(.*)("|')\)$/i);
5561
+ let pattern = textMatch[2];
5562
+ let flagMatch = pattern.match(/("|'),[\s]*("|')([igm]{0,3})$/i);
5563
+ let flags = "";
5564
+ if (flagMatch) {
5565
+ pattern = pattern.replace(/("|'),[\s]*("|')([igm]{0,3})$/gi, "");
5566
+ flags = flagMatch[3];
5567
+ }
5568
+ let regexp = new RegExp(pattern, flags);
5569
+ selector = selector.replace(/:regexp\(("|')(.*)("|')\)$/gi, "");
5570
+ let $closest = $el?.closest(selector);
5571
+ if ($closest) {
5572
+ // @ts-ignore
5573
+ let content = $el?.textContent || $el?.innerText;
5574
+ if (typeof content === "string" && content.match(regexp)) {
5575
+ return $closest;
5576
+ }
5577
+ }
5578
+ return null;
5579
+ }
5580
+ else {
5581
+ // 普通语法
5582
+ let $closest = $el?.closest(selector);
5583
+ return $closest;
5584
+ }
5585
+ }
5586
+ }
5587
+ let domUtils = new DOMUtils();
5588
+
5249
5589
  class Utils {
5250
5590
  windowApi;
5251
5591
  constructor(option) {
5252
5592
  this.windowApi = new WindowApi(option);
5253
5593
  }
5254
5594
  /** 版本号 */
5255
- version = "2025.5.28";
5595
+ version = "2025.6.26";
5256
5596
  addStyle(cssText) {
5257
5597
  if (typeof cssText !== "string") {
5258
5598
  throw new Error("Utils.addStyle 参数cssText 必须为String类型");
@@ -5278,58 +5618,22 @@ define((function () { 'use strict';
5278
5618
  }
5279
5619
  return cssNode;
5280
5620
  }
5281
- assign(target = {}, source = {}, isAdd = false) {
5282
- let UtilsContext = this;
5283
- if (Array.isArray(source)) {
5284
- let canTraverse = source.filter((item) => {
5285
- return typeof item === "object";
5286
- });
5287
- if (!canTraverse.length) {
5288
- return source;
5289
- }
5290
- }
5291
- if (source == null) {
5292
- return target;
5293
- }
5294
- if (target == null) {
5295
- target = {};
5296
- }
5297
- if (isAdd) {
5298
- for (const sourceKeyName in source) {
5299
- const targetKeyName = sourceKeyName;
5300
- let targetValue = target[targetKeyName];
5301
- let sourceValue = source[sourceKeyName];
5302
- if (typeof sourceValue === "object" &&
5303
- sourceValue != null &&
5304
- sourceKeyName in target &&
5305
- !UtilsContext.isDOM(sourceValue)) {
5306
- /* 源端的值是object类型,且不是元素节点 */
5307
- target[sourceKeyName] = UtilsContext.assign(targetValue, sourceValue, isAdd);
5308
- continue;
5309
- }
5310
- target[sourceKeyName] = sourceValue;
5311
- }
5312
- }
5313
- else {
5314
- for (const targetKeyName in target) {
5315
- if (targetKeyName in source) {
5316
- let targetValue = target[targetKeyName];
5317
- let sourceValue = source[targetKeyName];
5318
- if (typeof sourceValue === "object" &&
5319
- sourceValue != null &&
5320
- !UtilsContext.isDOM(sourceValue) &&
5321
- Object.keys(sourceValue).length) {
5322
- /* 源端的值是object类型,且不是元素节点 */
5323
- target[targetKeyName] = UtilsContext.assign(targetValue, sourceValue, isAdd);
5324
- continue;
5325
- }
5326
- /* 直接赋值 */
5327
- target[targetKeyName] = sourceValue;
5328
- }
5621
+ /**
5622
+ * JSON数据从源端替换到目标端中,如果目标端存在该数据则替换,不添加,返回结果为目标端替换完毕的结果
5623
+ * @param target 目标数据
5624
+ * @param source 源数据
5625
+ * @param isAdd 是否可以追加键,默认false
5626
+ * @example
5627
+ * Utils.assign({"1":1,"2":{"3":3}}, {"2":{"3":4}});
5628
+ * >
5629
+ * {
5630
+ "1": 1,
5631
+ "2": {
5632
+ "3": 4
5329
5633
  }
5330
5634
  }
5331
- return target;
5332
- }
5635
+ */
5636
+ assign = commonUtil.assign.bind(commonUtil);
5333
5637
  async asyncReplaceAll(string, pattern, asyncFn) {
5334
5638
  let UtilsContext = this;
5335
5639
  if (typeof string !== "string") {
@@ -5372,7 +5676,7 @@ define((function () { 'use strict';
5372
5676
  * ajax劫持库,支持xhr和fetch劫持。
5373
5677
  * + 来源:https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
5374
5678
  * + 作者:cxxjackie
5375
- * + 版本:1.4.4
5679
+ * + 版本:1.4.6
5376
5680
  * + 旧版本:1.2.4
5377
5681
  * + 文档:https://scriptcat.org/zh-CN/script-show-page/637/
5378
5682
  * @param useOldVersion 是否使用旧版本,默认false
@@ -5382,7 +5686,7 @@ define((function () { 'use strict';
5382
5686
  return AjaxHooker1_2_4();
5383
5687
  }
5384
5688
  else {
5385
- return AjaxHooker();
5689
+ return ajaxHooker();
5386
5690
  }
5387
5691
  };
5388
5692
  canvasClickByPosition(canvasElement, clientX = 0, clientY = 0, view = globalThis) {
@@ -5482,19 +5786,11 @@ define((function () { 'use strict';
5482
5786
  * @returns
5483
5787
  */
5484
5788
  ColorConversion = ColorConversion;
5485
- deepClone(obj) {
5486
- let UtilsContext = this;
5487
- if (obj === undefined)
5488
- return undefined;
5489
- if (obj === null)
5490
- return null;
5491
- let clone = obj instanceof Array ? [] : {};
5492
- for (const [key, value] of Object.entries(obj)) {
5493
- clone[key] =
5494
- typeof value === "object" ? UtilsContext.deepClone(value) : value;
5495
- }
5496
- return clone;
5497
- }
5789
+ /**
5790
+ * 深拷贝
5791
+ * @param obj 对象
5792
+ */
5793
+ deepClone = commonUtil.deepClone.bind(commonUtil);
5498
5794
  debounce(fn, delay = 0) {
5499
5795
  let timer = null;
5500
5796
  let UtilsContext = this;
@@ -5517,7 +5813,7 @@ define((function () { 'use strict';
5517
5813
  throw new Error("Utils.deleteParentNode 参数 targetSelector 必须为 string 类型");
5518
5814
  }
5519
5815
  let result = false;
5520
- let needRemoveDOM = element.closest(targetSelector);
5816
+ let needRemoveDOM = domUtils.closest(element, targetSelector);
5521
5817
  if (needRemoveDOM) {
5522
5818
  needRemoveDOM.remove();
5523
5819
  result = true;
@@ -6505,9 +6801,17 @@ define((function () { 'use strict';
6505
6801
  throw new TypeError("参数1类型错误" + typeof firstArg);
6506
6802
  }
6507
6803
  }
6508
- isDOM(target) {
6509
- return target instanceof Node;
6510
- }
6804
+ /**
6805
+ * 判断对象是否是元素
6806
+ * @param target
6807
+ * @returns
6808
+ * + true 是元素
6809
+ * + false 不是元素
6810
+ * @example
6811
+ * Utils.isDOM(document.querySelector("a"))
6812
+ * > true
6813
+ */
6814
+ isDOM = commonUtil.isDOM.bind(commonUtil);
6511
6815
  isFullscreenEnabled() {
6512
6816
  return !!(this.windowApi.document.fullscreenEnabled ||
6513
6817
  this.windowApi.document.webkitFullScreenEnabled ||
@@ -6698,52 +7002,62 @@ define((function () { 'use strict';
6698
7002
  }
6699
7003
  return result;
6700
7004
  }
6701
- isNotNull(...args) {
6702
- let UtilsContext = this;
6703
- return !UtilsContext.isNull.apply(this, args);
6704
- }
6705
- isNull(...args) {
6706
- let result = true;
6707
- let checkList = [...args];
6708
- for (const objItem of checkList) {
6709
- let itemResult = false;
6710
- if (objItem === null || objItem === undefined) {
6711
- itemResult = true;
6712
- }
6713
- else {
6714
- switch (typeof objItem) {
6715
- case "object":
6716
- if (typeof objItem[Symbol.iterator] === "function") {
6717
- /* 可迭代 */
6718
- itemResult = objItem.length === 0;
6719
- }
6720
- else {
6721
- itemResult = Object.keys(objItem).length === 0;
6722
- }
6723
- break;
6724
- case "number":
6725
- itemResult = objItem === 0;
6726
- break;
6727
- case "string":
6728
- itemResult =
6729
- objItem.trim() === "" ||
6730
- objItem === "null" ||
6731
- objItem === "undefined";
6732
- break;
6733
- case "boolean":
6734
- itemResult = !objItem;
6735
- break;
6736
- case "function":
6737
- let funcStr = objItem.toString().replace(/\s/g, "");
6738
- /* 排除()=>{}、(xxx="")=>{}、function(){}、function(xxx=""){} */
6739
- itemResult = Boolean(funcStr.match(/^\(.*?\)=>\{\}$|^function.*?\(.*?\)\{\}$/));
6740
- break;
6741
- }
6742
- }
6743
- result = result && itemResult;
6744
- }
6745
- return result;
6746
- }
7005
+ /**
7006
+ * 判断对象是否不为空
7007
+ * @returns {boolean}
7008
+ * + true 不为空
7009
+ * + false 为空
7010
+ * @example
7011
+ * Utils.isNotNull("123");
7012
+ * > true
7013
+ */
7014
+ isNotNull = commonUtil.isNotNull.bind(commonUtil);
7015
+ /**
7016
+ * 判断对象或数据是否为空
7017
+ * + `String`判空的值,如 ""、"null"、"undefined"、" "
7018
+ * + `Number`判空的值,如 0
7019
+ * + `Object`判空的值,如 {}、null、undefined
7020
+ * + `Array`(存在属性Symbol.iterator)判空的值,如 []
7021
+ * + `Boolean`判空的值,如false
7022
+ * + `Function`判空的值,如()=>{}、(xxx="")=>{}、function(){}、function(xxx=""){}
7023
+ * @returns
7024
+ * + true 为空
7025
+ * + false 不为空
7026
+ * @example
7027
+ Utils.isNull({});
7028
+ > true
7029
+ * @example
7030
+ Utils.isNull([]);
7031
+ > true
7032
+ * @example
7033
+ Utils.isNull(" ");
7034
+ > true
7035
+ * @example
7036
+ Utils.isNull(function(){});
7037
+ > true
7038
+ * @example
7039
+ Utils.isNull(()=>{}));
7040
+ > true
7041
+ * @example
7042
+ Utils.isNull("undefined");
7043
+ > true
7044
+ * @example
7045
+ Utils.isNull("null");
7046
+ > true
7047
+ * @example
7048
+ Utils.isNull(" ", false);
7049
+ > true
7050
+ * @example
7051
+ Utils.isNull([1],[]);
7052
+ > false
7053
+ * @example
7054
+ Utils.isNull([],[1]);
7055
+ > false
7056
+ * @example
7057
+ Utils.isNull(false,[123]);
7058
+ > false
7059
+ **/
7060
+ isNull = commonUtil.isNull.bind(commonUtil);
6747
7061
  isThemeDark() {
6748
7062
  return this.windowApi.globalThis.matchMedia("(prefers-color-scheme: dark)")
6749
7063
  .matches;
@@ -6933,36 +7247,36 @@ define((function () { 'use strict';
6933
7247
  * + true 监听以 target 为根节点的整个子树。包括子树中所有节点的属性,而不仅仅是针对 target
6934
7248
  * + false (默认) 不生效
6935
7249
  */
6936
- subtree: undefined,
7250
+ subtree: void 0,
6937
7251
  /**
6938
7252
  * + true 监听 target 节点中发生的节点的新增与删除(同时,如果 subtree 为 true,会针对整个子树生效)
6939
7253
  * + false (默认) 不生效
6940
7254
  */
6941
- childList: undefined,
7255
+ childList: void 0,
6942
7256
  /**
6943
7257
  * + true 观察所有监听的节点属性值的变化。默认值为 true,当声明了 attributeFilter 或 attributeOldValue
6944
7258
  * + false (默认) 不生效
6945
7259
  */
6946
- attributes: undefined,
7260
+ attributes: void 0,
6947
7261
  /**
6948
7262
  * 一个用于声明哪些属性名会被监听的数组。如果不声明该属性,所有属性的变化都将触发通知
6949
7263
  */
6950
- attributeFilter: undefined,
7264
+ attributeFilter: void 0,
6951
7265
  /**
6952
7266
  * + true 记录上一次被监听的节点的属性变化;可查阅 MutationObserver 中的 Monitoring attribute values 了解关于观察属性变化和属性值记录的详情
6953
7267
  * + false (默认) 不生效
6954
7268
  */
6955
- attributeOldValue: undefined,
7269
+ attributeOldValue: void 0,
6956
7270
  /**
6957
7271
  * + true 监听声明的 target 节点上所有字符的变化。默认值为 true,如果声明了 characterDataOldValue
6958
7272
  * + false (默认) 不生效
6959
7273
  */
6960
- characterData: undefined,
7274
+ characterData: void 0,
6961
7275
  /**
6962
7276
  * + true 记录前一个被监听的节点中发生的文本变化
6963
7277
  * + false (默认) 不生效
6964
7278
  */
6965
- characterDataOldValue: undefined,
7279
+ characterDataOldValue: void 0,
6966
7280
  },
6967
7281
  immediate: false,
6968
7282
  };
@@ -7538,7 +7852,7 @@ define((function () { 'use strict';
7538
7852
  }
7539
7853
  return new Promise((resolve) => {
7540
7854
  UtilsContext.workerSetTimeout(() => {
7541
- resolve(undefined);
7855
+ resolve(void 0);
7542
7856
  }, delayTime);
7543
7857
  });
7544
7858
  }
@@ -7552,7 +7866,7 @@ define((function () { 'use strict';
7552
7866
  return mouseEvent;
7553
7867
  }
7554
7868
  let sliderElement = typeof selector === "string"
7555
- ? this.windowApi.document.querySelector(selector)
7869
+ ? domUtils.selector(selector)
7556
7870
  : selector;
7557
7871
  if (!(sliderElement instanceof Node) ||
7558
7872
  !(sliderElement instanceof Element)) {
@@ -7762,47 +8076,15 @@ define((function () { 'use strict';
7762
8076
  }
7763
8077
  return newTargetString;
7764
8078
  }
7765
- toJSON(data, errorCallBack) {
7766
- let UtilsContext = this;
7767
- let result = {};
7768
- if (typeof data === "object") {
7769
- return data;
7770
- }
7771
- UtilsContext.tryCatch()
7772
- .config({ log: false })
7773
- .error((error) => {
7774
- UtilsContext.tryCatch()
7775
- .error(() => {
7776
- try {
7777
- result = UtilsContext.windowApi.window.eval("(" + data + ")");
7778
- }
7779
- catch (error2) {
7780
- if (typeof errorCallBack === "function") {
7781
- errorCallBack(error2);
7782
- }
7783
- }
7784
- })
7785
- .run(() => {
7786
- if (data &&
7787
- /^[\],:{}\s]*$/.test(data
7788
- .replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
7789
- .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
7790
- .replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
7791
- result = new Function("return " + data)();
7792
- }
7793
- else {
7794
- if (typeof errorCallBack === "function") {
7795
- errorCallBack(new Error("target is not a JSON"));
7796
- }
7797
- }
7798
- });
7799
- })
7800
- .run(() => {
7801
- data = data.trim();
7802
- result = JSON.parse(data);
7803
- });
7804
- return result;
7805
- }
8079
+ /**
8080
+ * 字符串转Object对象,类似'{"test":""}' => {"test":""}
8081
+ * @param data
8082
+ * @param errorCallBack (可选)错误回调
8083
+ * @example
8084
+ * Utils.toJSON("{123:123}")
8085
+ * > {123:123}
8086
+ */
8087
+ toJSON = commonUtil.toJSON.bind(commonUtil);
7806
8088
  toSearchParamsStr(obj, addPrefix) {
7807
8089
  let UtilsContext = this;
7808
8090
  let searhParamsStr = "";
@@ -7913,7 +8195,7 @@ define((function () { 'use strict';
7913
8195
  }
7914
8196
  waitNode(...args) {
7915
8197
  // 过滤掉undefined
7916
- args = args.filter((arg) => arg !== undefined);
8198
+ args = args.filter((arg) => arg !== void 0);
7917
8199
  let UtilsContext = this;
7918
8200
  // 选择器
7919
8201
  let selector = args[0];
@@ -7968,7 +8250,7 @@ define((function () { 'use strict';
7968
8250
  if (Array.isArray(selector)) {
7969
8251
  let result = [];
7970
8252
  for (let index = 0; index < selector.length; index++) {
7971
- let node = parent.querySelector(selector[index]);
8253
+ let node = domUtils.selector(selector[index]);
7972
8254
  if (node) {
7973
8255
  result.push(node);
7974
8256
  }
@@ -7981,7 +8263,7 @@ define((function () { 'use strict';
7981
8263
  return selector();
7982
8264
  }
7983
8265
  else {
7984
- return parent.querySelector(selector);
8266
+ return domUtils.selector(selector, parent);
7985
8267
  }
7986
8268
  }
7987
8269
  return UtilsContext.wait(() => {
@@ -8002,7 +8284,7 @@ define((function () { 'use strict';
8002
8284
  }
8003
8285
  waitAnyNode(...args) {
8004
8286
  // 过滤掉undefined
8005
- args = args.filter((arg) => arg !== undefined);
8287
+ args = args.filter((arg) => arg !== void 0);
8006
8288
  let UtilsContext = this;
8007
8289
  // 选择器
8008
8290
  let selectorList = args[0];
@@ -8058,7 +8340,7 @@ define((function () { 'use strict';
8058
8340
  }
8059
8341
  waitNodeList(...args) {
8060
8342
  // 过滤掉undefined
8061
- args = args.filter((arg) => arg !== undefined);
8343
+ args = args.filter((arg) => arg !== void 0);
8062
8344
  let UtilsContext = this;
8063
8345
  // 选择器数组
8064
8346
  let selector = args[0];
@@ -8111,7 +8393,7 @@ define((function () { 'use strict';
8111
8393
  if (Array.isArray(selector)) {
8112
8394
  let result = [];
8113
8395
  for (let index = 0; index < selector.length; index++) {
8114
- let nodeList = parent.querySelectorAll(selector[index]);
8396
+ let nodeList = domUtils.selectorAll(selector[index], parent);
8115
8397
  if (nodeList.length) {
8116
8398
  result.push(nodeList);
8117
8399
  }
@@ -8121,7 +8403,7 @@ define((function () { 'use strict';
8121
8403
  }
8122
8404
  }
8123
8405
  else {
8124
- let nodeList = parent.querySelectorAll(selector);
8406
+ let nodeList = domUtils.selectorAll(selector, parent);
8125
8407
  if (nodeList.length) {
8126
8408
  return nodeList;
8127
8409
  }
@@ -8145,7 +8427,7 @@ define((function () { 'use strict';
8145
8427
  }
8146
8428
  waitAnyNodeList(...args) {
8147
8429
  // 过滤掉undefined
8148
- args = args.filter((arg) => arg !== undefined);
8430
+ args = args.filter((arg) => arg !== void 0);
8149
8431
  let UtilsContext = this;
8150
8432
  // 选择器数组
8151
8433
  let selectorList = args[0];
@@ -8430,17 +8712,7 @@ define((function () { 'use strict';
8430
8712
  * @param target 需要覆盖的对象
8431
8713
  * @param [objectThis] 覆盖的this指向,如果为传入,则默认为对象本身
8432
8714
  */
8433
- coverObjectFunctionThis(target, objectThis) {
8434
- if (typeof target !== "object" || target === null) {
8435
- throw new Error("target must be object");
8436
- }
8437
- objectThis = objectThis || target;
8438
- Object.keys(target).forEach((key) => {
8439
- if (typeof target[key] === "function") {
8440
- target[key] = target[key].bind(objectThis);
8441
- }
8442
- });
8443
- }
8715
+ coverObjectFunctionThis = commonUtil.coverObjectFunctionThis.bind(commonUtil);
8444
8716
  /**
8445
8717
  * 生成uuid
8446
8718
  * @example
@@ -8481,7 +8753,7 @@ define((function () { 'use strict';
8481
8753
  workerClearTimeout(timeId) {
8482
8754
  try {
8483
8755
  if (timeId != null) {
8484
- clearTimeout(timeId);
8756
+ clearTimeout$1(timeId);
8485
8757
  }
8486
8758
  }
8487
8759
  catch (error) {