@whitesev/utils 2.9.4 → 2.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  class ColorConversion {
2
2
  /**
3
3
  * 判断是否是16进制颜色
4
- * @param str
4
+ * @param str 十六进制颜色,如`#000000`
5
5
  */
6
6
  isHex(str) {
7
7
  if (typeof str !== "string") {
@@ -16,8 +16,8 @@ class ColorConversion {
16
16
  * 16进制颜色转rgba
17
17
  *
18
18
  * 例如:`#ff0000` 转为 `rgba(123,123,123, 0.4)`
19
- * @param hex
20
- * @param opacity
19
+ * @param hex 十六进制颜色,如`#000000`
20
+ * @param opacity 透明度,0~1
21
21
  */
22
22
  hexToRgba(hex, opacity) {
23
23
  if (!this.isHex(hex)) {
@@ -29,16 +29,16 @@ class ColorConversion {
29
29
  }
30
30
  /**
31
31
  * hex转rgb
32
- * @param str
32
+ * @param hex 十六进制颜色,如`#000000`
33
33
  */
34
- hexToRgb(str) {
35
- if (!this.isHex(str)) {
36
- throw new TypeError(`输入错误的hex:${str}`);
34
+ hexToRgb(hex) {
35
+ if (!this.isHex(hex)) {
36
+ throw new TypeError(`输入错误的hex:${hex}`);
37
37
  }
38
38
  /* replace替换查找的到的字符串 */
39
- str = str.replace("#", "");
39
+ hex = hex.replace("#", "");
40
40
  /* match得到查询数组 */
41
- const hxs = str.match(/../g);
41
+ const hxs = hex.match(/../g);
42
42
  for (let index = 0; index < 3; index++) {
43
43
  const value = parseInt(hxs[index], 16);
44
44
  Reflect.set(hxs, index, value);
@@ -47,9 +47,10 @@ class ColorConversion {
47
47
  }
48
48
  /**
49
49
  * rgb转hex
50
- * @param redValue
51
- * @param greenValue
52
- * @param blueValue
50
+ * @param redValue 红色值
51
+ * @param greenValue 绿色值
52
+ * @param blueValue 蓝色值
53
+ * @returns hex
53
54
  */
54
55
  rgbToHex(redValue, greenValue, blueValue) {
55
56
  /* 验证输入的rgb值是否合法 */
@@ -66,30 +67,42 @@ class ColorConversion {
66
67
  }
67
68
  /**
68
69
  * 获取颜色变暗或亮
69
- * @param color 颜色
70
- * @param level 0~1.0
70
+ * @param color hex颜色,如`#000000`
71
+ * @param level 0~1.0 系数越大,颜色越变暗
71
72
  */
72
73
  getDarkColor(color, level) {
73
74
  if (!this.isHex(color)) {
74
75
  throw new TypeError(`输入错误的hex:${color}`);
75
76
  }
77
+ if (typeof level !== "number") {
78
+ level = Number(level);
79
+ }
80
+ if (isNaN(level)) {
81
+ throw new TypeError(`输入错误的level:${level}`);
82
+ }
76
83
  const rgbc = this.hexToRgb(color);
77
84
  for (let index = 0; index < 3; index++) {
78
85
  const rgbcItemValue = rgbc[index];
79
- const value = Math.floor(Number(rgbcItemValue) * (1 - Number(level)));
86
+ const value = Math.floor(Number(rgbcItemValue) * (1 - level));
80
87
  Reflect.set(rgbc, index, value);
81
88
  }
82
89
  return this.rgbToHex(rgbc[0], rgbc[1], rgbc[2]);
83
90
  }
84
91
  /**
85
92
  * 获取颜色变亮
86
- * @param color 颜色
87
- * @param level 0~1.0
93
+ * @param color hex颜色,如`#000000`
94
+ * @param level 0~1.0 系数越大,颜色越变亮
88
95
  */
89
96
  getLightColor(color, level) {
90
97
  if (!this.isHex(color)) {
91
98
  throw new TypeError(`输入错误的hex:${color}`);
92
99
  }
100
+ if (typeof level !== "number") {
101
+ level = Number(level);
102
+ }
103
+ if (isNaN(level)) {
104
+ throw new TypeError(`输入错误的level:${level}`);
105
+ }
93
106
  const rgbc = this.hexToRgb(color);
94
107
  for (let index = 0; index < 3; index++) {
95
108
  const rgbcItemValue = Number(rgbc[index]);
@@ -573,7 +586,7 @@ class UtilsGMCookie {
573
586
  }
574
587
  }
575
588
  /**
576
- * 获取多组Cookie
589
+ * 获取多组Cookie
577
590
  * @param option 配置
578
591
  **/
579
592
  getList(option) {
@@ -686,7 +699,8 @@ class UtilsGMCookie {
686
699
  }
687
700
  }
688
701
  /**
689
- * 解析cookie字符串
702
+ * 解析cookie字符串,按`;`分割
703
+ *
690
704
  * 例如:document.cookie
691
705
  * @param cookieStr
692
706
  */
@@ -711,1001 +725,981 @@ class UtilsGMCookie {
711
725
  }
712
726
  }
713
727
 
714
- /* eslint-disable */
715
- // ==UserScript==
716
- // @name ajaxHooker
717
- // @author cxxjackie
718
- // @version 1.4.8
719
- // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
720
- // @license GNU LGPL-3.0
721
- // ==/UserScript==
722
-
723
- const ajaxHooker = function () {
724
- const version = "1.4.8";
725
- const hookInst = {
726
- hookFns: [],
727
- filters: [],
728
- };
729
- const win = window.unsafeWindow || document.defaultView || window;
730
- let winAh = win.__ajaxHooker;
731
- const resProto = win.Response.prototype;
732
- const xhrResponses = ["response", "responseText", "responseXML"];
733
- const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
734
- const xhrExtraProps = ["responseType", "timeout", "withCredentials"];
735
- const fetchExtraProps = [
736
- "cache",
737
- "credentials",
738
- "integrity",
739
- "keepalive",
740
- "mode",
741
- "priority",
742
- "redirect",
743
- "referrer",
744
- "referrerPolicy",
745
- "signal",
746
- ];
747
- const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
748
- const getType = {}.toString.call.bind({}.toString);
749
- const getDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
750
- const emptyFn = () => {};
751
- const errorFn = (e) => console.error(e);
752
- function isThenable(obj) {
753
- return obj && ["object", "function"].includes(typeof obj) && typeof obj.then === "function";
754
- }
755
- function catchError(fn, ...args) {
756
- try {
757
- const result = fn(...args);
758
- if (isThenable(result)) return result.then(null, errorFn);
759
- return result;
760
- } catch (err) {
761
- console.error(err);
762
- }
763
- }
764
- function defineProp(obj, prop, getter, setter) {
765
- Object.defineProperty(obj, prop, {
766
- configurable: true,
767
- enumerable: true,
768
- get: getter,
769
- set: setter,
770
- });
771
- }
772
- function readonly(obj, prop, value = obj[prop]) {
773
- defineProp(obj, prop, () => value, emptyFn);
774
- }
775
- function writable(obj, prop, value = obj[prop]) {
776
- Object.defineProperty(obj, prop, {
777
- configurable: true,
778
- enumerable: true,
779
- writable: true,
780
- value: value,
781
- });
782
- }
783
- function parseHeaders(obj) {
784
- const headers = {};
785
- switch (getType(obj)) {
786
- case "[object String]":
787
- for (const line of obj.trim().split(/[\r\n]+/)) {
788
- const [header, value] = line.split(/(?<=^[^:]+)\s*:\s*/);
789
- if (!value) continue;
790
- const lheader = header.toLowerCase();
791
- headers[lheader] = lheader in headers ? `${headers[lheader]}, ${value}` : value;
792
- }
793
- break;
794
- case "[object Headers]":
795
- for (const [key, val] of obj) {
796
- headers[key] = val;
797
- }
798
- break;
799
- case "[object Object]":
800
- return { ...obj };
801
- }
802
- return headers;
803
- }
804
- function stopImmediatePropagation() {
805
- this.ajaxHooker_isStopped = true;
806
- }
807
- class SyncThenable {
808
- then(fn) {
809
- fn && fn();
810
- return new SyncThenable();
811
- }
812
- }
813
- class AHRequest {
814
- constructor(request) {
815
- this.request = request;
816
- this.requestClone = { ...this.request };
817
- }
818
- _recoverRequestKey(key) {
819
- if (key in this.requestClone) this.request[key] = this.requestClone[key];
820
- else delete this.request[key];
821
- }
822
- shouldFilter(filters) {
823
- const { type, url, method, async } = this.request;
824
- return (
825
- filters.length &&
826
- !filters.find((obj) => {
827
- switch (true) {
828
- case obj.type && obj.type !== type:
829
- case getType(obj.url) === "[object String]" && !url.includes(obj.url):
830
- case getType(obj.url) === "[object RegExp]" && !obj.url.test(url):
831
- case obj.method && obj.method.toUpperCase() !== method.toUpperCase():
832
- case "async" in obj && obj.async !== async:
833
- return false;
834
- }
835
- return true;
836
- })
837
- );
838
- }
839
- waitForRequestKeys() {
840
- if (!this.request.async) {
841
- win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
842
- if (this.shouldFilter(filters)) return;
843
- hookFns.forEach((fn) => {
844
- if (getType(fn) === "[object Function]") catchError(fn, this.request);
845
- });
846
- for (const key in this.request) {
847
- if (isThenable(this.request[key])) this._recoverRequestKey(key);
848
- }
849
- });
850
- return new SyncThenable();
851
- }
852
- const promises = [];
853
- const ignoreKeys = new Set(["type", "async", "response"]);
854
- win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
855
- if (this.shouldFilter(filters)) return;
856
- promises.push(
857
- Promise.all(hookFns.map((fn) => catchError(fn, this.request))).then(() => {
858
- const requestKeys = [];
859
- for (const key in this.request) !ignoreKeys.has(key) && requestKeys.push(key);
860
- return Promise.all(
861
- requestKeys.map((key) =>
862
- Promise.resolve(this.request[key]).then(
863
- (val) => (this.request[key] = val),
864
- () => this._recoverRequestKey(key)
865
- )
866
- )
867
- );
868
- })
869
- );
870
- });
871
- return Promise.all(promises);
872
- }
873
- waitForResponseKeys(response) {
874
- const responseKeys = this.request.type === "xhr" ? xhrResponses : fetchResponses;
875
- if (!this.request.async) {
876
- if (getType(this.request.response) === "[object Function]") {
877
- catchError(this.request.response, response);
878
- responseKeys.forEach((key) => {
879
- if ("get" in getDescriptor(response, key) || isThenable(response[key])) {
880
- delete response[key];
881
- }
882
- });
883
- }
884
- return new SyncThenable();
885
- }
886
- return Promise.resolve(catchError(this.request.response, response)).then(() =>
887
- Promise.all(
888
- responseKeys.map((key) => {
889
- const descriptor = getDescriptor(response, key);
890
- if (descriptor && "value" in descriptor) {
891
- return Promise.resolve(descriptor.value).then(
892
- (val) => (response[key] = val),
893
- () => delete response[key]
894
- );
895
- } else {
896
- delete response[key];
897
- }
898
- })
899
- )
900
- );
901
- }
902
- }
903
- const proxyHandler = {
904
- get(target, prop) {
905
- const descriptor = getDescriptor(target, prop);
906
- if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.get)
907
- return target[prop];
908
- const ah = target.__ajaxHooker;
909
- if (ah && ah.proxyProps) {
910
- if (prop in ah.proxyProps) {
911
- const pDescriptor = ah.proxyProps[prop];
912
- if ("get" in pDescriptor) return pDescriptor.get();
913
- if (typeof pDescriptor.value === "function") return pDescriptor.value.bind(ah);
914
- return pDescriptor.value;
915
- }
916
- if (typeof target[prop] === "function") return target[prop].bind(target);
917
- }
918
- return target[prop];
919
- },
920
- set(target, prop, value) {
921
- const descriptor = getDescriptor(target, prop);
922
- if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.set) return true;
923
- const ah = target.__ajaxHooker;
924
- if (ah && ah.proxyProps && prop in ah.proxyProps) {
925
- const pDescriptor = ah.proxyProps[prop];
926
- pDescriptor.set ? pDescriptor.set(value) : (pDescriptor.value = value);
927
- } else {
928
- target[prop] = value;
929
- }
930
- return true;
931
- },
932
- };
933
- class XhrHooker {
934
- constructor(xhr) {
935
- const ah = this;
936
- Object.assign(ah, {
937
- originalXhr: xhr,
938
- proxyXhr: new Proxy(xhr, proxyHandler),
939
- resThenable: new SyncThenable(),
940
- proxyProps: {},
941
- proxyEvents: {},
942
- });
943
- xhr.addEventListener("readystatechange", (e) => {
944
- if (ah.proxyXhr.readyState === 4 && ah.request && typeof ah.request.response === "function") {
945
- const response = {
946
- finalUrl: ah.proxyXhr.responseURL,
947
- status: ah.proxyXhr.status,
948
- responseHeaders: parseHeaders(ah.proxyXhr.getAllResponseHeaders()),
949
- };
950
- const tempValues = {};
951
- for (const key of xhrResponses) {
952
- try {
953
- tempValues[key] = ah.originalXhr[key];
954
- } catch (err) {}
955
- defineProp(
956
- response,
957
- key,
958
- () => {
959
- return (response[key] = tempValues[key]);
960
- },
961
- (val) => {
962
- delete response[key];
963
- response[key] = val;
964
- }
965
- );
966
- }
967
- ah.resThenable = new AHRequest(ah.request).waitForResponseKeys(response).then(() => {
968
- for (const key of xhrResponses) {
969
- ah.proxyProps[key] = {
970
- get: () => {
971
- if (!(key in response)) response[key] = tempValues[key];
972
- return response[key];
973
- },
974
- };
975
- }
976
- });
977
- }
978
- ah.dispatchEvent(e);
979
- });
980
- xhr.addEventListener("load", (e) => ah.dispatchEvent(e));
981
- xhr.addEventListener("loadend", (e) => ah.dispatchEvent(e));
982
- for (const evt of xhrAsyncEvents) {
983
- const onEvt = "on" + evt;
984
- ah.proxyProps[onEvt] = {
985
- get: () => ah.proxyEvents[onEvt] || null,
986
- set: (val) => ah.addEvent(onEvt, val),
987
- };
988
- }
989
- for (const method of ["setRequestHeader", "addEventListener", "removeEventListener", "open", "send"]) {
990
- ah.proxyProps[method] = { value: ah[method] };
991
- }
992
- }
993
- toJSON() {} // Converting circular structure to JSON
994
- addEvent(type, event) {
995
- if (type.startsWith("on")) {
996
- this.proxyEvents[type] = typeof event === "function" ? event : null;
997
- } else {
998
- if (typeof event === "object" && event !== null) event = event.handleEvent;
999
- if (typeof event !== "function") return;
1000
- this.proxyEvents[type] = this.proxyEvents[type] || new Set();
1001
- this.proxyEvents[type].add(event);
1002
- }
1003
- }
1004
- removeEvent(type, event) {
1005
- if (type.startsWith("on")) {
1006
- this.proxyEvents[type] = null;
1007
- } else {
1008
- if (typeof event === "object" && event !== null) event = event.handleEvent;
1009
- this.proxyEvents[type] && this.proxyEvents[type].delete(event);
1010
- }
1011
- }
1012
- dispatchEvent(e) {
1013
- e.stopImmediatePropagation = stopImmediatePropagation;
1014
- defineProp(e, "target", () => this.proxyXhr);
1015
- defineProp(e, "currentTarget", () => this.proxyXhr);
1016
- defineProp(e, "srcElement", () => this.proxyXhr);
1017
- this.proxyEvents[e.type] &&
1018
- this.proxyEvents[e.type].forEach((fn) => {
1019
- this.resThenable.then(() => !e.ajaxHooker_isStopped && fn.call(this.proxyXhr, e));
1020
- });
1021
- if (e.ajaxHooker_isStopped) return;
1022
- const onEvent = this.proxyEvents["on" + e.type];
1023
- onEvent && this.resThenable.then(onEvent.bind(this.proxyXhr, e));
1024
- }
1025
- setRequestHeader(header, value) {
1026
- this.originalXhr.setRequestHeader(header, value);
1027
- if (!this.request) return;
1028
- const headers = this.request.headers;
1029
- headers[header] = header in headers ? `${headers[header]}, ${value}` : value;
1030
- }
1031
- addEventListener(...args) {
1032
- if (xhrAsyncEvents.includes(args[0])) {
1033
- this.addEvent(args[0], args[1]);
1034
- } else {
1035
- this.originalXhr.addEventListener(...args);
1036
- }
1037
- }
1038
- removeEventListener(...args) {
1039
- if (xhrAsyncEvents.includes(args[0])) {
1040
- this.removeEvent(args[0], args[1]);
1041
- } else {
1042
- this.originalXhr.removeEventListener(...args);
1043
- }
1044
- }
1045
- open(method, url, async = true, ...args) {
1046
- this.request = {
1047
- type: "xhr",
1048
- url: url.toString(),
1049
- method: method.toUpperCase(),
1050
- abort: false,
1051
- headers: {},
1052
- data: null,
1053
- response: null,
1054
- async: !!async,
1055
- };
1056
- this.openArgs = args;
1057
- this.resThenable = new SyncThenable();
1058
- ["responseURL", "readyState", "status", "statusText", ...xhrResponses].forEach((key) => {
1059
- delete this.proxyProps[key];
1060
- });
1061
- return this.originalXhr.open(method, url, async, ...args);
1062
- }
1063
- send(data) {
1064
- const ah = this;
1065
- const xhr = ah.originalXhr;
1066
- const request = ah.request;
1067
- if (!request) return xhr.send(data);
1068
- request.data = data;
1069
- new AHRequest(request).waitForRequestKeys().then(() => {
1070
- if (request.abort) {
1071
- if (typeof request.response === "function") {
1072
- Object.assign(ah.proxyProps, {
1073
- responseURL: { value: request.url },
1074
- readyState: { value: 4 },
1075
- status: { value: 200 },
1076
- statusText: { value: "OK" },
1077
- });
1078
- xhrAsyncEvents.forEach((evt) => xhr.dispatchEvent(new Event(evt)));
1079
- }
1080
- } else {
1081
- xhr.open(request.method, request.url, request.async, ...ah.openArgs);
1082
- for (const header in request.headers) {
1083
- xhr.setRequestHeader(header, request.headers[header]);
1084
- }
1085
- for (const prop of xhrExtraProps) {
1086
- if (prop in request) xhr[prop] = request[prop];
1087
- }
1088
- xhr.send(request.data);
1089
- }
1090
- });
1091
- }
1092
- }
1093
- function fakeXHR() {
1094
- const xhr = new winAh.realXHR();
1095
- if ("__ajaxHooker" in xhr) console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1096
- xhr.__ajaxHooker = new XhrHooker(xhr);
1097
- return xhr.__ajaxHooker.proxyXhr;
1098
- }
1099
- fakeXHR.prototype = win.XMLHttpRequest.prototype;
1100
- Object.keys(win.XMLHttpRequest).forEach((key) => (fakeXHR[key] = win.XMLHttpRequest[key]));
1101
- function fakeFetch(url, options = {}) {
1102
- if (!url) return winAh.realFetch.call(win, url, options);
1103
- return new Promise(async (resolve, reject) => {
1104
- const init = {};
1105
- if (getType(url) === "[object Request]") {
1106
- init.method = url.method;
1107
- init.headers = url.headers;
1108
- if (url.body) init.body = await url.arrayBuffer();
1109
- for (const prop of fetchExtraProps) init[prop] = url[prop];
1110
- url = url.url;
1111
- }
1112
- url = url.toString();
1113
- Object.assign(init, options);
1114
- init.method = init.method || "GET";
1115
- init.headers = init.headers || {};
1116
- const request = {
1117
- type: "fetch",
1118
- url: url,
1119
- method: init.method.toUpperCase(),
1120
- abort: false,
1121
- headers: parseHeaders(init.headers),
1122
- data: init.body,
1123
- response: null,
1124
- async: true,
1125
- };
1126
- const req = new AHRequest(request);
1127
- await req.waitForRequestKeys();
1128
- if (request.abort) {
1129
- if (typeof request.response === "function") {
1130
- const response = {
1131
- finalUrl: request.url,
1132
- status: 200,
1133
- responseHeaders: {},
1134
- };
1135
- await req.waitForResponseKeys(response);
1136
- const key = fetchResponses.find((k) => k in response);
1137
- let val = response[key];
1138
- if (key === "json" && typeof val === "object") {
1139
- val = catchError(JSON.stringify.bind(JSON), val);
1140
- }
1141
- const res = new Response(val, {
1142
- status: 200,
1143
- statusText: "OK",
1144
- });
1145
- defineProp(res, "type", () => "basic");
1146
- defineProp(res, "url", () => request.url);
1147
- resolve(res);
1148
- } else {
1149
- reject(new DOMException("aborted", "AbortError"));
1150
- }
1151
- return;
1152
- }
1153
- init.method = request.method;
1154
- init.headers = request.headers;
1155
- init.body = request.data;
1156
- for (const prop of fetchExtraProps) {
1157
- if (prop in request) init[prop] = request[prop];
1158
- }
1159
- winAh.realFetch.call(win, request.url, init).then((res) => {
1160
- if (typeof request.response === "function") {
1161
- const response = {
1162
- finalUrl: res.url,
1163
- status: res.status,
1164
- responseHeaders: parseHeaders(res.headers),
1165
- };
1166
- if (res.ok) {
1167
- fetchResponses.forEach(
1168
- (key) =>
1169
- (res[key] = function () {
1170
- if (key in response) return Promise.resolve(response[key]);
1171
- return resProto[key].call(this).then((val) => {
1172
- response[key] = val;
1173
- return req
1174
- .waitForResponseKeys(response)
1175
- .then(() => (key in response ? response[key] : val));
1176
- });
1177
- })
1178
- );
1179
- } else {
1180
- catchError(request.response, response);
1181
- }
1182
- }
1183
- resolve(res);
1184
- }, reject);
1185
- });
1186
- }
1187
- function fakeFetchClone() {
1188
- const descriptors = Object.getOwnPropertyDescriptors(this);
1189
- const res = winAh.realFetchClone.call(this);
1190
- Object.defineProperties(res, descriptors);
1191
- return res;
1192
- }
1193
- winAh = win.__ajaxHooker = winAh || {
1194
- version,
1195
- fakeXHR,
1196
- fakeFetch,
1197
- fakeFetchClone,
1198
- realXHR: win.XMLHttpRequest,
1199
- realFetch: win.fetch,
1200
- realFetchClone: resProto.clone,
1201
- hookInsts: new Set(),
1202
- };
1203
- if (winAh.version !== version) console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1204
- win.XMLHttpRequest = winAh.fakeXHR;
1205
- win.fetch = winAh.fakeFetch;
1206
- resProto.clone = winAh.fakeFetchClone;
1207
- winAh.hookInsts.add(hookInst);
1208
- // 针对头条、抖音 secsdk.umd.js 的兼容性处理
1209
- class AHFunction extends Function {
1210
- call(thisArg, ...args) {
1211
- if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
1212
- thisArg = thisArg.__ajaxHooker.originalXhr;
1213
- }
1214
- return Reflect.apply(this, thisArg, args);
1215
- }
1216
- apply(thisArg, args) {
1217
- if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
1218
- thisArg = thisArg.__ajaxHooker.originalXhr;
1219
- }
1220
- return Reflect.apply(this, thisArg, args || []);
1221
- }
1222
- }
1223
- function hookSecsdk(csrf) {
1224
- Object.setPrototypeOf(csrf.nativeXMLHttpRequestSetRequestHeader, AHFunction.prototype);
1225
- Object.setPrototypeOf(csrf.nativeXMLHttpRequestOpen, AHFunction.prototype);
1226
- Object.setPrototypeOf(csrf.nativeXMLHttpRequestSend, AHFunction.prototype);
1227
- }
1228
- if (win.secsdk) {
1229
- if (win.secsdk.csrf && win.secsdk.csrf.nativeXMLHttpRequestOpen) hookSecsdk(win.secsdk.csrf);
1230
- } else {
1231
- defineProp(win, "secsdk", emptyFn, (secsdk) => {
1232
- delete win.secsdk;
1233
- win.secsdk = secsdk;
1234
- defineProp(secsdk, "csrf", emptyFn, (csrf) => {
1235
- delete secsdk.csrf;
1236
- secsdk.csrf = csrf;
1237
- if (csrf.nativeXMLHttpRequestOpen) hookSecsdk(csrf);
1238
- });
1239
- });
1240
- }
1241
- return {
1242
- hook: (fn) => hookInst.hookFns.push(fn),
1243
- filter: (arr) => {
1244
- if (Array.isArray(arr)) hookInst.filters = arr;
1245
- },
1246
- protect: () => {
1247
- readonly(win, "XMLHttpRequest", winAh.fakeXHR);
1248
- readonly(win, "fetch", winAh.fakeFetch);
1249
- readonly(resProto, "clone", winAh.fakeFetchClone);
1250
- },
1251
- unhook: () => {
1252
- winAh.hookInsts.delete(hookInst);
1253
- if (!winAh.hookInsts.size) {
1254
- writable(win, "XMLHttpRequest", winAh.realXHR);
1255
- writable(win, "fetch", winAh.realFetch);
1256
- writable(resProto, "clone", winAh.realFetchClone);
1257
- delete win.__ajaxHooker;
1258
- }
1259
- },
1260
- };
728
+ /* eslint-disable */
729
+ // ==UserScript==
730
+ // @name ajaxHooker
731
+ // @author cxxjackie
732
+ // @version 1.4.8
733
+ // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
734
+ // @license GNU LGPL-3.0
735
+ // ==/UserScript==
736
+ const ajaxHooker = function () {
737
+ const version = "1.4.8";
738
+ const hookInst = {
739
+ hookFns: [],
740
+ filters: [],
741
+ };
742
+ const win = window.unsafeWindow || document.defaultView || window;
743
+ let winAh = win.__ajaxHooker;
744
+ const resProto = win.Response.prototype;
745
+ const xhrResponses = ["response", "responseText", "responseXML"];
746
+ const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
747
+ const xhrExtraProps = ["responseType", "timeout", "withCredentials"];
748
+ const fetchExtraProps = [
749
+ "cache",
750
+ "credentials",
751
+ "integrity",
752
+ "keepalive",
753
+ "mode",
754
+ "priority",
755
+ "redirect",
756
+ "referrer",
757
+ "referrerPolicy",
758
+ "signal",
759
+ ];
760
+ const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
761
+ const getType = {}.toString.call.bind({}.toString);
762
+ const getDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
763
+ const emptyFn = () => { };
764
+ const errorFn = (e) => console.error(e);
765
+ function isThenable(obj) {
766
+ return obj && ["object", "function"].includes(typeof obj) && typeof obj.then === "function";
767
+ }
768
+ function catchError(fn, ...args) {
769
+ try {
770
+ const result = fn(...args);
771
+ if (isThenable(result))
772
+ return result.then(null, errorFn);
773
+ return result;
774
+ }
775
+ catch (err) {
776
+ console.error(err);
777
+ }
778
+ }
779
+ function defineProp(obj, prop, getter, setter) {
780
+ Object.defineProperty(obj, prop, {
781
+ configurable: true,
782
+ enumerable: true,
783
+ get: getter,
784
+ set: setter,
785
+ });
786
+ }
787
+ function readonly(obj, prop, value = obj[prop]) {
788
+ defineProp(obj, prop, () => value, emptyFn);
789
+ }
790
+ function writable(obj, prop, value = obj[prop]) {
791
+ Object.defineProperty(obj, prop, {
792
+ configurable: true,
793
+ enumerable: true,
794
+ writable: true,
795
+ value: value,
796
+ });
797
+ }
798
+ function parseHeaders(obj) {
799
+ const headers = {};
800
+ switch (getType(obj)) {
801
+ case "[object String]":
802
+ for (const line of obj.trim().split(/[\r\n]+/)) {
803
+ const [header, value] = line.split(/(?<=^[^:]+)\s*:\s*/);
804
+ if (!value)
805
+ continue;
806
+ const lheader = header.toLowerCase();
807
+ headers[lheader] = lheader in headers ? `${headers[lheader]}, ${value}` : value;
808
+ }
809
+ break;
810
+ case "[object Headers]":
811
+ for (const [key, val] of obj) {
812
+ headers[key] = val;
813
+ }
814
+ break;
815
+ case "[object Object]":
816
+ return { ...obj };
817
+ }
818
+ return headers;
819
+ }
820
+ function stopImmediatePropagation() {
821
+ this.ajaxHooker_isStopped = true;
822
+ }
823
+ class SyncThenable {
824
+ then(fn) {
825
+ fn && fn();
826
+ return new SyncThenable();
827
+ }
828
+ }
829
+ class AHRequest {
830
+ constructor(request) {
831
+ this.request = request;
832
+ this.requestClone = { ...this.request };
833
+ }
834
+ _recoverRequestKey(key) {
835
+ if (key in this.requestClone)
836
+ this.request[key] = this.requestClone[key];
837
+ else
838
+ delete this.request[key];
839
+ }
840
+ shouldFilter(filters) {
841
+ const { type, url, method, async } = this.request;
842
+ return (filters.length &&
843
+ !filters.find((obj) => {
844
+ switch (true) {
845
+ case obj.type && obj.type !== type:
846
+ case getType(obj.url) === "[object String]" && !url.includes(obj.url):
847
+ case getType(obj.url) === "[object RegExp]" && !obj.url.test(url):
848
+ case obj.method && obj.method.toUpperCase() !== method.toUpperCase():
849
+ case "async" in obj && obj.async !== async:
850
+ return false;
851
+ }
852
+ return true;
853
+ }));
854
+ }
855
+ waitForRequestKeys() {
856
+ if (!this.request.async) {
857
+ win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
858
+ if (this.shouldFilter(filters))
859
+ return;
860
+ hookFns.forEach((fn) => {
861
+ if (getType(fn) === "[object Function]")
862
+ catchError(fn, this.request);
863
+ });
864
+ for (const key in this.request) {
865
+ if (isThenable(this.request[key]))
866
+ this._recoverRequestKey(key);
867
+ }
868
+ });
869
+ return new SyncThenable();
870
+ }
871
+ const promises = [];
872
+ const ignoreKeys = new Set(["type", "async", "response"]);
873
+ win.__ajaxHooker.hookInsts.forEach(({ hookFns, filters }) => {
874
+ if (this.shouldFilter(filters))
875
+ return;
876
+ promises.push(Promise.all(hookFns.map((fn) => catchError(fn, this.request))).then(() => {
877
+ const requestKeys = [];
878
+ for (const key in this.request)
879
+ !ignoreKeys.has(key) && requestKeys.push(key);
880
+ return Promise.all(requestKeys.map((key) => Promise.resolve(this.request[key]).then((val) => (this.request[key] = val), () => this._recoverRequestKey(key))));
881
+ }));
882
+ });
883
+ return Promise.all(promises);
884
+ }
885
+ waitForResponseKeys(response) {
886
+ const responseKeys = this.request.type === "xhr" ? xhrResponses : fetchResponses;
887
+ if (!this.request.async) {
888
+ if (getType(this.request.response) === "[object Function]") {
889
+ catchError(this.request.response, response);
890
+ responseKeys.forEach((key) => {
891
+ if ("get" in getDescriptor(response, key) || isThenable(response[key])) {
892
+ delete response[key];
893
+ }
894
+ });
895
+ }
896
+ return new SyncThenable();
897
+ }
898
+ return Promise.resolve(catchError(this.request.response, response)).then(() => Promise.all(responseKeys.map((key) => {
899
+ const descriptor = getDescriptor(response, key);
900
+ if (descriptor && "value" in descriptor) {
901
+ return Promise.resolve(descriptor.value).then((val) => (response[key] = val), () => delete response[key]);
902
+ }
903
+ else {
904
+ delete response[key];
905
+ }
906
+ })));
907
+ }
908
+ }
909
+ const proxyHandler = {
910
+ get(target, prop) {
911
+ const descriptor = getDescriptor(target, prop);
912
+ if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.get)
913
+ return target[prop];
914
+ const ah = target.__ajaxHooker;
915
+ if (ah && ah.proxyProps) {
916
+ if (prop in ah.proxyProps) {
917
+ const pDescriptor = ah.proxyProps[prop];
918
+ if ("get" in pDescriptor)
919
+ return pDescriptor.get();
920
+ if (typeof pDescriptor.value === "function")
921
+ return pDescriptor.value.bind(ah);
922
+ return pDescriptor.value;
923
+ }
924
+ if (typeof target[prop] === "function")
925
+ return target[prop].bind(target);
926
+ }
927
+ return target[prop];
928
+ },
929
+ set(target, prop, value) {
930
+ const descriptor = getDescriptor(target, prop);
931
+ if (descriptor && !descriptor.configurable && !descriptor.writable && !descriptor.set)
932
+ return true;
933
+ const ah = target.__ajaxHooker;
934
+ if (ah && ah.proxyProps && prop in ah.proxyProps) {
935
+ const pDescriptor = ah.proxyProps[prop];
936
+ pDescriptor.set ? pDescriptor.set(value) : (pDescriptor.value = value);
937
+ }
938
+ else {
939
+ target[prop] = value;
940
+ }
941
+ return true;
942
+ },
943
+ };
944
+ class XhrHooker {
945
+ constructor(xhr) {
946
+ const ah = this;
947
+ Object.assign(ah, {
948
+ originalXhr: xhr,
949
+ proxyXhr: new Proxy(xhr, proxyHandler),
950
+ resThenable: new SyncThenable(),
951
+ proxyProps: {},
952
+ proxyEvents: {},
953
+ });
954
+ xhr.addEventListener("readystatechange", (e) => {
955
+ if (ah.proxyXhr.readyState === 4 && ah.request && typeof ah.request.response === "function") {
956
+ const response = {
957
+ finalUrl: ah.proxyXhr.responseURL,
958
+ status: ah.proxyXhr.status,
959
+ responseHeaders: parseHeaders(ah.proxyXhr.getAllResponseHeaders()),
960
+ };
961
+ const tempValues = {};
962
+ for (const key of xhrResponses) {
963
+ try {
964
+ tempValues[key] = ah.originalXhr[key];
965
+ }
966
+ catch (err) { }
967
+ defineProp(response, key, () => {
968
+ return (response[key] = tempValues[key]);
969
+ }, (val) => {
970
+ delete response[key];
971
+ response[key] = val;
972
+ });
973
+ }
974
+ ah.resThenable = new AHRequest(ah.request).waitForResponseKeys(response).then(() => {
975
+ for (const key of xhrResponses) {
976
+ ah.proxyProps[key] = {
977
+ get: () => {
978
+ if (!(key in response))
979
+ response[key] = tempValues[key];
980
+ return response[key];
981
+ },
982
+ };
983
+ }
984
+ });
985
+ }
986
+ ah.dispatchEvent(e);
987
+ });
988
+ xhr.addEventListener("load", (e) => ah.dispatchEvent(e));
989
+ xhr.addEventListener("loadend", (e) => ah.dispatchEvent(e));
990
+ for (const evt of xhrAsyncEvents) {
991
+ const onEvt = "on" + evt;
992
+ ah.proxyProps[onEvt] = {
993
+ get: () => ah.proxyEvents[onEvt] || null,
994
+ set: (val) => ah.addEvent(onEvt, val),
995
+ };
996
+ }
997
+ for (const method of ["setRequestHeader", "addEventListener", "removeEventListener", "open", "send"]) {
998
+ ah.proxyProps[method] = { value: ah[method] };
999
+ }
1000
+ }
1001
+ toJSON() { } // Converting circular structure to JSON
1002
+ addEvent(type, event) {
1003
+ if (type.startsWith("on")) {
1004
+ this.proxyEvents[type] = typeof event === "function" ? event : null;
1005
+ }
1006
+ else {
1007
+ if (typeof event === "object" && event !== null)
1008
+ event = event.handleEvent;
1009
+ if (typeof event !== "function")
1010
+ return;
1011
+ this.proxyEvents[type] = this.proxyEvents[type] || new Set();
1012
+ this.proxyEvents[type].add(event);
1013
+ }
1014
+ }
1015
+ removeEvent(type, event) {
1016
+ if (type.startsWith("on")) {
1017
+ this.proxyEvents[type] = null;
1018
+ }
1019
+ else {
1020
+ if (typeof event === "object" && event !== null)
1021
+ event = event.handleEvent;
1022
+ this.proxyEvents[type] && this.proxyEvents[type].delete(event);
1023
+ }
1024
+ }
1025
+ dispatchEvent(e) {
1026
+ e.stopImmediatePropagation = stopImmediatePropagation;
1027
+ defineProp(e, "target", () => this.proxyXhr);
1028
+ defineProp(e, "currentTarget", () => this.proxyXhr);
1029
+ defineProp(e, "srcElement", () => this.proxyXhr);
1030
+ this.proxyEvents[e.type] &&
1031
+ this.proxyEvents[e.type].forEach((fn) => {
1032
+ this.resThenable.then(() => !e.ajaxHooker_isStopped && fn.call(this.proxyXhr, e));
1033
+ });
1034
+ if (e.ajaxHooker_isStopped)
1035
+ return;
1036
+ const onEvent = this.proxyEvents["on" + e.type];
1037
+ onEvent && this.resThenable.then(onEvent.bind(this.proxyXhr, e));
1038
+ }
1039
+ setRequestHeader(header, value) {
1040
+ this.originalXhr.setRequestHeader(header, value);
1041
+ if (!this.request)
1042
+ return;
1043
+ const headers = this.request.headers;
1044
+ headers[header] = header in headers ? `${headers[header]}, ${value}` : value;
1045
+ }
1046
+ addEventListener(...args) {
1047
+ if (xhrAsyncEvents.includes(args[0])) {
1048
+ this.addEvent(args[0], args[1]);
1049
+ }
1050
+ else {
1051
+ this.originalXhr.addEventListener(...args);
1052
+ }
1053
+ }
1054
+ removeEventListener(...args) {
1055
+ if (xhrAsyncEvents.includes(args[0])) {
1056
+ this.removeEvent(args[0], args[1]);
1057
+ }
1058
+ else {
1059
+ this.originalXhr.removeEventListener(...args);
1060
+ }
1061
+ }
1062
+ open(method, url, async = true, ...args) {
1063
+ this.request = {
1064
+ type: "xhr",
1065
+ url: url.toString(),
1066
+ method: method.toUpperCase(),
1067
+ abort: false,
1068
+ headers: {},
1069
+ data: null,
1070
+ response: null,
1071
+ async: !!async,
1072
+ };
1073
+ this.openArgs = args;
1074
+ this.resThenable = new SyncThenable();
1075
+ ["responseURL", "readyState", "status", "statusText", ...xhrResponses].forEach((key) => {
1076
+ delete this.proxyProps[key];
1077
+ });
1078
+ return this.originalXhr.open(method, url, async, ...args);
1079
+ }
1080
+ send(data) {
1081
+ const ah = this;
1082
+ const xhr = ah.originalXhr;
1083
+ const request = ah.request;
1084
+ if (!request)
1085
+ return xhr.send(data);
1086
+ request.data = data;
1087
+ new AHRequest(request).waitForRequestKeys().then(() => {
1088
+ if (request.abort) {
1089
+ if (typeof request.response === "function") {
1090
+ Object.assign(ah.proxyProps, {
1091
+ responseURL: { value: request.url },
1092
+ readyState: { value: 4 },
1093
+ status: { value: 200 },
1094
+ statusText: { value: "OK" },
1095
+ });
1096
+ xhrAsyncEvents.forEach((evt) => xhr.dispatchEvent(new Event(evt)));
1097
+ }
1098
+ }
1099
+ else {
1100
+ xhr.open(request.method, request.url, request.async, ...ah.openArgs);
1101
+ for (const header in request.headers) {
1102
+ xhr.setRequestHeader(header, request.headers[header]);
1103
+ }
1104
+ for (const prop of xhrExtraProps) {
1105
+ if (prop in request)
1106
+ xhr[prop] = request[prop];
1107
+ }
1108
+ xhr.send(request.data);
1109
+ }
1110
+ });
1111
+ }
1112
+ }
1113
+ function fakeXHR() {
1114
+ const xhr = new winAh.realXHR();
1115
+ if ("__ajaxHooker" in xhr)
1116
+ console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1117
+ xhr.__ajaxHooker = new XhrHooker(xhr);
1118
+ return xhr.__ajaxHooker.proxyXhr;
1119
+ }
1120
+ fakeXHR.prototype = win.XMLHttpRequest.prototype;
1121
+ Object.keys(win.XMLHttpRequest).forEach((key) => (fakeXHR[key] = win.XMLHttpRequest[key]));
1122
+ function fakeFetch(url, options = {}) {
1123
+ if (!url)
1124
+ return winAh.realFetch.call(win, url, options);
1125
+ return new Promise(async (resolve, reject) => {
1126
+ const init = {};
1127
+ if (getType(url) === "[object Request]") {
1128
+ init.method = url.method;
1129
+ init.headers = url.headers;
1130
+ if (url.body)
1131
+ init.body = await url.arrayBuffer();
1132
+ for (const prop of fetchExtraProps)
1133
+ init[prop] = url[prop];
1134
+ url = url.url;
1135
+ }
1136
+ url = url.toString();
1137
+ Object.assign(init, options);
1138
+ init.method = init.method || "GET";
1139
+ init.headers = init.headers || {};
1140
+ const request = {
1141
+ type: "fetch",
1142
+ url: url,
1143
+ method: init.method.toUpperCase(),
1144
+ abort: false,
1145
+ headers: parseHeaders(init.headers),
1146
+ data: init.body,
1147
+ response: null,
1148
+ async: true,
1149
+ };
1150
+ const req = new AHRequest(request);
1151
+ await req.waitForRequestKeys();
1152
+ if (request.abort) {
1153
+ if (typeof request.response === "function") {
1154
+ const response = {
1155
+ finalUrl: request.url,
1156
+ status: 200,
1157
+ responseHeaders: {},
1158
+ };
1159
+ await req.waitForResponseKeys(response);
1160
+ const key = fetchResponses.find((k) => k in response);
1161
+ let val = response[key];
1162
+ if (key === "json" && typeof val === "object") {
1163
+ val = catchError(JSON.stringify.bind(JSON), val);
1164
+ }
1165
+ const res = new Response(val, {
1166
+ status: 200,
1167
+ statusText: "OK",
1168
+ });
1169
+ defineProp(res, "type", () => "basic");
1170
+ defineProp(res, "url", () => request.url);
1171
+ resolve(res);
1172
+ }
1173
+ else {
1174
+ reject(new DOMException("aborted", "AbortError"));
1175
+ }
1176
+ return;
1177
+ }
1178
+ init.method = request.method;
1179
+ init.headers = request.headers;
1180
+ init.body = request.data;
1181
+ for (const prop of fetchExtraProps) {
1182
+ if (prop in request)
1183
+ init[prop] = request[prop];
1184
+ }
1185
+ winAh.realFetch.call(win, request.url, init).then((res) => {
1186
+ if (typeof request.response === "function") {
1187
+ const response = {
1188
+ finalUrl: res.url,
1189
+ status: res.status,
1190
+ responseHeaders: parseHeaders(res.headers),
1191
+ };
1192
+ if (res.ok) {
1193
+ fetchResponses.forEach((key) => (res[key] = function () {
1194
+ if (key in response)
1195
+ return Promise.resolve(response[key]);
1196
+ return resProto[key].call(this).then((val) => {
1197
+ response[key] = val;
1198
+ return req
1199
+ .waitForResponseKeys(response)
1200
+ .then(() => (key in response ? response[key] : val));
1201
+ });
1202
+ }));
1203
+ }
1204
+ else {
1205
+ catchError(request.response, response);
1206
+ }
1207
+ }
1208
+ resolve(res);
1209
+ }, reject);
1210
+ });
1211
+ }
1212
+ function fakeFetchClone() {
1213
+ const descriptors = Object.getOwnPropertyDescriptors(this);
1214
+ const res = winAh.realFetchClone.call(this);
1215
+ Object.defineProperties(res, descriptors);
1216
+ return res;
1217
+ }
1218
+ winAh = win.__ajaxHooker = winAh || {
1219
+ version,
1220
+ fakeXHR,
1221
+ fakeFetch,
1222
+ fakeFetchClone,
1223
+ realXHR: win.XMLHttpRequest,
1224
+ realFetch: win.fetch,
1225
+ realFetchClone: resProto.clone,
1226
+ hookInsts: new Set(),
1227
+ };
1228
+ if (winAh.version !== version)
1229
+ console.warn("检测到不同版本的ajaxHooker,可能发生冲突!");
1230
+ win.XMLHttpRequest = winAh.fakeXHR;
1231
+ win.fetch = winAh.fakeFetch;
1232
+ resProto.clone = winAh.fakeFetchClone;
1233
+ winAh.hookInsts.add(hookInst);
1234
+ // 针对头条、抖音 secsdk.umd.js 的兼容性处理
1235
+ class AHFunction extends Function {
1236
+ call(thisArg, ...args) {
1237
+ if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
1238
+ thisArg = thisArg.__ajaxHooker.originalXhr;
1239
+ }
1240
+ return Reflect.apply(this, thisArg, args);
1241
+ }
1242
+ apply(thisArg, args) {
1243
+ if (thisArg && thisArg.__ajaxHooker && thisArg.__ajaxHooker.proxyXhr === thisArg) {
1244
+ thisArg = thisArg.__ajaxHooker.originalXhr;
1245
+ }
1246
+ return Reflect.apply(this, thisArg, args || []);
1247
+ }
1248
+ }
1249
+ function hookSecsdk(csrf) {
1250
+ Object.setPrototypeOf(csrf.nativeXMLHttpRequestSetRequestHeader, AHFunction.prototype);
1251
+ Object.setPrototypeOf(csrf.nativeXMLHttpRequestOpen, AHFunction.prototype);
1252
+ Object.setPrototypeOf(csrf.nativeXMLHttpRequestSend, AHFunction.prototype);
1253
+ }
1254
+ if (win.secsdk) {
1255
+ if (win.secsdk.csrf && win.secsdk.csrf.nativeXMLHttpRequestOpen)
1256
+ hookSecsdk(win.secsdk.csrf);
1257
+ }
1258
+ else {
1259
+ defineProp(win, "secsdk", emptyFn, (secsdk) => {
1260
+ delete win.secsdk;
1261
+ win.secsdk = secsdk;
1262
+ defineProp(secsdk, "csrf", emptyFn, (csrf) => {
1263
+ delete secsdk.csrf;
1264
+ secsdk.csrf = csrf;
1265
+ if (csrf.nativeXMLHttpRequestOpen)
1266
+ hookSecsdk(csrf);
1267
+ });
1268
+ });
1269
+ }
1270
+ return {
1271
+ hook: (fn) => hookInst.hookFns.push(fn),
1272
+ filter: (arr) => {
1273
+ if (Array.isArray(arr))
1274
+ hookInst.filters = arr;
1275
+ },
1276
+ protect: () => {
1277
+ readonly(win, "XMLHttpRequest", winAh.fakeXHR);
1278
+ readonly(win, "fetch", winAh.fakeFetch);
1279
+ readonly(resProto, "clone", winAh.fakeFetchClone);
1280
+ },
1281
+ unhook: () => {
1282
+ winAh.hookInsts.delete(hookInst);
1283
+ if (!winAh.hookInsts.size) {
1284
+ writable(win, "XMLHttpRequest", winAh.realXHR);
1285
+ writable(win, "fetch", winAh.realFetch);
1286
+ writable(resProto, "clone", winAh.realFetchClone);
1287
+ delete win.__ajaxHooker;
1288
+ }
1289
+ },
1290
+ };
1261
1291
  };
