@whitesev/utils 2.9.12 → 2.10.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.
Files changed (73) hide show
  1. package/README.md +176 -176
  2. package/dist/index.amd.js +206 -117
  3. package/dist/index.amd.js.map +1 -1
  4. package/dist/index.amd.min.js +1 -1
  5. package/dist/index.amd.min.js.map +1 -1
  6. package/dist/index.cjs.js +206 -117
  7. package/dist/index.cjs.js.map +1 -1
  8. package/dist/index.cjs.min.js +1 -1
  9. package/dist/index.cjs.min.js.map +1 -1
  10. package/dist/index.esm.js +206 -117
  11. package/dist/index.esm.js.map +1 -1
  12. package/dist/index.esm.min.js +1 -1
  13. package/dist/index.esm.min.js.map +1 -1
  14. package/dist/index.iife.js +206 -117
  15. package/dist/index.iife.js.map +1 -1
  16. package/dist/index.iife.min.js +1 -1
  17. package/dist/index.iife.min.js.map +1 -1
  18. package/dist/index.system.js +206 -117
  19. package/dist/index.system.js.map +1 -1
  20. package/dist/index.system.min.js +1 -1
  21. package/dist/index.system.min.js.map +1 -1
  22. package/dist/index.umd.js +206 -117
  23. package/dist/index.umd.js.map +1 -1
  24. package/dist/index.umd.min.js +1 -1
  25. package/dist/index.umd.min.js.map +1 -1
  26. package/dist/types/src/Dictionary.d.ts +2 -0
  27. package/dist/types/src/Utils.d.ts +9 -2
  28. package/dist/types/src/types/Httpx.d.ts +1344 -1344
  29. package/dist/types/src/types/Log.d.ts +19 -19
  30. package/dist/types/src/types/Progress.d.ts +20 -20
  31. package/dist/types/src/types/React.d.ts +119 -119
  32. package/dist/types/src/types/TryCatch.d.ts +9 -9
  33. package/dist/types/src/types/UtilsGMCookie.d.ts +93 -93
  34. package/dist/types/src/types/UtilsGMMenu.d.ts +77 -77
  35. package/dist/types/src/types/Vue2.d.ts +166 -166
  36. package/dist/types/src/types/WindowApi.d.ts +14 -14
  37. package/dist/types/src/types/ajaxHooker.d.ts +155 -155
  38. package/dist/types/src/types/env.d.ts +7 -7
  39. package/dist/types/src/types/global.d.ts +31 -31
  40. package/package.json +26 -24
  41. package/src/ColorConversion.ts +118 -118
  42. package/src/CommonUtil.ts +301 -301
  43. package/src/DOMUtils.ts +251 -251
  44. package/src/Dictionary.ts +205 -199
  45. package/src/GBKEncoder.ts +108 -108
  46. package/src/Hooks.ts +73 -73
  47. package/src/Httpx.ts +1457 -1457
  48. package/src/LockFunction.ts +65 -62
  49. package/src/Log.ts +233 -233
  50. package/src/ModuleRaid.js +378 -360
  51. package/src/Progress.ts +108 -108
  52. package/src/TryCatch.ts +86 -86
  53. package/src/Utils.ts +3907 -3852
  54. package/src/UtilsCommon.ts +14 -14
  55. package/src/UtilsGMCookie.ts +273 -273
  56. package/src/UtilsGMMenu.ts +460 -460
  57. package/src/Vue.ts +233 -233
  58. package/src/WindowApi.ts +59 -59
  59. package/src/ajaxHooker/ajaxHooker.js +606 -538
  60. package/src/ajaxHooker/ajaxHooker1.2.4.js +440 -438
  61. package/src/indexedDB.ts +497 -497
  62. package/src/types/Httpx.d.ts +1344 -1344
  63. package/src/types/Log.d.ts +19 -19
  64. package/src/types/Progress.d.ts +20 -20
  65. package/src/types/React.d.ts +119 -119
  66. package/src/types/TryCatch.d.ts +9 -9
  67. package/src/types/UtilsGMCookie.d.ts +93 -93
  68. package/src/types/UtilsGMMenu.d.ts +77 -77
  69. package/src/types/Vue2.d.ts +166 -166
  70. package/src/types/WindowApi.d.ts +14 -14
  71. package/src/types/ajaxHooker.d.ts +155 -155
  72. package/src/types/env.d.ts +7 -7
  73. package/src/types/global.d.ts +31 -31
package/dist/index.umd.js CHANGED
@@ -61,47 +61,7 @@
61
61
  const cache = createCache(LAST_NUMBER_WEAK_MAP);
62
62
  const generateUniqueNumber = createGenerateUniqueNumber(cache, LAST_NUMBER_WEAK_MAP);
63
63
 
