@whitesev/utils 2.9.3 → 2.9.5

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