1262
1292
 
1263
- // ==UserScript==
1264
- // @name ajaxHooker
1265
- // @author cxxjackie
1266
- // @version 1.2.4
1267
- // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
1268
- // ==/UserScript==
1269
-
1270
- const AjaxHooker1_2_4 = function () {
1271
- return (function () {
1272
- const win = window.unsafeWindow || document.defaultView || window;
1273
- const hookFns = [];
1274
- const realXhr = win.XMLHttpRequest;
1275
- const resProto = win.Response.prototype;
1276
- const toString = Object.prototype.toString;
1277
- const realFetch = win.fetch;
1278
- const xhrResponses = ["response", "responseText", "responseXML"];
1279
- const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
1280
- const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
1281
- let filter;
1282
- function emptyFn() {}
1283
- function errorFn(err) {
1284
- console.error(err);
1285
- }
1286
- function defineProp(obj, prop, getter, setter) {
1287
- Object.defineProperty(obj, prop, {
1288
- configurable: true,
1289
- enumerable: true,
1290
- get: getter,
1291
- set: setter,
1292
- });
1293
- }
1294
- function readonly(obj, prop, value = obj[prop]) {
1295
- defineProp(obj, prop, () => value, emptyFn);
1296
- }
1297
- function writable(obj, prop, value = obj[prop]) {
1298
- Object.defineProperty(obj, prop, {
1299
- configurable: true,
1300
- enumerable: true,
1301
- writable: true,
1302
- value: value,
1303
- });
1304
- }
1305
- function toFilterObj(obj) {
1306
- return {
1307
- type: obj.type,
1308
- url: obj.url,
1309
- method: obj.method && obj.method.toUpperCase(),
1310
- };
1311
- }
1312
- function shouldFilter(type, url, method) {
1313
- return (
1314
- filter &&
1315
- !filter.find(
1316
- (obj) =>
1317
- (!obj.type || obj.type === type) &&
1318
- (!obj.url ||
1319
- (toString.call(obj.url) === "[object String]"
1320
- ? url.includes(obj.url)
1321
- : obj.url.test(url))) &&
1322
- (!obj.method || obj.method === method.toUpperCase())
1323
- )
1324
- );
1325
- }
1326
- function lookupGetter(obj, prop) {
1327
- let getter;
1328
- let proto = obj;
1329
- while (proto) {
1330
- const descriptor = Object.getOwnPropertyDescriptor(proto, prop);
1331
- getter = descriptor && descriptor.get;
1332
- if (getter) break;
1333
- proto = Object.getPrototypeOf(proto);
1334
- }
1335
- return getter ? getter.bind(obj) : emptyFn;
1336
- }
1337
- function waitForHookFns(request) {
1338
- return Promise.all(
1339
- hookFns.map((fn) => Promise.resolve(fn(request)).then(emptyFn, errorFn))
1340
- );
1341
- }
1342
- function waitForRequestKeys(request, requestClone) {
1343
- return Promise.all(
1344
- ["url", "method", "abort", "headers", "data"].map((key) => {
1345
- return Promise.resolve(request[key]).then(
1346
- (val) => (request[key] = val),
1347
- () => (request[key] = requestClone[key])
1348
- );
1349
- })
1350
- );
1351
- }
1352
- function fakeEventSIP() {
1353
- this.ajaxHooker_stopped = true;
1354
- }
1355
- function xhrDelegateEvent(e) {
1356
- const xhr = e.target;
1357
- e.stopImmediatePropagation = fakeEventSIP;
1358
- xhr.__ajaxHooker.hookedEvents[e.type].forEach(
1359
- (fn) => !e.ajaxHooker_stopped && fn.call(xhr, e)
1360
- );
1361
- const onEvent = xhr.__ajaxHooker.hookedEvents["on" + e.type];
1362
- typeof onEvent === "function" && onEvent.call(xhr, e);
1363
- }
1364
- function xhrReadyStateChange(e) {
1365
- if (e.target.readyState === 4) {
1366
- e.target.dispatchEvent(
1367
- new CustomEvent("ajaxHooker_responseReady", { detail: e })
1368
- );
1369
- } else {
1370
- e.target.__ajaxHooker.delegateEvent(e);
1371
- }
1372
- }
1373
- function xhrLoadAndLoadend(e) {
1374
- e.target.__ajaxHooker.delegateEvent(e);
1375
- }
1376
- function fakeXhrOpen(method, url, ...args) {
1377
- const ah = this.__ajaxHooker;
1378
- ah.url = url.toString();
1379
- ah.method = method.toUpperCase();
1380
- ah.openArgs = args;
1381
- ah.headers = {};
1382
- return ah.originalMethods.open(method, url, ...args);
1383
- }
1384
- function fakeXhr() {
1385
- const xhr = new realXhr();
1386
- let ah = xhr.__ajaxHooker;
1387
- if (!ah) {
1388
- ah = xhr.__ajaxHooker = {
1389
- headers: {},
1390
- hookedEvents: {
1391
- readystatechange: new Set(),
1392
- load: new Set(),
1393
- loadend: new Set(),
1394
- },
1395
- delegateEvent: xhrDelegateEvent,
1396
- originalGetters: {},
1397
- originalMethods: {},
1398
- };
1399
- xhr.addEventListener("readystatechange", xhrReadyStateChange);
1400
- xhr.addEventListener("load", xhrLoadAndLoadend);
1401
- xhr.addEventListener("loadend", xhrLoadAndLoadend);
1402
- for (const key of xhrResponses) {
1403
- ah.originalGetters[key] = lookupGetter(xhr, key);
1404
- }
1405
- for (const method of [
1406
- "open",
1407
- "setRequestHeader",
1408
- "addEventListener",
1409
- "removeEventListener",
1410
- ]) {
1411
- ah.originalMethods[method] = xhr[method].bind(xhr);
1412
- }
1413
- xhr.open = fakeXhrOpen;
1414
- xhr.setRequestHeader = (header, value) => {
1415
- ah.originalMethods.setRequestHeader(header, value);
1416
- if (xhr.readyState === 1) {
1417
- if (ah.headers[header]) {
1418
- ah.headers[header] += ", " + value;
1419
- } else {
1420
- ah.headers[header] = value;
1421
- }
1422
- }
1423
- };
1424
- xhr.addEventListener = function (...args) {
1425
- if (xhrAsyncEvents.includes(args[0])) {
1426
- ah.hookedEvents[args[0]].add(args[1]);
1427
- } else {
1428
- ah.originalMethods.addEventListener(...args);
1429
- }
1430
- };
1431
- xhr.removeEventListener = function (...args) {
1432
- if (xhrAsyncEvents.includes(args[0])) {
1433
- ah.hookedEvents[args[0]].delete(args[1]);
1434
- } else {
1435
- ah.originalMethods.removeEventListener(...args);
1436
- }
1437
- };
1438
- xhrAsyncEvents.forEach((evt) => {
1439
- const onEvt = "on" + evt;
1440
- defineProp(
1441
- xhr,
1442
- onEvt,
1443
- () => {
1444
- return ah.hookedEvents[onEvt] || null;
1445
- },
1446
- (val) => {
1447
- ah.hookedEvents[onEvt] = typeof val === "function" ? val : null;
1448
- }
1449
- );
1450
- });
1451
- }
1452
- const realSend = xhr.send.bind(xhr);
1453
- xhr.send = function (data) {
1454
- if (xhr.readyState !== 1) return realSend(data);
1455
- ah.delegateEvent = xhrDelegateEvent;
1456
- xhrResponses.forEach((prop) => {
1457
- delete xhr[prop]; // delete descriptor
1458
- });
1459
- if (shouldFilter("xhr", ah.url, ah.method)) {
1460
- xhr.addEventListener("ajaxHooker_responseReady", (e) => {
1461
- ah.delegateEvent(e.detail);
1462
- });
1463
- return realSend(data);
1464
- }
1465
- try {
1466
- const request = {
1467
- type: "xhr",
1468
- url: ah.url,
1469
- method: ah.method,
1470
- abort: false,
1471
- headers: ah.headers,
1472
- data: data,
1473
- response: null,
1474
- };
1475
- const requestClone = { ...request };
1476
- waitForHookFns(request).then(() => {
1477
- waitForRequestKeys(request, requestClone).then(() => {
1478
- if (request.abort) return;
1479
- ah.originalMethods.open(
1480
- request.method,
1481
- request.url,
1482
- ...ah.openArgs
1483
- );
1484
- for (const header in request.headers) {
1485
- ah.originalMethods.setRequestHeader(
1486
- header,
1487
- request.headers[header]
1488
- );
1489
- }
1490
- data = request.data;
1491
- xhr.addEventListener("ajaxHooker_responseReady", (e) => {
1492
- try {
1493
- if (typeof request.response === "function") {
1494
- const arg = {
1495
- finalUrl: xhr.responseURL,
1496
- status: xhr.status,
1497
- responseHeaders: {},
1498
- };
1499
- for (const line of xhr
1500
- .getAllResponseHeaders()
1501
- .trim()
1502
- .split(/[\r\n]+/)) {
1503
- const parts = line.split(/:\s*/);
1504
- if (parts.length === 2) {
1505
- const lheader = parts[0].toLowerCase();
1506
- if (arg.responseHeaders[lheader]) {
1507
- arg.responseHeaders[lheader] += ", " + parts[1];
1508
- } else {
1509
- arg.responseHeaders[lheader] = parts[1];
1510
- }
1511
- }
1512
- }
1513
- xhrResponses.forEach((prop) => {
1514
- defineProp(
1515
- arg,
1516
- prop,
1517
- () => {
1518
- return (arg[prop] = ah.originalGetters[prop]());
1519
- },
1520
- (val) => {
1521
- delete arg[prop];
1522
- arg[prop] = val;
1523
- }
1524
- );
1525
- defineProp(xhr, prop, () => {
1526
- const val = ah.originalGetters[prop]();
1527
- xhr.dispatchEvent(
1528
- new CustomEvent("ajaxHooker_readResponse", {
1529
- detail: { prop, val },
1530
- })
1531
- );
1532
- return val;
1533
- });
1534
- });
1535
- xhr.addEventListener("ajaxHooker_readResponse", (e) => {
1536
- arg[e.detail.prop] = e.detail.val;
1537
- });
1538
- const resPromise = Promise.resolve(
1539
- request.response(arg)
1540
- ).then(() => {
1541
- const task = [];
1542
- xhrResponses.forEach((prop) => {
1543
- const descriptor = Object.getOwnPropertyDescriptor(
1544
- arg,
1545
- prop
1546
- );
1547
- if (descriptor && "value" in descriptor) {
1548
- task.push(
1549
- Promise.resolve(descriptor.value).then((val) => {
1550
- arg[prop] = val;
1551
- defineProp(xhr, prop, () => {
1552
- xhr.dispatchEvent(
1553
- new CustomEvent("ajaxHooker_readResponse", {
1554
- detail: { prop, val },
1555
- })
1556
- );
1557
- return val;
1558
- });
1559
- }, emptyFn)
1560
- );
1561
- }
1562
- });
1563
- return Promise.all(task);
1564
- }, errorFn);
1565
- const eventsClone = {};
1566
- xhrAsyncEvents.forEach((type) => {
1567
- eventsClone[type] = new Set([...ah.hookedEvents[type]]);
1568
- eventsClone["on" + type] = ah.hookedEvents["on" + type];
1569
- });
1570
- ah.delegateEvent = (event) =>
1571
- resPromise.then(() => {
1572
- event.stopImmediatePropagation = fakeEventSIP;
1573
- eventsClone[event.type].forEach(
1574
- (fn) =>
1575
- !event.ajaxHooker_stopped && fn.call(xhr, event)
1576
- );
1577
- const onEvent = eventsClone["on" + event.type];
1578
- typeof onEvent === "function" &&
1579
- onEvent.call(xhr, event);
1580
- });
1581
- }
1582
- } catch (err) {
1583
- console.error(err);
1584
- }
1585
- ah.delegateEvent(e.detail);
1586
- });
1587
- realSend(data);
1588
- });
1589
- });
1590
- } catch (err) {
1591
- console.error(err);
1592
- realSend(data);
1593
- }
1594
- };
1595
- return xhr;
1596
- }
1597
- function hookFetchResponse(response, arg, callback) {
1598
- fetchResponses.forEach((prop) => {
1599
- response[prop] = () =>
1600
- new Promise((resolve, reject) => {
1601
- resProto[prop].call(response).then((res) => {
1602
- if (prop in arg) {
1603
- resolve(arg[prop]);
1604
- } else {
1605
- try {
1606
- arg[prop] = res;
1607
- Promise.resolve(callback(arg)).then(() => {
1608
- if (prop in arg) {
1609
- Promise.resolve(arg[prop]).then(
1610
- (val) => resolve((arg[prop] = val)),
1611
- () => resolve(res)
1612
- );
1613
- } else {
1614
- resolve(res);
1615
- }
1616
- }, errorFn);
1617
- } catch (err) {
1618
- console.error(err);
1619
- resolve(res);
1620
- }
1621
- }
1622
- }, reject);
1623
- });
1624
- });
1625
- }
1626
- function fakeFetch(url, init) {
1627
- if (url && typeof url.toString === "function") {
1628
- url = url.toString();
1629
- init = init || {};
1630
- init.method = init.method || "GET";
1631
- init.headers = init.headers || {};
1632
- if (shouldFilter("fetch", url, init.method))
1633
- return realFetch.call(win, url, init);
1634
- const request = {
1635
- type: "fetch",
1636
- url: url,
1637
- method: init.method.toUpperCase(),
1638
- abort: false,
1639
- headers: {},
1640
- data: init.body,
1641
- response: null,
1642
- };
1643
- if (toString.call(init.headers) === "[object Headers]") {
1644
- for (const [key, val] of init.headers) {
1645
- request.headers[key] = val;
1646
- }
1647
- } else {
1648
- request.headers = { ...init.headers };
1649
- }
1650
- const requestClone = { ...request };
1651
- return new Promise((resolve, reject) => {
1652
- try {
1653
- waitForHookFns(request).then(() => {
1654
- waitForRequestKeys(request, requestClone).then(() => {
1655
- if (request.abort) return reject("aborted");
1656
- url = request.url;
1657
- init.method = request.method;
1658
- init.headers = request.headers;
1659
- init.body = request.data;
1660
- realFetch.call(win, url, init).then((response) => {
1661
- if (typeof request.response === "function") {
1662
- const arg = {
1663
- finalUrl: response.url,
1664
- status: response.status,
1665
- responseHeaders: {},
1666
- };
1667
- for (const [key, val] of response.headers) {
1668
- arg.responseHeaders[key] = val;
1669
- }
1670
- hookFetchResponse(response, arg, request.response);
1671
- response.clone = () => {
1672
- const resClone = resProto.clone.call(response);
1673
- hookFetchResponse(resClone, arg, request.response);
1674
- return resClone;
1675
- };
1676
- }
1677
- resolve(response);
1678
- }, reject);
1679
- });
1680
- });
1681
- } catch (err) {
1682
- console.error(err);
1683
- return realFetch.call(win, url, init);
1684
- }
1685
- });
1686
- } else {
1687
- return realFetch.call(win, url, init);
1688
- }
1689
- }
1690
- win.XMLHttpRequest = fakeXhr;
1691
- Object.keys(realXhr).forEach((key) => (fakeXhr[key] = realXhr[key]));
1692
- fakeXhr.prototype = realXhr.prototype;
1693
- win.fetch = fakeFetch;
1694
- return {
1695
- hook: (fn) => hookFns.push(fn),
1696
- filter: (arr) => {
1697
- filter = Array.isArray(arr) && arr.map(toFilterObj);
1698
- },
1699
- protect: () => {
1700
- readonly(win, "XMLHttpRequest", fakeXhr);
1701
- readonly(win, "fetch", fakeFetch);
1702
- },
1703
- unhook: () => {
1704
- writable(win, "XMLHttpRequest", realXhr);
1705
- writable(win, "fetch", realFetch);
1706
- },
1707
- };
1708
- })();
1293
+ // ==UserScript==
1294
+ // @name ajaxHooker
1295
+ // @author cxxjackie
1296
+ // @version 1.2.4
1297
+ // @supportURL https://bbs.tampermonkey.net.cn/thread-3284-1-1.html
1298
+ // ==/UserScript==
1299
+ const AjaxHooker1_2_4 = function () {
1300
+ return (function () {
1301
+ const win = window.unsafeWindow || document.defaultView || window;
1302
+ const hookFns = [];
1303
+ const realXhr = win.XMLHttpRequest;
1304
+ const resProto = win.Response.prototype;
1305
+ const toString = Object.prototype.toString;
1306
+ const realFetch = win.fetch;
1307
+ const xhrResponses = ["response", "responseText", "responseXML"];
1308
+ const fetchResponses = ["arrayBuffer", "blob", "formData", "json", "text"];
1309
+ const xhrAsyncEvents = ["readystatechange", "load", "loadend"];
1310
+ let filter;
1311
+ function emptyFn() { }
1312
+ function errorFn(err) {
1313
+ console.error(err);
1314
+ }
1315
+ function defineProp(obj, prop, getter, setter) {
1316
+ Object.defineProperty(obj, prop, {
1317
+ configurable: true,
1318
+ enumerable: true,
1319
+ get: getter,
1320
+ set: setter,
1321
+ });
1322
+ }
1323
+ function readonly(obj, prop, value = obj[prop]) {
1324
+ defineProp(obj, prop, () => value, emptyFn);
1325
+ }
1326
+ function writable(obj, prop, value = obj[prop]) {
1327
+ Object.defineProperty(obj, prop, {
1328
+ configurable: true,
1329
+ enumerable: true,
1330
+ writable: true,
1331
+ value: value,
1332
+ });
1333
+ }
1334
+ function toFilterObj(obj) {
1335
+ return {
1336
+ type: obj.type,
1337
+ url: obj.url,
1338
+ method: obj.method && obj.method.toUpperCase(),
1339
+ };
1340
+ }
1341
+ function shouldFilter(type, url, method) {
1342
+ return (filter &&
1343
+ !filter.find((obj) => (!obj.type || obj.type === type) &&
1344
+ (!obj.url ||
1345
+ (toString.call(obj.url) === "[object String]"
1346
+ ? url.includes(obj.url)
1347
+ : obj.url.test(url))) &&
1348
+ (!obj.method || obj.method === method.toUpperCase())));
1349
+ }
1350
+ function lookupGetter(obj, prop) {
1351
+ let getter;
1352
+ let proto = obj;
1353
+ while (proto) {
1354
+ const descriptor = Object.getOwnPropertyDescriptor(proto, prop);
1355
+ getter = descriptor && descriptor.get;
1356
+ if (getter)
1357
+ break;
1358
+ proto = Object.getPrototypeOf(proto);
1359
+ }
1360
+ return getter ? getter.bind(obj) : emptyFn;
1361
+ }
1362
+ function waitForHookFns(request) {
1363
+ return Promise.all(hookFns.map((fn) => Promise.resolve(fn(request)).then(emptyFn, errorFn)));
1364
+ }
1365
+ function waitForRequestKeys(request, requestClone) {
1366
+ return Promise.all(["url", "method", "abort", "headers", "data"].map((key) => {
1367
+ return Promise.resolve(request[key]).then((val) => (request[key] = val), () => (request[key] = requestClone[key]));
1368
+ }));
1369
+ }
1370
+ function fakeEventSIP() {
1371
+ this.ajaxHooker_stopped = true;
1372
+ }
1373
+ function xhrDelegateEvent(e) {
1374
+ const xhr = e.target;
1375
+ e.stopImmediatePropagation = fakeEventSIP;
1376
+ xhr.__ajaxHooker.hookedEvents[e.type].forEach((fn) => !e.ajaxHooker_stopped && fn.call(xhr, e));
1377
+ const onEvent = xhr.__ajaxHooker.hookedEvents["on" + e.type];
1378
+ typeof onEvent === "function" && onEvent.call(xhr, e);
1379
+ }
1380
+ function xhrReadyStateChange(e) {
1381
+ if (e.target.readyState === 4) {
1382
+ e.target.dispatchEvent(new CustomEvent("ajaxHooker_responseReady", { detail: e }));
1383
+ }
1384
+ else {
1385
+ e.target.__ajaxHooker.delegateEvent(e);
1386
+ }
1387
+ }
1388
+ function xhrLoadAndLoadend(e) {
1389
+ e.target.__ajaxHooker.delegateEvent(e);
1390
+ }
1391
+ function fakeXhrOpen(method, url, ...args) {
1392
+ const ah = this.__ajaxHooker;
1393
+ ah.url = url.toString();
1394
+ ah.method = method.toUpperCase();
1395
+ ah.openArgs = args;
1396
+ ah.headers = {};
1397
+ return ah.originalMethods.open(method, url, ...args);
1398
+ }
1399
+ function fakeXhr() {
1400
+ const xhr = new realXhr();
1401
+ let ah = xhr.__ajaxHooker;
1402
+ if (!ah) {
1403
+ ah = xhr.__ajaxHooker = {
1404
+ headers: {},
1405
+ hookedEvents: {
1406
+ readystatechange: new Set(),
1407
+ load: new Set(),
1408
+ loadend: new Set(),
1409
+ },
1410
+ delegateEvent: xhrDelegateEvent,
1411
+ originalGetters: {},
1412
+ originalMethods: {},
1413
+ };
1414
+ xhr.addEventListener("readystatechange", xhrReadyStateChange);
1415
+ xhr.addEventListener("load", xhrLoadAndLoadend);
1416
+ xhr.addEventListener("loadend", xhrLoadAndLoadend);
1417
+ for (const key of xhrResponses) {
1418
+ ah.originalGetters[key] = lookupGetter(xhr, key);
1419
+ }
1420
+ for (const method of [
1421
+ "open",
1422
+ "setRequestHeader",
1423
+ "addEventListener",
1424
+ "removeEventListener",
1425
+ ]) {
1426
+ ah.originalMethods[method] = xhr[method].bind(xhr);
1427
+ }
1428
+ xhr.open = fakeXhrOpen;
1429
+ xhr.setRequestHeader = (header, value) => {
1430
+ ah.originalMethods.setRequestHeader(header, value);
1431
+ if (xhr.readyState === 1) {
1432
+ if (ah.headers[header]) {
1433
+ ah.headers[header] += ", " + value;
1434
+ }
1435
+ else {
1436
+ ah.headers[header] = value;
1437
+ }
1438
+ }
1439
+ };
1440
+ xhr.addEventListener = function (...args) {
1441
+ if (xhrAsyncEvents.includes(args[0])) {
1442
+ ah.hookedEvents[args[0]].add(args[1]);
1443
+ }
1444
+ else {
1445
+ ah.originalMethods.addEventListener(...args);
1446
+ }
1447
+ };
1448
+ xhr.removeEventListener = function (...args) {
1449
+ if (xhrAsyncEvents.includes(args[0])) {
1450
+ ah.hookedEvents[args[0]].delete(args[1]);
1451
+ }
1452
+ else {
1453
+ ah.originalMethods.removeEventListener(...args);
1454
+ }
1455
+ };
1456
+ xhrAsyncEvents.forEach((evt) => {
1457
+ const onEvt = "on" + evt;
1458
+ defineProp(xhr, onEvt, () => {
1459
+ return ah.hookedEvents[onEvt] || null;
1460
+ }, (val) => {
1461
+ ah.hookedEvents[onEvt] = typeof val === "function" ? val : null;
1462
+ });
1463
+ });
1464
+ }
1465
+ const realSend = xhr.send.bind(xhr);
1466
+ xhr.send = function (data) {
1467
+ if (xhr.readyState !== 1)
1468
+ return realSend(data);
1469
+ ah.delegateEvent = xhrDelegateEvent;
1470
+ xhrResponses.forEach((prop) => {
1471
+ delete xhr[prop]; // delete descriptor
1472
+ });
1473
+ if (shouldFilter("xhr", ah.url, ah.method)) {
1474
+ xhr.addEventListener("ajaxHooker_responseReady", (e) => {
1475
+ ah.delegateEvent(e.detail);
1476
+ });
1477
+ return realSend(data);
1478
+ }
1479
+ try {
1480
+ const request = {
1481
+ type: "xhr",
1482
+ url: ah.url,
1483
+ method: ah.method,
1484
+ abort: false,
1485
+ headers: ah.headers,
1486
+ data: data,
1487
+ response: null,
1488
+ };
1489
+ const requestClone = { ...request };
1490
+ waitForHookFns(request).then(() => {
1491
+ waitForRequestKeys(request, requestClone).then(() => {
1492
+ if (request.abort)
1493
+ return;
1494
+ ah.originalMethods.open(request.method, request.url, ...ah.openArgs);
1495
+ for (const header in request.headers) {
1496
+ ah.originalMethods.setRequestHeader(header, request.headers[header]);
1497
+ }
1498
+ data = request.data;
1499
+ xhr.addEventListener("ajaxHooker_responseReady", (e) => {
1500
+ try {
1501
+ if (typeof request.response === "function") {
1502
+ const arg = {
1503
+ finalUrl: xhr.responseURL,
1504
+ status: xhr.status,
1505
+ responseHeaders: {},
1506
+ };
1507
+ for (const line of xhr
1508
+ .getAllResponseHeaders()
1509
+ .trim()
1510
+ .split(/[\r\n]+/)) {
1511
+ const parts = line.split(/:\s*/);
1512
+ if (parts.length === 2) {
1513
+ const lheader = parts[0].toLowerCase();
1514
+ if (arg.responseHeaders[lheader]) {
1515
+ arg.responseHeaders[lheader] += ", " + parts[1];
1516
+ }
1517
+ else {
1518
+ arg.responseHeaders[lheader] = parts[1];
1519
+ }
1520
+ }
1521
+ }
1522
+ xhrResponses.forEach((prop) => {
1523
+ defineProp(arg, prop, () => {
1524
+ return (arg[prop] = ah.originalGetters[prop]());
1525
+ }, (val) => {
1526
+ delete arg[prop];
1527
+ arg[prop] = val;
1528
+ });
1529
+ defineProp(xhr, prop, () => {
1530
+ const val = ah.originalGetters[prop]();
1531
+ xhr.dispatchEvent(new CustomEvent("ajaxHooker_readResponse", {
1532
+ detail: { prop, val },
1533
+ }));
1534
+ return val;
1535
+ });
1536
+ });
1537
+ xhr.addEventListener("ajaxHooker_readResponse", (e) => {
1538
+ arg[e.detail.prop] = e.detail.val;
1539
+ });
1540
+ const resPromise = Promise.resolve(request.response(arg)).then(() => {
1541
+ const task = [];
1542
+ xhrResponses.forEach((prop) => {
1543
+ const descriptor = Object.getOwnPropertyDescriptor(arg, prop);
1544
+ if (descriptor && "value" in descriptor) {
1545
+ task.push(Promise.resolve(descriptor.value).then((val) => {
1546
+ arg[prop] = val;
1547
+ defineProp(xhr, prop, () => {
1548
+ xhr.dispatchEvent(new CustomEvent("ajaxHooker_readResponse", {
1549
+ detail: { prop, val },
1550
+ }));
1551
+ return val;
1552
+ });
1553
+ }, emptyFn));
1554
+ }
1555
+ });
1556
+ return Promise.all(task);
1557
+ }, errorFn);
1558
+ const eventsClone = {};
1559
+ xhrAsyncEvents.forEach((type) => {
1560
+ eventsClone[type] = new Set([...ah.hookedEvents[type]]);
1561
+ eventsClone["on" + type] = ah.hookedEvents["on" + type];
1562
+ });
1563
+ ah.delegateEvent = (event) => resPromise.then(() => {
1564
+ event.stopImmediatePropagation = fakeEventSIP;
1565
+ eventsClone[event.type].forEach((fn) => !event.ajaxHooker_stopped && fn.call(xhr, event));
1566
+ const onEvent = eventsClone["on" + event.type];
1567
+ typeof onEvent === "function" &&
1568
+ onEvent.call(xhr, event);
1569
+ });
1570
+ }
1571
+ }
1572
+ catch (err) {
1573
+ console.error(err);
1574
+ }
1575
+ ah.delegateEvent(e.detail);
1576
+ });
1577
+ realSend(data);
1578
+ });
1579
+ });
1580
+ }
1581
+ catch (err) {
1582
+ console.error(err);
1583
+ realSend(data);
1584
+ }
1585
+ };
1586
+ return xhr;
1587
+ }
1588
+ function hookFetchResponse(response, arg, callback) {
1589
+ fetchResponses.forEach((prop) => {
1590
+ response[prop] = () => new Promise((resolve, reject) => {
1591
+ resProto[prop].call(response).then((res) => {
1592
+ if (prop in arg) {
1593
+ resolve(arg[prop]);
1594
+ }
1595
+ else {
1596
+ try {
1597
+ arg[prop] = res;
1598
+ Promise.resolve(callback(arg)).then(() => {
1599
+ if (prop in arg) {
1600
+ Promise.resolve(arg[prop]).then((val) => resolve((arg[prop] = val)), () => resolve(res));
1601
+ }
1602
+ else {
1603
+ resolve(res);
1604
+ }
1605
+ }, errorFn);
1606
+ }
1607
+ catch (err) {
1608
+ console.error(err);
1609
+ resolve(res);
1610
+ }
1611
+ }
1612
+ }, reject);
1613
+ });
1614
+ });
1615
+ }
1616
+ function fakeFetch(url, init) {
1617
+ if (url && typeof url.toString === "function") {
1618
+ url = url.toString();
1619
+ init = init || {};
1620
+ init.method = init.method || "GET";
1621
+ init.headers = init.headers || {};
1622
+ if (shouldFilter("fetch", url, init.method))
1623
+ return realFetch.call(win, url, init);
1624
+ const request = {
1625
+ type: "fetch",
1626
+ url: url,
1627
+ method: init.method.toUpperCase(),
1628
+ abort: false,
1629
+ headers: {},
1630
+ data: init.body,
1631
+ response: null,
1632
+ };
1633
+ if (toString.call(init.headers) === "[object Headers]") {
1634
+ for (const [key, val] of init.headers) {
1635
+ request.headers[key] = val;
1636
+ }
1637
+ }
1638
+ else {
1639
+ request.headers = { ...init.headers };
1640
+ }
1641
+ const requestClone = { ...request };
1642
+ return new Promise((resolve, reject) => {
1643
+ try {
1644
+ waitForHookFns(request).then(() => {
1645
+ waitForRequestKeys(request, requestClone).then(() => {
1646
+ if (request.abort)
1647
+ return reject("aborted");
1648
+ url = request.url;
1649
+ init.method = request.method;
1650
+ init.headers = request.headers;
1651
+ init.body = request.data;
1652
+ realFetch.call(win, url, init).then((response) => {
1653
+ if (typeof request.response === "function") {
1654
+ const arg = {
1655
+ finalUrl: response.url,
1656
+ status: response.status,
1657
+ responseHeaders: {},
1658
+ };
1659
+ for (const [key, val] of response.headers) {
1660
+ arg.responseHeaders[key] = val;
1661
+ }
1662
+ hookFetchResponse(response, arg, request.response);
1663
+ response.clone = () => {
1664
+ const resClone = resProto.clone.call(response);
1665
+ hookFetchResponse(resClone, arg, request.response);
1666
+ return resClone;
1667
+ };
1668
+ }
1669
+ resolve(response);
1670
+ }, reject);
1671
+ });
1672
+ });
1673
+ }
1674
+ catch (err) {
1675
+ console.error(err);
1676
+ return realFetch.call(win, url, init);
1677
+ }
1678
+ });
1679
+ }
1680
+ else {
1681
+ return realFetch.call(win, url, init);
1682
+ }
1683
+ }
1684
+ win.XMLHttpRequest = fakeXhr;
1685
+ Object.keys(realXhr).forEach((key) => (fakeXhr[key] = realXhr[key]));
1686
+ fakeXhr.prototype = realXhr.prototype;
1687
+ win.fetch = fakeFetch;
1688
+ return {
1689
+ hook: (fn) => hookFns.push(fn),
1690
+ filter: (arr) => {
1691
+ filter = Array.isArray(arr) && arr.map(toFilterObj);
1692
+ },
1693
+ protect: () => {
1694
+ readonly(win, "XMLHttpRequest", fakeXhr);
1695
+ readonly(win, "fetch", fakeFetch);
1696
+ },
1697
+ unhook: () => {
1698
+ writable(win, "XMLHttpRequest", realXhr);
1699
+ writable(win, "fetch", realFetch);
1700
+ },
1701
+ };
1702
+ })();
1709
1703
  };
1710
1704
 
1711
1705
  class GMMenu {
@@ -2123,31 +2117,31 @@ class GMMenu {
2123
2117
  }
2124
2118
  /**
2125
2119
  * 设置当enable为true时默认显示在菜单中前面的emoji图标
2126
- * @param emojiString
2120
+ * @param emojiString emoji字符串
2127
2121
  */
2128
2122
  setEnableTrueEmoji(emojiString) {
2129
2123
  if (typeof emojiString !== "string") {
2130
- throw new Error("参数emojiString必须是string类型");
2124
+ throw new TypeError("参数emojiString必须是string类型");
2131
2125
  }
2132
2126
  this.MenuHandle.$emoji.success = emojiString;
2133
2127
  }
2134
2128
  /**
2135
2129
  * 设置当enable为false时默认显示在菜单中前面的emoji图标
2136
- * @param emojiString
2130
+ * @param emojiString emoji字符串
2137
2131
  */
2138
2132
  setEnableFalseEmoji(emojiString) {
2139
2133
  if (typeof emojiString !== "string") {
2140
- throw new Error("参数emojiString必须是string类型");
2134
+ throw new TypeError("参数emojiString必须是string类型");
2141
2135
  }
2142
2136
  this.MenuHandle.$emoji.error = emojiString;
2143
2137
  }
2144
2138
  /**
2145
2139
  * 设置本地存储的菜单外部的键名
2146
- * @param keyName
2140
+ * @param keyName 键名
2147
2141
  */
2148
2142
  setLocalStorageKeyName(keyName) {
2149
2143
  if (typeof keyName !== "string") {
2150
- throw new Error("参数keyName必须是string类型");
2144
+ throw new TypeError("参数keyName必须是string类型");
2151
2145
  }
2152
2146
  this.MenuHandle.$data.key = keyName;
2153
2147
  }
@@ -4930,403 +4924,401 @@ const clearTimeout$1 = (timerId) => loadOrReturnBroker().clearTimeout(timerId);
4930
4924
  const setInterval = (...args) => loadOrReturnBroker().setInterval(...args);
4931
4925
  const setTimeout$1 = (...args) => loadOrReturnBroker().setTimeout(...args);
4932
4926
 
4933
- /* eslint-disable */
4934
- // ==UserScript==
4935
- // @name ModuleRaid.js
4936
- // @namespace http://tampermonkey.net/
4937
- // @version 6.2.0
4938
- // @description 检索调用webpackJsonp模块,可指定检索的window
4939
- // @author empyrealtear
4940
- // @license MIT
4941
- // @original-script https://github.com/pixeldesu/moduleRaid
4942
- // ==/UserScript==
4943
-
4944
-
4945
- /**
4946
- * Main moduleRaid class
4947
- * @link https://scriptcat.org/zh-CN/script-show-page/2628
4948
- */
4949
- class ModuleRaid {
4950
- /**
4951
- * moduleRaid constructor
4952
- *
4953
- * @example
4954
- * Constructing an instance without any arguments:
4955
- * ```ts
4956
- * const mR = new ModuleRaid()
4957
- * ```
4958
- *
4959
- * Constructing an instance with the optional `opts` object:
4960
- * ```ts
4961
- * const mR = new ModuleRaid({ entrypoint: 'webpackChunk_custom_name' })
4962
- * ```
4963
- *
4964
- * @param opts a object containing options to initialize moduleRaid with
4965
- * - **opts:**
4966
- * - _target_: the window object being searched for
4967
- * - _entrypoint_: the Webpack entrypoint present on the global window object
4968
- * - _debug_: whether debug mode is enabled or not
4969
- * - _strict_: whether strict mode is enabled or not
4970
- */
4971
- constructor(opts) {
4972
- /**
4973
- * A random generated module ID we use for injecting into Webpack
4974
- */
4975
- this.moduleID = Math.random().toString(36).substring(7);
4976
- /**
4977
- * An array containing different argument injection methods for
4978
- * Webpack (before version 4), and subsequently pulling out methods and modules
4979
- * @internal
4980
- */
4981
- this.functionArguments = [
4982
- [
4983
- [0],
4984
- [
4985
- (_e, _t, i) => {
4986
- this.modules = i.c;
4987
- this.constructors = i.m;
4988
- this.get = i;
4989
- },
4990
- ],
4991
- ],
4992
- [
4993
- [1e3],
4994
- {
4995
- [this.moduleID]: (_e, _t, i) => {
4996
- this.modules = i.c;
4997
- this.constructors = i.m;
4998
- this.get = i;
4999
- },
5000
- },
5001
- [[this.moduleID]],
5002
- ],
5003
- ];
5004
- /**
5005
- * An array containing different argument injection methods for
5006
- * Webpack (after version 4), and subsequently pulling out methods and modules
5007
- * @internal
5008
- */
5009
- this.arrayArguments = [
5010
- [
5011
- [this.moduleID],
5012
- {},
5013
- (e) => {
5014
- const mCac = e.m;
5015
- Object.keys(mCac).forEach((mod) => {
5016
- try {
5017
- this.modules[mod] = e(mod);
5018
- }
5019
- catch (err) {
5020
- this.log(`[arrayArguments/1] Failed to require(${mod}) with error:\n${err}\n${err.stack}`);
5021
- }
5022
- });
5023
- this.get = e;
5024
- },
5025
- ],
5026
- this.functionArguments[1],
5027
- ];
5028
- /**
5029
- * Storage for the modules we extracted from Webpack
5030
- */
5031
- this.modules = {};
5032
- /**
5033
- * Storage for the constructors we extracted from Webpack
5034
- */
5035
- this.constructors = [];
5036
- let options = {
5037
- target: window,
5038
- entrypoint: 'webpackJsonp',
5039
- debug: false,
5040
- strict: false,
5041
- };
5042
- if (typeof opts === 'object') {
5043
- options = Object.assign(Object.assign({}, options), opts);
5044
- }
5045
- this.target = options.target;
5046
- this.entrypoint = options.entrypoint;
5047
- this.debug = options.debug;
5048
- this.strict = options.strict;
5049
- this.detectEntrypoint();
5050
- this.fillModules();
5051
- this.replaceGet();
5052
- this.setupPushEvent();
5053
- }
5054
- /**
5055
- * Debug logging method, outputs to the console when {@link ModuleRaid.debug} is true
5056
- *
5057
- * @param {*} message The message to be logged
5058
- * @internal
5059
- */
5060
- log(message) {
5061
- if (this.debug) {
5062
- console.warn(`[moduleRaid] ${message}`);
5063
- }
5064
- }
5065
- /**
5066
- * Method to set an alternative getter if we weren't able to extract __webpack_require__
5067
- * from Webpack
5068
- * @internal
5069
- */
5070
- replaceGet() {
5071
- if (this.get === null) {
5072
- this.get = (key) => this.modules[key];
5073
- }
5074
- }
5075
- /**
5076
- * Method that will try to inject a module into Webpack or get modules
5077
- * depending on it's success it might be more or less brute about it
5078
- * @internal
5079
- */
5080
- fillModules() {
5081
- if (typeof this.target[this.entrypoint] === 'function') {
5082
- this.functionArguments.forEach((argument, index) => {
5083
- try {
5084
- if (this.modules && Object.keys(this.modules).length > 0)
5085
- return;
5086
- this.target[this.entrypoint](...argument);
5087
- }
5088
- catch (err) {
5089
- this.log(`moduleRaid.functionArguments[${index}] failed:\n${err}\n${err.stack}`);
5090
- }
5091
- });
5092
- }
5093
- else {
5094
- this.arrayArguments.forEach((argument, index) => {
5095
- try {
5096
- if (this.modules && Object.keys(this.modules).length > 0)
5097
- return;
5098
- this.target[this.entrypoint].push(argument);
5099
- }
5100
- catch (err) {
5101
- this.log(`Pushing moduleRaid.arrayArguments[${index}] into ${this.entrypoint} failed:\n${err}\n${err.stack}`);
5102
- }
5103
- });
5104
- }
5105
- if (this.modules && Object.keys(this.modules).length == 0) {
5106
- let moduleEnd = false;
5107
- let moduleIterator = 0;
5108
- if (typeof this.target[this.entrypoint] != 'function' || !this.target[this.entrypoint]([], [], [moduleIterator])) {
5109
- throw Error('Unknown Webpack structure');
5110
- }
5111
- while (!moduleEnd) {
5112
- try {
5113
- this.modules[moduleIterator] = this.target[this.entrypoint]([], [], [moduleIterator]);
5114
- moduleIterator++;
5115
- }
5116
- catch (err) {
5117
- moduleEnd = true;
5118
- }
5119
- }
5120
- }
5121
- }
5122
- /**
5123
- * Method to hook into `window[this.entrypoint].push` adding a listener for new
5124
- * chunks being pushed into Webpack
5125
- *
5126
- * @example
5127
- * You can listen for newly pushed packages using the `moduleraid:webpack-push` event
5128
- * on `document`
5129
- *
5130
- * ```ts
5131
- * document.addEventListener('moduleraid:webpack-push', (e) => {
5132
- * // e.detail contains the arguments push() was called with
5133
- * console.log(e.detail)
5134
- * })
5135
- * ```
5136
- * @internal
5137
- */
5138
- setupPushEvent() {
5139
- const originalPush = this.target[this.entrypoint].push;
5140
- this.target[this.entrypoint].push = (...args) => {
5141
- const result = Reflect.apply(originalPush, this.target[this.entrypoint], args);
5142
- document.dispatchEvent(new CustomEvent('moduleraid:webpack-push', { detail: args }));
5143
- return result;
5144
- };
5145
- }
5146
- /**
5147
- * Method to try autodetecting a Webpack JSONP entrypoint based on common naming
5148
- *
5149
- * If the default entrypoint, or the entrypoint that's passed to the moduleRaid constructor
5150
- * already matches, the method exits early
5151
- *
5152
- * If `options.strict` has been set in the constructor and the initial entrypoint cannot
5153
- * be found, this method will error, demanding a strictly set entrypoint
5154
- * @internal
5155
- */
5156
- detectEntrypoint() {
5157
- if (this.target[this.entrypoint] != undefined) {
5158
- return;
5159
- }
5160
- if (this.strict) {
5161
- throw Error(`Strict mode is enabled and entrypoint at window.${this.entrypoint} couldn't be found. Please specify the correct one!`);
5162
- }
5163
- let windowObjects = Object.keys(this.target);
5164
- windowObjects = windowObjects
5165
- .filter((object) => object.toLowerCase().includes('chunk') || object.toLowerCase().includes('webpack'))
5166
- .filter((object) => typeof this.target[object] === 'function' || Array.isArray(this.target[object]));
5167
- if (windowObjects.length > 1) {
5168
- throw Error(`Multiple possible endpoints have been detected, please create a new moduleRaid instance with a specific one:\n${windowObjects.join(', ')}`);
5169
- }
5170
- if (windowObjects.length === 0) {
5171
- throw Error('No Webpack JSONP entrypoints could be detected');
5172
- }
5173
- this.log(`Entrypoint has been detected at window.${windowObjects[0]} and set for injection`);
5174
- this.entrypoint = windowObjects[0];
5175
- }
5176
- /**
5177
- * Recursive object-search function for modules
5178
- *
5179
- * @param object the object to search through
5180
- * @param query the query the object keys/values are searched for
5181
- * @returns boolean state of `object` containing `query` somewhere in it
5182
- * @internal
5183
- */
5184
- searchObject(object, query) {
5185
- for (const key in object) {
5186
- const value = object[key];
5187
- const lowerCaseQuery = query.toLowerCase();
5188
- if (typeof value != 'object') {
5189
- const lowerCaseKey = key.toString().toLowerCase();
5190
- if (lowerCaseKey.includes(lowerCaseQuery))
5191
- return true;
5192
- if (typeof value != 'object') {
5193
- const lowerCaseValue = value.toString().toLowerCase();
5194
- if (lowerCaseValue.includes(lowerCaseQuery))
5195
- return true;
5196
- }
5197
- else {
5198
- if (this.searchObject(value, query))
5199
- return true;
5200
- }
5201
- }
5202
- }
5203
- return false;
5204
- }
5205
- /**
5206
- * Method to search through the module object, searching for the fitting content
5207
- * if a string is supplied
5208
- *
5209
- * If query is supplied as a function, everything that returns true when passed
5210
- * to the query function will be returned
5211
- *
5212
- * @example
5213
- * With a string as query argument:
5214
- * ```ts
5215
- * const results = mR.findModule('feature')
5216
- * // => Array of module results
5217
- * ```
5218
- *
5219
- * With a function as query argument:
5220
- * ```ts
5221
- * const results = mR.findModule((module) => { typeof module === 'function' })
5222
- * // => Array of module results
5223
- * ```
5224
- *
5225
- * @param query query to search the module list for
5226
- * @return a list of modules fitting the query
5227
- */
5228
- findModule(query) {
5229
- const results = [];
5230
- const modules = Object.keys(this.modules);
5231
- if (modules.length === 0) {
5232
- throw new Error('There are no modules to search through!');
5233
- }
5234
- modules.forEach((key) => {
5235
- const module = this.modules[key.toString()];
5236
- if (module === undefined)
5237
- return;
5238
- try {
5239
- if (typeof query === 'string') {
5240
- query = query.toLowerCase();
5241
- switch (typeof module) {
5242
- case 'string':
5243
- if (module.toLowerCase().includes(query))
5244
- results.push(module);
5245
- break;
5246
- case 'function':
5247
- if (module.toString().toLowerCase().includes(query))
5248
- results.push(module);
5249
- break;
5250
- case 'object':
5251
- if (this.searchObject(module, query))
5252
- results.push(module);
5253
- break;
5254
- }
5255
- }
5256
- else if (typeof query === 'function') {
5257
- if (query(module))
5258
- results.push(module);
5259
- }
5260
- else {
5261
- throw new TypeError(`findModule can only find via string and function, ${typeof query} was passed`);
5262
- }
5263
- }
5264
- catch (err) {
5265
- this.log(`There was an error while searching through module '${key}':\n${err}\n${err.stack}`);
5266
- }
5267
- });
5268
- return results;
5269
- }
5270
- /**
5271
- * Method to search through the constructor array, searching for the fitting content
5272
- * if a string is supplied
5273
- *
5274
- * If query is supplied as a function, everything that returns true when passed
5275
- * to the query function will be returned
5276
- *
5277
- * @example
5278
- * With a string as query argument:
5279
- * ```ts
5280
- * const results = mR.findConstructor('feature')
5281
- * // => Array of constructor/module tuples
5282
- * ```
5283
- *
5284
- * With a function as query argument:
5285
- * ```ts
5286
- * const results = mR.findConstructor((constructor) => { constructor.prototype.value !== undefined })
5287
- * // => Array of constructor/module tuples
5288
- * ```
5289
- *
5290
- * Accessing the resulting data:
5291
- * ```ts
5292
- * // With array destructuring (ES6)
5293
- * const [constructor, module] = results[0]
5294
- *
5295
- * // ...or...
5296
- *
5297
- * // regular access
5298
- * const constructor = results[0][0]
5299
- * const module = results[0][1]
5300
- * ```
5301
- *
5302
- * @param query query to search the constructor list for
5303
- * @returns a list of constructor/module tuples fitting the query
5304
- */
5305
- findConstructor(query) {
5306
- const results = [];
5307
- const constructors = Object.keys(this.constructors);
5308
- if (constructors.length === 0) {
5309
- throw new Error('There are no constructors to search through!');
5310
- }
5311
- constructors.forEach((key) => {
5312
- const constructor = this.constructors[key];
5313
- try {
5314
- if (typeof query === 'string') {
5315
- query = query.toLowerCase();
5316
- if (constructor.toString().toLowerCase().includes(query))
5317
- results.push([this.constructors[key], this.modules[key]]);
5318
- }
5319
- else if (typeof query === 'function') {
5320
- if (query(constructor))
5321
- results.push([this.constructors[key], this.modules[key]]);
5322
- }
5323
- }
5324
- catch (err) {
5325
- this.log(`There was an error while searching through constructor '${key}':\n${err}\n${err.stack}`);
5326
- }
5327
- });
5328
- return results;
5329
- }
4927
+ /* eslint-disable */
4928
+ // ==UserScript==
4929
+ // @name ModuleRaid.js
4930
+ // @namespace http://tampermonkey.net/
4931
+ // @version 6.2.0
4932
+ // @description 检索调用webpackJsonp模块,可指定检索的window
4933
+ // @author empyrealtear
4934
+ // @license MIT
4935
+ // @original-script https://github.com/pixeldesu/moduleRaid
4936
+ // ==/UserScript==
4937
+ /**
4938
+ * Main moduleRaid class
4939
+ * @link https://scriptcat.org/zh-CN/script-show-page/2628
4940
+ */
4941
+ class ModuleRaid {
4942
+ /**
4943
+ * moduleRaid constructor
4944
+ *
4945
+ * @example
4946
+ * Constructing an instance without any arguments:
4947
+ * ```ts
4948
+ * const mR = new ModuleRaid()
4949
+ * ```
4950
+ *
4951
+ * Constructing an instance with the optional `opts` object:
4952
+ * ```ts
4953
+ * const mR = new ModuleRaid({ entrypoint: 'webpackChunk_custom_name' })
4954
+ * ```
4955
+ *
4956
+ * @param opts a object containing options to initialize moduleRaid with
4957
+ * - **opts:**
4958
+ * - _target_: the window object being searched for
4959
+ * - _entrypoint_: the Webpack entrypoint present on the global window object
4960
+ * - _debug_: whether debug mode is enabled or not
4961
+ * - _strict_: whether strict mode is enabled or not
4962
+ */
4963
+ constructor(opts) {
4964
+ /**
4965
+ * A random generated module ID we use for injecting into Webpack
4966
+ */
4967
+ this.moduleID = Math.random().toString(36).substring(7);
4968
+ /**
4969
+ * An array containing different argument injection methods for
4970
+ * Webpack (before version 4), and subsequently pulling out methods and modules
4971
+ * @internal
4972
+ */
4973
+ this.functionArguments = [
4974
+ [
4975
+ [0],
4976
+ [
4977
+ (_e, _t, i) => {
4978
+ this.modules = i.c;
4979
+ this.constructors = i.m;
4980
+ this.get = i;
4981
+ },
4982
+ ],
4983
+ ],
4984
+ [
4985
+ [1e3],
4986
+ {
4987
+ [this.moduleID]: (_e, _t, i) => {
4988
+ this.modules = i.c;
4989
+ this.constructors = i.m;
4990
+ this.get = i;
4991
+ },
4992
+ },
4993
+ [[this.moduleID]],
4994
+ ],
4995
+ ];
4996
+ /**
4997
+ * An array containing different argument injection methods for
4998
+ * Webpack (after version 4), and subsequently pulling out methods and modules
4999
+ * @internal
5000
+ */
5001
+ this.arrayArguments = [
5002
+ [
5003
+ [this.moduleID],
5004
+ {},
5005
+ (e) => {
5006
+ const mCac = e.m;
5007
+ Object.keys(mCac).forEach((mod) => {
5008
+ try {
5009
+ this.modules[mod] = e(mod);
5010
+ }
5011
+ catch (err) {
5012
+ this.log(`[arrayArguments/1] Failed to require(${mod}) with error:\n${err}\n${err.stack}`);
5013
+ }
5014
+ });
5015
+ this.get = e;
5016
+ },
5017
+ ],
5018
+ this.functionArguments[1],
5019
+ ];
5020
+ /**
5021
+ * Storage for the modules we extracted from Webpack
5022
+ */
5023
+ this.modules = {};
5024
+ /**
5025
+ * Storage for the constructors we extracted from Webpack
5026
+ */
5027
+ this.constructors = [];
5028
+ let options = {
5029
+ target: window,
5030
+ entrypoint: 'webpackJsonp',
5031
+ debug: false,
5032
+ strict: false,
5033
+ };
5034
+ if (typeof opts === 'object') {
5035
+ options = Object.assign(Object.assign({}, options), opts);
5036
+ }
5037
+ this.target = options.target;
5038
+ this.entrypoint = options.entrypoint;
5039
+ this.debug = options.debug;
5040
+ this.strict = options.strict;
5041
+ this.detectEntrypoint();
5042
+ this.fillModules();
5043
+ this.replaceGet();
5044
+ this.setupPushEvent();
5045
+ }
5046
+ /**
5047
+ * Debug logging method, outputs to the console when {@link ModuleRaid.debug} is true
5048
+ *
5049
+ * @param {*} message The message to be logged
5050
+ * @internal
5051
+ */
5052
+ log(message) {
5053
+ if (this.debug) {
5054
+ console.warn(`[moduleRaid] ${message}`);
5055
+ }
5056
+ }
5057
+ /**
5058
+ * Method to set an alternative getter if we weren't able to extract __webpack_require__
5059
+ * from Webpack
5060
+ * @internal
5061
+ */
5062
+ replaceGet() {
5063
+ if (this.get === null) {
5064
+ this.get = (key) => this.modules[key];
5065
+ }
5066
+ }
5067
+ /**
5068
+ * Method that will try to inject a module into Webpack or get modules
5069
+ * depending on it's success it might be more or less brute about it
5070
+ * @internal
5071
+ */
5072
+ fillModules() {
5073
+ if (typeof this.target[this.entrypoint] === 'function') {
5074
+ this.functionArguments.forEach((argument, index) => {
5075
+ try {
5076
+ if (this.modules && Object.keys(this.modules).length > 0)
5077
+ return;
5078
+ this.target[this.entrypoint](...argument);
5079
+ }
5080
+ catch (err) {
5081
+ this.log(`moduleRaid.functionArguments[${index}] failed:\n${err}\n${err.stack}`);
5082
+ }
5083
+ });
5084
+ }
5085
+ else {
5086
+ this.arrayArguments.forEach((argument, index) => {
5087
+ try {
5088
+ if (this.modules && Object.keys(this.modules).length > 0)
5089
+ return;
5090
+ this.target[this.entrypoint].push(argument);
5091
+ }
5092
+ catch (err) {
5093
+ this.log(`Pushing moduleRaid.arrayArguments[${index}] into ${this.entrypoint} failed:\n${err}\n${err.stack}`);
5094
+ }
5095
+ });
5096
+ }
5097
+ if (this.modules && Object.keys(this.modules).length == 0) {
5098
+ let moduleEnd = false;
5099
+ let moduleIterator = 0;
5100
+ if (typeof this.target[this.entrypoint] != 'function' || !this.target[this.entrypoint]([], [], [moduleIterator])) {
5101
+ throw Error('Unknown Webpack structure');
5102
+ }
5103
+ while (!moduleEnd) {
5104
+ try {
5105
+ this.modules[moduleIterator] = this.target[this.entrypoint]([], [], [moduleIterator]);
5106
+ moduleIterator++;
5107
+ }
5108
+ catch (err) {
5109
+ moduleEnd = true;
5110
+ }
5111
+ }
5112
+ }
5113
+ }
5114
+ /**
5115
+ * Method to hook into `window[this.entrypoint].push` adding a listener for new
5116
+ * chunks being pushed into Webpack
5117
+ *
5118
+ * @example
5119
+ * You can listen for newly pushed packages using the `moduleraid:webpack-push` event
5120
+ * on `document`
5121
+ *
5122
+ * ```ts
5123
+ * document.addEventListener('moduleraid:webpack-push', (e) => {
5124
+ * // e.detail contains the arguments push() was called with
5125
+ * console.log(e.detail)
5126
+ * })
5127
+ * ```
5128
+ * @internal
5129
+ */
5130
+ setupPushEvent() {
5131
+ const originalPush = this.target[this.entrypoint].push;
5132
+ this.target[this.entrypoint].push = (...args) => {
5133
+ const result = Reflect.apply(originalPush, this.target[this.entrypoint], args);
5134
+ document.dispatchEvent(new CustomEvent('moduleraid:webpack-push', { detail: args }));
5135
+ return result;
5136
+ };
5137
+ }
5138
+ /**
5139
+ * Method to try autodetecting a Webpack JSONP entrypoint based on common naming
5140
+ *
5141
+ * If the default entrypoint, or the entrypoint that's passed to the moduleRaid constructor
5142
+ * already matches, the method exits early
5143
+ *
5144
+ * If `options.strict` has been set in the constructor and the initial entrypoint cannot
5145
+ * be found, this method will error, demanding a strictly set entrypoint
5146
+ * @internal
5147
+ */
5148
+ detectEntrypoint() {
5149
+ if (this.target[this.entrypoint] != undefined) {
5150
+ return;
5151
+ }
5152
+ if (this.strict) {
5153
+ throw Error(`Strict mode is enabled and entrypoint at window.${this.entrypoint} couldn't be found. Please specify the correct one!`);
5154
+ }
5155
+ let windowObjects = Object.keys(this.target);
5156
+ windowObjects = windowObjects
5157
+ .filter((object) => object.toLowerCase().includes('chunk') || object.toLowerCase().includes('webpack'))
5158
+ .filter((object) => typeof this.target[object] === 'function' || Array.isArray(this.target[object]));
5159
+ if (windowObjects.length > 1) {
5160
+ throw Error(`Multiple possible endpoints have been detected, please create a new moduleRaid instance with a specific one:\n${windowObjects.join(', ')}`);
5161
+ }
5162
+ if (windowObjects.length === 0) {
5163
+ throw Error('No Webpack JSONP entrypoints could be detected');
5164
+ }
5165
+ this.log(`Entrypoint has been detected at window.${windowObjects[0]} and set for injection`);
5166
+ this.entrypoint = windowObjects[0];
5167
+ }
5168
+ /**
5169
+ * Recursive object-search function for modules
5170
+ *
5171
+ * @param object the object to search through
5172
+ * @param query the query the object keys/values are searched for
5173
+ * @returns boolean state of `object` containing `query` somewhere in it
5174
+ * @internal
5175
+ */
5176
+ searchObject(object, query) {
5177
+ for (const key in object) {
5178
+ const value = object[key];
5179
+ const lowerCaseQuery = query.toLowerCase();
5180
+ if (typeof value != 'object') {
5181
+ const lowerCaseKey = key.toString().toLowerCase();
5182
+ if (lowerCaseKey.includes(lowerCaseQuery))
5183
+ return true;
5184
+ if (typeof value != 'object') {
5185
+ const lowerCaseValue = value.toString().toLowerCase();
5186
+ if (lowerCaseValue.includes(lowerCaseQuery))
5187
+ return true;
5188
+ }
5189
+ else {
5190
+ if (this.searchObject(value, query))
5191
+ return true;
5192
+ }
5193
+ }
5194
+ }
5195
+ return false;
5196
+ }
5197
+ /**
5198
+ * Method to search through the module object, searching for the fitting content
5199
+ * if a string is supplied
5200
+ *
5201
+ * If query is supplied as a function, everything that returns true when passed
5202
+ * to the query function will be returned
5203
+ *
5204
+ * @example
5205
+ * With a string as query argument:
5206
+ * ```ts
5207
+ * const results = mR.findModule('feature')
5208
+ * // => Array of module results
5209
+ * ```
5210
+ *
5211
+ * With a function as query argument:
5212
+ * ```ts
5213
+ * const results = mR.findModule((module) => { typeof module === 'function' })
5214
+ * // => Array of module results
5215
+ * ```
5216
+ *
5217
+ * @param query query to search the module list for
5218
+ * @return a list of modules fitting the query
5219
+ */
5220
+ findModule(query) {
5221
+ const results = [];
5222
+ const modules = Object.keys(this.modules);
5223
+ if (modules.length === 0) {
5224
+ throw new Error('There are no modules to search through!');
5225
+ }
5226
+ modules.forEach((key) => {
5227
+ const module = this.modules[key.toString()];
5228
+ if (module === undefined)
5229
+ return;
5230
+ try {
5231
+ if (typeof query === 'string') {
5232
+ query = query.toLowerCase();
5233
+ switch (typeof module) {
5234
+ case 'string':
5235
+ if (module.toLowerCase().includes(query))
5236
+ results.push(module);
5237
+ break;
5238
+ case 'function':
5239
+ if (module.toString().toLowerCase().includes(query))
5240
+ results.push(module);
5241
+ break;
5242
+ case 'object':
5243
+ if (this.searchObject(module, query))
5244
+ results.push(module);
5245
+ break;
5246
+ }
5247
+ }
5248
+ else if (typeof query === 'function') {
5249
+ if (query(module))
5250
+ results.push(module);
5251
+ }
5252
+ else {
5253
+ throw new TypeError(`findModule can only find via string and function, ${typeof query} was passed`);
5254
+ }
5255
+ }
5256
+ catch (err) {
5257
+ this.log(`There was an error while searching through module '${key}':\n${err}\n${err.stack}`);
5258
+ }
5259
+ });
5260
+ return results;
5261
+ }
5262
+ /**
5263
+ * Method to search through the constructor array, searching for the fitting content
5264
+ * if a string is supplied
5265
+ *
5266
+ * If query is supplied as a function, everything that returns true when passed
5267
+ * to the query function will be returned
5268
+ *
5269
+ * @example
5270
+ * With a string as query argument:
5271
+ * ```ts
5272
+ * const results = mR.findConstructor('feature')
5273
+ * // => Array of constructor/module tuples
5274
+ * ```
5275
+ *
5276
+ * With a function as query argument:
5277
+ * ```ts
5278
+ * const results = mR.findConstructor((constructor) => { constructor.prototype.value !== undefined })
5279
+ * // => Array of constructor/module tuples
5280
+ * ```
5281
+ *
5282
+ * Accessing the resulting data:
5283
+ * ```ts
5284
+ * // With array destructuring (ES6)
5285
+ * const [constructor, module] = results[0]
5286
+ *
5287
+ * // ...or...
5288
+ *
5289
+ * // regular access
5290
+ * const constructor = results[0][0]
5291
+ * const module = results[0][1]
5292
+ * ```
5293
+ *
5294
+ * @param query query to search the constructor list for
5295
+ * @returns a list of constructor/module tuples fitting the query
5296
+ */
5297
+ findConstructor(query) {
5298
+ const results = [];
5299
+ const constructors = Object.keys(this.constructors);
5300
+ if (constructors.length === 0) {
5301
+ throw new Error('There are no constructors to search through!');
5302
+ }
5303
+ constructors.forEach((key) => {
5304
+ const constructor = this.constructors[key];
5305
+ try {
5306
+ if (typeof query === 'string') {
5307
+ query = query.toLowerCase();
5308
+ if (constructor.toString().toLowerCase().includes(query))
5309
+ results.push([this.constructors[key], this.modules[key]]);
5310
+ }
5311
+ else if (typeof query === 'function') {
5312
+ if (query(constructor))
5313
+ results.push([this.constructors[key], this.modules[key]]);
5314
+ }
5315
+ }
5316
+ catch (err) {
5317
+ this.log(`There was an error while searching through constructor '${key}':\n${err}\n${err.stack}`);
5318
+ }
5319
+ });
5320
+ return results;
5321
+ }
5330
5322
  }
5331
5323
 
5332
5324
  class DOMUtils {
@@ -5498,7 +5490,7 @@ class DOMUtils {
5498
5490
  }
5499
5491
  const domUtils = new DOMUtils();
5500
5492
 
5501
- const version = "2.9.4";
5493
+ const version = "2.9.6";
5502
5494
 
5503
5495
  class Utils {
5504
5496
  windowApi;