64
- const isMessagePort = (sender) => {
65
- return typeof sender.start === 'function';
66
- };
67
-
68
- const PORT_MAP = new WeakMap();
69
-
70
- const extendBrokerImplementation = (partialBrokerImplementation) => ({
71
- ...partialBrokerImplementation,
72
- connect: ({ call }) => {
73
- return async () => {
74
- const { port1, port2 } = new MessageChannel();
75
- const portId = await call('connect', { port: port1 }, [port1]);
76
- PORT_MAP.set(port2, portId);
77
- return port2;
78
- };
79
- },
80
- disconnect: ({ call }) => {
81
- return async (port) => {
82
- const portId = PORT_MAP.get(port);
83
- if (portId === undefined) {
84
- throw new Error('The given port is not connected.');
85
- }
86
- await call('disconnect', { portId });
87
- };
88
- },
89
- isSupported: ({ call }) => {
90
- return () => call('isSupported');
91
- }
92
- });
93
-
94
- const ONGOING_REQUESTS = new WeakMap();
95
- const createOrGetOngoingRequests = (sender) => {
96
- if (ONGOING_REQUESTS.has(sender)) {
97
- // @todo TypeScript needs to be convinced that has() works as expected.
98
- return ONGOING_REQUESTS.get(sender);
99
- }
100
- const ongoingRequests = new Map();
101
- ONGOING_REQUESTS.set(sender, ongoingRequests);
102
- return ongoingRequests;
103
- };
104
- const createBroker = (brokerImplementation) => {
64
+ const createBrokerFactory = (createOrGetOngoingRequests, extendBrokerImplementation, generateUniqueNumber, isMessagePort) => (brokerImplementation) => {
105
65
  const fullBrokerImplementation = extendBrokerImplementation(brokerImplementation);
106
66
  return (sender) => {
107
67
  const ongoingRequests = createOrGetOngoingRequests(sender);
@@ -144,6 +104,46 @@
144
104
  };
145
105
  };
146
106
 
107
+ const createCreateOrGetOngoingRequests = (ongoingRequestsMap) => (sender) => {
108
+ if (ongoingRequestsMap.has(sender)) {
109
+ // @todo TypeScript needs to be convinced that has() works as expected.
110
+ return ongoingRequestsMap.get(sender);
111
+ }
112
+ const ongoingRequests = new Map();
113
+ ongoingRequestsMap.set(sender, ongoingRequests);
114
+ return ongoingRequests;
115
+ };
116
+
117
+ const createExtendBrokerImplementation = (portMap) => (partialBrokerImplementation) => ({
118
+ ...partialBrokerImplementation,
119
+ connect: ({ call }) => {
120
+ return async () => {
121
+ const { port1, port2 } = new MessageChannel();
122
+ const portId = await call('connect', { port: port1 }, [port1]);
123
+ portMap.set(port2, portId);
124
+ return port2;
125
+ };
126
+ },
127
+ disconnect: ({ call }) => {
128
+ return async (port) => {
129
+ const portId = portMap.get(port);
130
+ if (portId === undefined) {
131
+ throw new Error('The given port is not connected.');
132
+ }
133
+ await call('disconnect', { portId });
134
+ };
135
+ },
136
+ isSupported: ({ call }) => {
137
+ return () => call('isSupported');
138
+ }
139
+ });
140
+
141
+ const isMessagePort = (sender) => {
142
+ return typeof sender.start === 'function';
143
+ };
144
+
145
+ const createBroker = createBrokerFactory(createCreateOrGetOngoingRequests(new WeakMap()), createExtendBrokerImplementation(new WeakMap()), generateUniqueNumber, isMessagePort);
146
+
147
147
  const createClearIntervalFactory = (scheduledIntervalsState) => (clear) => (timerId) => {
148
148
  if (typeof scheduledIntervalsState.get(timerId) === 'symbol') {
149
149
  scheduledIntervalsState.set(timerId, null);
@@ -235,15 +235,15 @@
235
235
  };
236
236
 
237
237
  // This is the minified and stringified code of the worker-timers-worker package.
238
- const worker = `(()=>{var e={455:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<s?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*s);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,u=r(i),c=a(u,i),l=t(c);e.addUniqueNumber=l,e.generateUniqueNumber=c}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,o=(e,t)=>Object.assign(new Error(e),{status:t}),s=t=>o('The handler of the method called "'.concat(t,'" returned an unexpected result.'),e),a=(t,r)=>async({data:{id:a,method:i,params:u}})=>{const c=r[i];try{if(void 0===c)throw(e=>o('The requested method called "'.concat(e,'" is not supported.'),n))(i);const r=void 0===u?c():c(u);if(void 0===r)throw(t=>o('The handler of the method called "'.concat(t,'" returned no required result.'),e))(i);const l=r instanceof Promise?await r:r;if(null===a){if(void 0!==l.result)throw s(i)}else{if(void 0===l.result)throw s(i);const{result:e,transferables:r=[]}=l;t.postMessage({id:a,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:a})}};var i=r(455);const u=new Map,c=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),o=(0,i.generateUniqueNumber)(u);return u.set(o,()=>{n(),t.close(),u.delete(o)}),{result:o}},disconnect:({portId:e})=>{const r=u.get(e);if(void 0===r)throw(e=>o('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise(e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])})){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),l=(e,t,r=()=>!0)=>{const n=c(l,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},d=(e,t)=>r=>{const n=t.get(r);if(void 0===n)return Promise.resolve(!1);const[o,s]=n;return e(o),t.delete(r),s(!1),Promise.resolve(!0)},f=(e,t,r,n)=>(o,s,a)=>{const i=o+s-t.timeOrigin,u=i-t.now();return new Promise(t=>{e.set(a,[r(n,u,i,e,t,a),t])})},m=new Map,h=d(globalThis.clearTimeout,m),p=new Map,v=d(globalThis.clearTimeout,p),w=((e,t)=>{const r=(n,o,s,a)=>{const i=n-e.now();i>0?o.set(a,[t(r,i,n,o,s,a),s]):(o.delete(a),s(!0))};return r})(performance,globalThis.setTimeout),g=f(m,performance,globalThis.setTimeout,w),T=f(p,performance,globalThis.setTimeout,w);l(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?h(e):v(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?g:T)(e,t,r)})})})()})();`; // tslint:disable-line:max-line-length
238
+ const worker = `(()=>{var e={455(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<s?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*s);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,u=r(i),c=a(u,i),l=t(c);e.addUniqueNumber=l,e.generateUniqueNumber=c}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,o=(e,t)=>Object.assign(new Error(e),{status:t}),s=t=>o('The handler of the method called "'.concat(t,'" returned an unexpected result.'),e),a=(t,r)=>async({data:{id:a,method:i,params:u}})=>{const c=r[i];try{if(void 0===c)throw(e=>o('The requested method called "'.concat(e,'" is not supported.'),n))(i);const r=void 0===u?c():c(u);if(void 0===r)throw(t=>o('The handler of the method called "'.concat(t,'" returned no required result.'),e))(i);const l=r instanceof Promise?await r:r;if(null===a){if(void 0!==l.result)throw s(i)}else{if(void 0===l.result)throw s(i);const{result:e,transferables:r=[]}=l;t.postMessage({id:a,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:a})}};var i=r(455);const u=new Map,c=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),o=(0,i.generateUniqueNumber)(u);return u.set(o,()=>{n(),t.close(),u.delete(o)}),{result:o}},disconnect:({portId:e})=>{const r=u.get(e);if(void 0===r)throw(e=>o('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise(e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])})){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),l=(e,t,r=()=>!0)=>{const n=c(l,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},d=(e,t)=>r=>{const n=t.get(r);if(void 0===n)return Promise.resolve(!1);const[o,s]=n;return e(o),t.delete(r),s(!1),Promise.resolve(!0)},m=(e,t,r,n)=>(o,s,a)=>{const i=o+s-t.timeOrigin,u=i-t.now();return new Promise(t=>{e.set(a,[r(n,u,i,e,t,a),t])})},f=new Map,h=d(globalThis.clearTimeout,f),p=new Map,v=d(globalThis.clearTimeout,p),w=((e,t)=>{const r=(n,o,s,a)=>{const i=n-e.now();i>0?o.set(a,[t(r,i,n,o,s,a),s]):(o.delete(a),s(!0))};return r})(performance,globalThis.setTimeout),g=m(f,performance,globalThis.setTimeout,w),T=m(p,performance,globalThis.setTimeout,w);l(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?h(e):v(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?g:T)(e,t,r)})})})()})();`; // tslint:disable-line:max-line-length
239
239
 
240
240
  const loadOrReturnBroker = createLoadOrReturnBroker(load, worker);
241
- const clearInterval = (timerId) => loadOrReturnBroker().clearInterval(timerId);
241
+ const clearInterval$1 = (timerId) => loadOrReturnBroker().clearInterval(timerId);
242
242
  const clearTimeout$1 = (timerId) => loadOrReturnBroker().clearTimeout(timerId);
243
- const setInterval = (...args) => loadOrReturnBroker().setInterval(...args);
243
+ const setInterval$1 = (...args) => loadOrReturnBroker().setInterval(...args);
244
244
  const setTimeout$1 = (...args) => loadOrReturnBroker().setTimeout(...args);
245
245
 
246
- const version = "2.9.12";
246
+ const version = "2.10.0";
247
247
 
248
248
  /* eslint-disable */
249
249
  // ==UserScript==
@@ -283,7 +283,9 @@
283
283
  const emptyFn = () => { };
284
284
  const errorFn = (e) => console.error(e);
285
285
  function isThenable(obj) {
286
- return obj && ["object", "function"].includes(typeof obj) && typeof obj.then === "function";
286
+ return (obj &&
287
+ ["object", "function"].includes(typeof obj) &&
288
+ typeof obj.then === "function");
287
289
  }
288
290
  function catchError(fn, ...args) {
289
291
  try {
@@ -324,7 +326,8 @@
324
326
  if (!value)
325
327
  continue;
326
328
  const lheader = header.toLowerCase();
327
- headers[lheader] = lheader in headers ? `${headers[lheader]}, ${value}` : value;
329
+ headers[lheader] =
330
+ lheader in headers ? `${headers[lheader]}, ${value}` : value;
328
331
  }
329
332
  break;
330
333
  case "[object Headers]":
@@ -363,9 +366,11 @@
363
366
  !filters.find((obj) => {
364
367
  switch (true) {
365
368
  case obj.type && obj.type !== type:
366
- case getType(obj.url) === "[object String]" && !url.includes(obj.url):
369
+ case getType(obj.url) === "[object String]" &&
370
+ !url.includes(obj.url):
367
371
  case getType(obj.url) === "[object RegExp]" && !obj.url.test(url):
368
- case obj.method && obj.method.toUpperCase() !== method.toUpperCase():
372
+ case obj.method &&
373
+ obj.method.toUpperCase() !== method.toUpperCase():
369
374
  case "async" in obj && obj.async !== async:
370
375
  return false;
371
376
  }
@@ -408,7 +413,8 @@
408
413
  if (getType(this.request.response) === "[object Function]") {
409
414
  catchError(this.request.response, response);
410
415
  responseKeys.forEach((key) => {
411
- if ("get" in getDescriptor(response, key) || isThenable(response[key])) {
416
+ if ("get" in getDescriptor(response, key) ||
417
+ isThenable(response[key])) {
412
418
  delete response[key];
413
419
  }
414
420
  });
@@ -429,7 +435,10 @@
429
435
  const proxyHandler = {
430
436
  get(target, prop) {
431
437
  const descriptor = getDescriptor(target, prop);
432
- if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.get)
438
+ if (descriptor &&
439
+ !descriptor.configurable &&
440
+ !descriptor.writable &&
441
+ !descriptor.get)
433
442
  return target[prop];
434
443
  const ah = target.__ajaxHooker;
435
444
  if (ah && ah.proxyProps) {
@@ -448,7 +457,10 @@
448
457
  },
449
458
  set(target, prop, value) {
450
459
  const descriptor = getDescriptor(target, prop);
451
- if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.set)
460
+ if (descriptor &&
461
+ !descriptor.configurable &&
462
+ !descriptor.writable &&
463
+ !descriptor.set)
452
464
  return true;
453
465
  const ah = target.__ajaxHooker;
454
466
  if (ah && ah.proxyProps && prop in ah.proxyProps) {
@@ -472,7 +484,9 @@
472
484
  proxyEvents: {},
473
485
  });
474
486
  xhr.addEventListener("readystatechange", (e) => {
475
- if (ah.proxyXhr.readyState === 4 && ah.request && typeof ah.request.response === "function") {
487
+ if (ah.proxyXhr.readyState === 4 &&
488
+ ah.request &&
489
+ typeof ah.request.response === "function") {
476
490
  const response = {
477
491
  finalUrl: ah.proxyXhr.responseURL,
478
492
  status: ah.proxyXhr.status,
@@ -491,7 +505,9 @@
491
505
  response[key] = val;
492
506
  });
493
507
  }
494
- ah.resThenable = new AHRequest(ah.request).waitForResponseKeys(response).then(() => {
508
+ ah.resThenable = new AHRequest(ah.request)
509
+ .waitForResponseKeys(response)
510
+ .then(() => {
495
511
  for (const key of xhrResponses) {
496
512
  ah.proxyProps[key] = {
497
513
  get: () => {
@@ -514,7 +530,13 @@
514
530
  set: (val) => ah.addEvent(onEvt, val),
515
531
  };
516
532
  }
517
- for (const method of ["setRequestHeader", "addEventListener", "removeEventListener", "open", "send"]) {
533
+ for (const method of [
534
+ "setRequestHeader",
535
+ "addEventListener",
536
+ "removeEventListener",
537
+ "open",
538
+ "send",
539
+ ]) {
518
540
  ah.proxyProps[method] = { value: ah[method] };
519
541
  }
520
542
  }
@@ -561,7 +583,8 @@
561
583
  if (!this.request)
562
584
  return;
563
585
  const headers = this.request.headers;
564
- headers[header] = header in headers ? `${headers[header]}, ${value}` : value;
586
+ headers[header] =
587
+ header in headers ? `${headers[header]}, ${value}` : value;
565
588
  }
566
589
  addEventListener(...args) {
567
590
  if (xhrAsyncEvents.includes(args[0])) {
@@ -592,7 +615,13 @@
592
615
  };
593
616
  this.openArgs = args;
594
617
  this.resThenable = new SyncThenable();
595
- ["responseURL", "readyState", "status", "statusText", ...xhrResponses].forEach((key) => {
618
+ [
619
+ "responseURL",
620
+ "readyState",
621
+ "status",
622
+ "statusText",
623
+ ...xhrResponses,
624
+ ].forEach((key) => {
596
625
  delete this.proxyProps[key];
597
626
  });
598
627
  return this.originalXhr.open(method, url, async, ...args);
@@ -754,13 +783,17 @@
754
783
  // 针对头条、抖音 secsdk.umd.js 的兼容性处理
755
784
  class AHFunction extends Function {
756
785
  call(thisArg, ...args) {
757
- if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
786
+ if (thisArg &&
787
+ thisArg.__ajaxHooker &&
788
+ thisArg.__ajaxHooker.proxyXhr === thisArg) {
758
789
  thisArg = thisArg.__ajaxHooker.originalXhr;
759
790
  }
760
791
  return Reflect.apply(this, thisArg, args);
761
792
  }
762
793
  apply(thisArg, args) {
763
- if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
794
+ if (thisArg &&
795
+ thisArg.__ajaxHooker &&
796
+ thisArg.__ajaxHooker.proxyXhr === thisArg) {
764
797
  thisArg = thisArg.__ajaxHooker.originalXhr;
765
798
  }
766
799
  return Reflect.apply(this, thisArg, args || []);
@@ -1659,6 +1692,12 @@
1659
1692
  this.set(key, value);
1660
1693
  }
1661
1694
  }
1695
+ [Symbol.dispose]() {
1696
+ this.clear();
1697
+ }
1698
+ async [Symbol.asyncDispose]() {
1699
+ this.clear();
1700
+ }
1662
1701
  /**
1663
1702
  * 获取字典的长度,同this.size
1664
1703
  */
@@ -2170,11 +2209,11 @@
2170
2209
  return "";
2171
2210
  }
2172
2211
  try {
2173
- new Function("_context", "_funcName", "hookFunc", `_context[_funcName] = function ${_funcName}() {
2174
- let args = Array.prototype.slice.call(arguments, 0);
2175
- let obj = this;
2176
- hookFunc.apply(obj, args);
2177
- return _context['realFunc_${_funcName}'].apply(obj, args);
2212
+ new Function("_context", "_funcName", "hookFunc", `_context[_funcName] = function ${_funcName}() {
2213
+ let args = Array.prototype.slice.call(arguments, 0);
2214
+ let obj = this;
2215
+ hookFunc.apply(obj, args);
2216
+ return _context['realFunc_${_funcName}'].apply(obj, args);
2178
2217
  };`)(_context, _funcName, hookFunc);
2179
2218
  _context[_funcName].prototype.isHooked = true;
2180
2219
  return true;
@@ -4194,11 +4233,11 @@
4194
4233
  this.constructors = [];
4195
4234
  let options = {
4196
4235
  target: window,
4197
- entrypoint: 'webpackJsonp',
4236
+ entrypoint: "webpackJsonp",
4198
4237
  debug: false,
4199
4238
  strict: false,
4200
4239
  };
4201
- if (typeof opts === 'object') {
4240
+ if (typeof opts === "object") {
4202
4241
  options = Object.assign(Object.assign({}, options), opts);
4203
4242
  }
4204
4243
  this.target = options.target;
@@ -4237,7 +4276,7 @@
4237
4276
  * @internal
4238
4277
  */
4239
4278
  fillModules() {
4240
- if (typeof this.target[this.entrypoint] === 'function') {
4279
+ if (typeof this.target[this.entrypoint] === "function") {
4241
4280
  this.functionArguments.forEach((argument, index) => {
4242
4281
  try {
4243
4282
  if (this.modules && Object.keys(this.modules).length > 0)
@@ -4264,8 +4303,9 @@
4264
4303
  if (this.modules && Object.keys(this.modules).length == 0) {
4265
4304
  let moduleEnd = false;
4266
4305
  let moduleIterator = 0;
4267
- if (typeof this.target[this.entrypoint] != 'function' || !this.target[this.entrypoint]([], [], [moduleIterator])) {
4268
- throw Error('Unknown Webpack structure');
4306
+ if (typeof this.target[this.entrypoint] != "function" ||
4307
+ !this.target[this.entrypoint]([], [], [moduleIterator])) {
4308
+ throw Error("Unknown Webpack structure");
4269
4309
  }
4270
4310
  while (!moduleEnd) {
4271
4311
  try {
@@ -4298,7 +4338,7 @@
4298
4338
  const originalPush = this.target[this.entrypoint].push;
4299
4339
  this.target[this.entrypoint].push = (...args) => {
4300
4340
  const result = Reflect.apply(originalPush, this.target[this.entrypoint], args);
4301
- document.dispatchEvent(new CustomEvent('moduleraid:webpack-push', { detail: args }));
4341
+ document.dispatchEvent(new CustomEvent("moduleraid:webpack-push", { detail: args }));
4302
4342
  return result;
4303
4343
  };
4304
4344
  }
@@ -4321,13 +4361,15 @@
4321
4361
  }
4322
4362
  let windowObjects = Object.keys(this.target);
4323
4363
  windowObjects = windowObjects
4324
- .filter((object) => object.toLowerCase().includes('chunk') || object.toLowerCase().includes('webpack'))
4325
- .filter((object) => typeof this.target[object] === 'function' || Array.isArray(this.target[object]));
4364
+ .filter((object) => object.toLowerCase().includes("chunk") ||
4365
+ object.toLowerCase().includes("webpack"))
4366
+ .filter((object) => typeof this.target[object] === "function" ||
4367
+ Array.isArray(this.target[object]));
4326
4368
  if (windowObjects.length > 1) {
4327
- throw Error(`Multiple possible endpoints have been detected, please create a new moduleRaid instance with a specific one:\n${windowObjects.join(', ')}`);
4369
+ throw Error(`Multiple possible endpoints have been detected, please create a new moduleRaid instance with a specific one:\n${windowObjects.join(", ")}`);
4328
4370
  }
4329
4371
  if (windowObjects.length === 0) {
4330
- throw Error('No Webpack JSONP entrypoints could be detected');
4372
+ throw Error("No Webpack JSONP entrypoints could be detected");
4331
4373
  }
4332
4374
  this.log(`Entrypoint has been detected at window.${windowObjects[0]} and set for injection`);
4333
4375
  this.entrypoint = windowObjects[0];
@@ -4344,11 +4386,11 @@
4344
4386
  for (const key in object) {
4345
4387
  const value = object[key];
4346
4388
  const lowerCaseQuery = query.toLowerCase();
4347
- if (typeof value != 'object') {
4389
+ if (typeof value != "object") {
4348
4390
  const lowerCaseKey = key.toString().toLowerCase();
4349
4391
  if (lowerCaseKey.includes(lowerCaseQuery))
4350
4392
  return true;
4351
- if (typeof value != 'object') {
4393
+ if (typeof value != "object") {
4352
4394
  const lowerCaseValue = value.toString().toLowerCase();
4353
4395
  if (lowerCaseValue.includes(lowerCaseQuery))
4354
4396
  return true;
@@ -4388,31 +4430,31 @@
4388
4430
  const results = [];
4389
4431
  const modules = Object.keys(this.modules);
4390
4432
  if (modules.length === 0) {
4391
- throw new Error('There are no modules to search through!');
4433
+ throw new Error("There are no modules to search through!");
4392
4434
  }
4393
4435
  modules.forEach((key) => {
4394
4436
  const module = this.modules[key.toString()];
4395
4437
  if (module === undefined)
4396
4438
  return;
4397
4439
  try {
4398
- if (typeof query === 'string') {
4440
+ if (typeof query === "string") {
4399
4441
  query = query.toLowerCase();
4400
4442
  switch (typeof module) {
4401
- case 'string':
4443
+ case "string":
4402
4444
  if (module.toLowerCase().includes(query))
4403
4445
  results.push(module);
4404
4446
  break;
4405
- case 'function':
4447
+ case "function":
4406
4448
  if (module.toString().toLowerCase().includes(query))
4407
4449
  results.push(module);
4408
4450
  break;
4409
- case 'object':
4451
+ case "object":
4410
4452
  if (this.searchObject(module, query))
4411
4453
  results.push(module);
4412
4454
  break;
4413
4455
  }
4414
4456
  }
4415
- else if (typeof query === 'function') {
4457
+ else if (typeof query === "function") {
4416
4458
  if (query(module))
4417
4459
  results.push(module);
4418
4460
  }
@@ -4465,17 +4507,17 @@
4465
4507
  const results = [];
4466
4508
  const constructors = Object.keys(this.constructors);
4467
4509
  if (constructors.length === 0) {
4468
- throw new Error('There are no constructors to search through!');
4510
+ throw new Error("There are no constructors to search through!");
4469
4511
  }
4470
4512
  constructors.forEach((key) => {
4471
4513
  const constructor = this.constructors[key];
4472
4514
  try {
4473
- if (typeof query === 'string') {
4515
+ if (typeof query === "string") {
4474
4516
  query = query.toLowerCase();
4475
4517
  if (constructor.toString().toLowerCase().includes(query))
4476
4518
  results.push([this.constructors[key], this.modules[key]]);
4477
4519
  }
4478
- else if (typeof query === 'function') {
4520
+ else if (typeof query === "function") {
4479
4521
  if (query(constructor))
4480
4522
  results.push([this.constructors[key], this.modules[key]]);
4481
4523
  }
@@ -5682,8 +5724,8 @@
5682
5724
  let timer = null;
5683
5725
  const that = this;
5684
5726
  return function (...args) {
5685
- that.workerClearTimeout(timer);
5686
- timer = that.workerSetTimeout(function () {
5727
+ clearTimeout(timer);
5728
+ timer = setTimeout(function () {
5687
5729
  fn.apply(that, args);
5688
5730
  }, delay);
5689
5731
  };
@@ -5702,7 +5744,6 @@
5702
5744
  **/
5703
5745
  Dictionary = UtilsDictionary;
5704
5746
  downloadBase64(base64Data, fileName, isIFrame = false) {
5705
- const that = this;
5706
5747
  if (typeof base64Data !== "string") {
5707
5748
  throw new Error("Utils.downloadBase64 参数 base64Data 必须为 string 类型");
5708
5749
  }
@@ -5715,7 +5756,7 @@
5715
5756
  $iframe.style.display = "none";
5716
5757
  $iframe.src = base64Data;
5717
5758
  (this.windowApi.document.body || this.windowApi.document.documentElement).appendChild($iframe);
5718
- that.workerSetTimeout(() => {
5759
+ setTimeout(() => {
5719
5760
  $iframe.contentWindow.document.execCommand("SaveAs", true, fileName);
5720
5761
  (this.windowApi.document.body || this.windowApi.document.documentElement).removeChild($iframe);
5721
5762
  }, 100);
@@ -5767,7 +5808,7 @@
5767
5808
  }
5768
5809
  return strFound ? true : false;
5769
5810
  }
5770
- formatByteToSize(byteSize, addType = true) {
5811
+ formatByteToSize(byteSize, addType = true, unit = "1024") {
5771
5812
  byteSize = parseInt(byteSize.toString());
5772
5813
  if (isNaN(byteSize)) {
5773
5814
  throw new Error("Utils.formatByteToSize 参数 byteSize 格式不正确");
@@ -5775,8 +5816,9 @@
5775
5816
  let result = 0;
5776
5817
  let resultType = "KB";
5777
5818
  const sizeData = {};
5819
+ const unitNumber = Number(unit);
5778
5820
  sizeData.B = 1;
5779
- sizeData.KB = 1024;
5821
+ sizeData.KB = unitNumber;
5780
5822
  sizeData.MB = sizeData.KB * sizeData.KB;
5781
5823
  sizeData.GB = sizeData.MB * sizeData.KB;
5782
5824
  sizeData.TB = sizeData.GB * sizeData.KB;
@@ -7613,7 +7655,6 @@
7613
7655
  });
7614
7656
  }
7615
7657
  setTimeout(callback, delayTime = 0) {
7616
- const that = this;
7617
7658
  if (typeof callback !== "function" && typeof callback !== "string") {
7618
7659
  throw new TypeError("Utils.setTimeout 参数 callback 必须为 function|string 类型");
7619
7660
  }
@@ -7621,18 +7662,17 @@
7621
7662
  throw new TypeError("Utils.setTimeout 参数 delayTime 必须为 number 类型");
7622
7663
  }
7623
7664
  return new Promise((resolve) => {
7624
- that.workerSetTimeout(() => {
7625
- resolve(that.tryCatch().run(callback));
7665
+ setTimeout(() => {
7666
+ resolve(this.tryCatch().run(callback));
7626
7667
  }, delayTime);
7627
7668
  });
7628
7669
  }
7629
7670
  sleep(delayTime = 0) {
7630
- const that = this;
7631
7671
  if (typeof delayTime !== "number") {
7632
7672
  throw new Error("Utils.sleep 参数 delayTime 必须为 number 类型");
7633
7673
  }
7634
7674
  return new Promise((resolve) => {
7635
- that.workerSetTimeout(() => {
7675
+ setTimeout(() => {
7636
7676
  resolve(void 0);
7637
7677
  }, delayTime);
7638
7678
  });
@@ -7958,13 +7998,12 @@
7958
7998
  });
7959
7999
  }
7960
8000
  waitPropertyByInterval(checkFn, propertyName, intervalTimer = 250, maxTime = -1) {
7961
- const that = this;
7962
8001
  if (checkFn == null) {
7963
8002
  throw new TypeError("checkObj 不能为空对象 ");
7964
8003
  }
7965
8004
  let isResolve = false;
7966
8005
  return new Promise((resolve, reject) => {
7967
- const interval = that.workerSetInterval(() => {
8006
+ const interval = setInterval(() => {
7968
8007
  let inst = checkFn;
7969
8008
  if (typeof checkFn === "function") {
7970
8009
  inst = checkFn();
@@ -7977,14 +8016,14 @@
7977
8016
  }
7978
8017
  if ((typeof propertyName === "function" && propertyName(inst)) || Reflect.has(inst, propertyName)) {
7979
8018
  isResolve = true;
7980
- that.workerClearInterval(interval);
8019
+ clearInterval(interval);
7981
8020
  resolve(inst[propertyName]);
7982
8021
  }
7983
8022
  }, intervalTimer);
7984
8023
  if (maxTime !== -1) {
7985
- that.workerSetTimeout(() => {
8024
+ setTimeout(() => {
7986
8025
  if (!isResolve) {
7987
- that.workerClearInterval(interval);
8026
+ clearInterval(interval);
7988
8027
  reject();
7989
8028
  }
7990
8029
  }, maxTime);
@@ -8206,9 +8245,8 @@
8206
8245
  workerSetTimeout(callback, timeout = 0) {
8207
8246
  try {
8208
8247
  return setTimeout$1(callback, timeout);
8209
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
8210
8248
  }
8211
- catch (error) {
8249
+ catch {
8212
8250
  return this.windowApi.setTimeout(callback, timeout);
8213
8251
  }
8214
8252
  }
@@ -8221,12 +8259,8 @@
8221
8259
  if (timeId != null) {
8222
8260
  clearTimeout$1(timeId);
8223
8261
  }
8224
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
8225
- }
8226
- catch (error) {
8227
- // console.log(error);
8228
8262
  }
8229
- finally {
8263
+ catch {
8230
8264
  this.windowApi.clearTimeout(timeId);
8231
8265
  }
8232
8266
  }
@@ -8237,10 +8271,9 @@
8237
8271
  */
8238
8272
  workerSetInterval(callback, timeout = 0) {
8239
8273
  try {
8240
- return setInterval(callback, timeout);
8241
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
8274
+ return setInterval$1(callback, timeout);
8242
8275
  }
8243
- catch (error) {
8276
+ catch {
8244
8277
  return this.windowApi.setInterval(callback, timeout);
8245
8278
  }
8246
8279
  }
@@ -8251,14 +8284,10 @@
8251
8284
  workerClearInterval(timeId) {
8252
8285
  try {
8253
8286
  if (timeId != null) {
8254
- clearInterval(timeId);
8287
+ clearInterval$1(timeId);
8255
8288
  }
8256
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
8257
- }
8258
- catch (error) {
8259
- // console.log(error);
8260
8289
  }
8261
- finally {
8290
+ catch {
8262
8291
  this.windowApi.clearInterval(timeId);
8263
8292
  }
8264
8293
  }
@@ -8279,6 +8308,66 @@
8279
8308
  return new FunctionConstructor(...args);
8280
8309
  }
8281
8310
  }
8311
+ /**
8312
+ * 判断页面中是否存在`worker-src`的CSP规则
8313
+ */
8314
+ hasWorkerCSP() {
8315
+ return new Promise((resolve) => {
8316
+ let flag = true;
8317
+ let workerBlobUrl = void 0;
8318
+ const workerJs = /*js*/ `
8319
+ (() => {
8320
+ this.addEventListener(
8321
+ "message",
8322
+ function () {
8323
+ this.postMessage({
8324
+ success: true,
8325
+ });
8326
+ },
8327
+ {
8328
+ capture: true,
8329
+ }
8330
+ );
8331
+ })();`;
8332
+ try {
8333
+ const workerScript = new Blob([workerJs], {
8334
+ type: "application/javascript",
8335
+ });
8336
+ workerBlobUrl = window.URL.createObjectURL(workerScript);
8337
+ // @ts-expect-error
8338
+ if (globalThis.trustedTypes && typeof globalThis.trustedTypes.createPolicy === "function") {
8339
+ // 使用这个后虽然不报错,但是仍会有blob错误
8340
+ // violates the following Content Security Policy directive: "worker-src 'self'". The action has been blocked.
8341
+ // 且这个错误无法使用try/catch捕捉,导致本该提醒使用手动匹配的结果并无提醒弹窗
8342
+ // @ts-expect-error
8343
+ const workerPolicy = globalThis.trustedTypes.createPolicy("workerPolicy", {
8344
+ createScriptURL: (url) => url,
8345
+ });
8346
+ workerBlobUrl = workerPolicy.createScriptURL(workerBlobUrl);
8347
+ }
8348
+ const worker = new Worker(workerBlobUrl);
8349
+ worker.onmessage = (data) => {
8350
+ if (data.data.success) {
8351
+ flag = false;
8352
+ }
8353
+ };
8354
+ setTimeout(() => {
8355
+ worker.terminate();
8356
+ resolve(flag);
8357
+ }, 500);
8358
+ worker.postMessage("test");
8359
+ }
8360
+ catch {
8361
+ flag = true;
8362
+ }
8363
+ finally {
8364
+ // 释放
8365
+ if (typeof workerBlobUrl === "string") {
8366
+ globalThis.URL.revokeObjectURL(workerBlobUrl);
8367
+ }
8368
+ }
8369
+ });
8370
+ }
8282
8371
  }
8283
8372
  const utils = new Utils();
8284
8373