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