@whitesev/utils 2.3.0 → 2.3.2

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.
@@ -1580,7 +1580,7 @@ var Utils = (function () {
1580
1580
  return uuid;
1581
1581
  }
1582
1582
  else {
1583
- console.warn("HttpxRequestHook.addBeforeRequestCallBack: fn is not a function");
1583
+ console.warn("[Httpx-HttpxRequestHook.addBeforeRequestCallBack] fn is not a function");
1584
1584
  }
1585
1585
  },
1586
1586
  /**
@@ -2059,65 +2059,81 @@ var Utils = (function () {
2059
2059
  */
2060
2060
  onLoad(details, resolve, reject, argumentsList) {
2061
2061
  /* X浏览器会因为设置了responseType导致不返回responseText */
2062
- let Response = argumentsList[0];
2062
+ let originResponse = argumentsList[0];
2063
2063
  /* responseText为空,response不为空的情况 */
2064
- if (utils.isNull(Response["responseText"]) &&
2065
- utils.isNotNull(Response["response"])) {
2066
- if (typeof Response["response"] === "object") {
2064
+ if (utils.isNull(originResponse["responseText"]) &&
2065
+ utils.isNotNull(originResponse["response"])) {
2066
+ if (typeof originResponse["response"] === "object") {
2067
2067
  utils.tryCatch().run(() => {
2068
- Response["responseText"] = JSON.stringify(Response["response"]);
2068
+ originResponse["responseText"] = JSON.stringify(originResponse["response"]);
2069
2069
  });
2070
2070
  }
2071
2071
  else {
2072
- Response["responseText"] = Response["response"];
2072
+ originResponse["responseText"] = originResponse["response"];
2073
2073
  }
2074
2074
  }
2075
2075
  /* response为空,responseText不为空的情况 */
2076
- if (Response["response"] == null &&
2077
- typeof Response["responseText"] === "string" &&
2078
- Response["responseText"].trim() !== "") {
2079
- let newResponse = Response["responseText"];
2076
+ if (originResponse["response"] == null &&
2077
+ typeof originResponse["responseText"] === "string" &&
2078
+ originResponse["responseText"].trim() !== "") {
2079
+ /** 原始的请求text */
2080
+ let httpxResponseText = originResponse.responseText;
2081
+ // 自定义个新的response
2082
+ let httpxResponse = httpxResponseText;
2080
2083
  if (details.responseType === "json") {
2081
- newResponse = utils.toJSON(Response["responseText"]);
2084
+ httpxResponse = utils.toJSON(httpxResponseText);
2082
2085
  }
2083
2086
  else if (details.responseType === "document") {
2084
2087
  let parser = new DOMParser();
2085
- newResponse = parser.parseFromString(Response["responseText"], "text/html");
2088
+ httpxResponse = parser.parseFromString(httpxResponseText, "text/html");
2086
2089
  }
2087
2090
  else if (details.responseType === "arraybuffer") {
2088
2091
  let encoder = new TextEncoder();
2089
- let arrayBuffer = encoder.encode(Response["responseText"]);
2090
- newResponse = arrayBuffer;
2092
+ let arrayBuffer = encoder.encode(httpxResponseText);
2093
+ httpxResponse = arrayBuffer;
2091
2094
  }
2092
2095
  else if (details.responseType === "blob") {
2093
2096
  let encoder = new TextEncoder();
2094
- let arrayBuffer = encoder.encode(Response["responseText"]);
2095
- newResponse = new Blob([arrayBuffer]);
2096
- }
2097
- else {
2098
- newResponse = Response["responseText"];
2097
+ let arrayBuffer = encoder.encode(httpxResponseText);
2098
+ httpxResponse = new Blob([arrayBuffer]);
2099
2099
  }
2100
+ // 尝试覆盖原response
2100
2101
  try {
2101
- Response["response"] = newResponse;
2102
+ let setStatus = Reflect.set(originResponse, "response", httpxResponse);
2103
+ if (!setStatus) {
2104
+ console.warn("[Httpx-HttpxCallBack.oonLoad] 覆盖原始 response 失败,尝试添加新的httpxResponse");
2105
+ try {
2106
+ Reflect.set(originResponse, "httpxResponse", httpxResponse);
2107
+ }
2108
+ catch (error) {
2109
+ console.warn("[Httpx-HttpxCallBack.oonLoad] httpxResponse 无法被覆盖");
2110
+ }
2111
+ }
2102
2112
  }
2103
2113
  catch (error) {
2104
- console.warn("response 无法被覆盖");
2114
+ console.warn("[Httpx-HttpxCallBack.oonLoad] 原始 response 无法被覆盖,尝试添加新的httpxResponse");
2115
+ try {
2116
+ Reflect.set(originResponse, "httpxResponse", httpxResponse);
2117
+ }
2118
+ catch (error) {
2119
+ console.warn("[Httpx-HttpxCallBack.oonLoad] httpxResponse 无法被覆盖");
2120
+ }
2105
2121
  }
2106
2122
  }
2107
2123
  /* Stay扩展中没有finalUrl,对应的是responseURL */
2108
- if (Response["finalUrl"] == null &&
2109
- Response["responseURL"] != null) {
2110
- Response["finalUrl"] = Response["responseURL"];
2124
+ let originResponseURL = Reflect.get(originResponse, "responseURL");
2125
+ if (originResponse["finalUrl"] == null && originResponseURL != null) {
2126
+ Reflect.set(originResponse, "finalUrl", originResponseURL);
2111
2127
  }
2112
2128
  /* 状态码2xx都是成功的 */
2113
- if (Math.floor(Response.status / 100) === 2) {
2114
- if (this.context.HttpxResponseHook.successResponseCallBack(Response, details) == null) {
2129
+ if (Math.floor(originResponse.status / 100) === 2) {
2130
+ if (this.context.HttpxResponseHook.successResponseCallBack(originResponse, details) == null) {
2115
2131
  // reject(new TypeError("response is intercept with onloada"));
2116
2132
  return;
2117
2133
  }
2118
2134
  resolve({
2119
2135
  status: true,
2120
- data: Response,
2136
+ data: originResponse,
2121
2137
  details: details,
2122
2138
  msg: "请求完毕",
2123
2139
  type: "onload",
@@ -2162,7 +2178,7 @@ var Utils = (function () {
2162
2178
  */
2163
2179
  request(details) {
2164
2180
  if (this.context.#LOG_DETAILS) {
2165
- console.log("Httpx请求配置👇", details);
2181
+ console.log("[Httpx-HttpxRequest.request] 请求前的配置👇", details);
2166
2182
  }
2167
2183
  if (typeof this.context.HttpxRequestHook.beforeRequestCallBack ===
2168
2184
  "function") {
@@ -2195,33 +2211,38 @@ var Utils = (function () {
2195
2211
  */
2196
2212
  fetch(details, fetchRequestInit, abortController) {
2197
2213
  fetch(details.url, fetchRequestInit)
2198
- .then(async (resp) => {
2199
- /**
2200
- * @type {HttpxAsyncResultData}
2201
- */
2214
+ .then(async (fetchResponse) => {
2215
+ /** 自定义的response */
2202
2216
  let httpxResponse = {
2203
2217
  isFetch: true,
2204
- finalUrl: resp.url,
2218
+ finalUrl: fetchResponse.url,
2205
2219
  readyState: 4,
2206
- status: resp.status,
2207
- statusText: resp.statusText,
2220
+ // @ts-ignore
2221
+ status: fetchResponse.status,
2222
+ statusText: fetchResponse.statusText,
2208
2223
  response: void 0,
2209
- responseFetchHeaders: resp.headers,
2224
+ responseFetchHeaders: fetchResponse.headers,
2210
2225
  responseHeaders: "",
2226
+ // @ts-ignore
2211
2227
  responseText: void 0,
2212
2228
  responseType: details.responseType,
2213
2229
  responseXML: void 0,
2214
2230
  };
2215
2231
  Object.assign(httpxResponse, details.context || {});
2216
- for (const [key, value] of resp.headers.entries()) {
2232
+ // headers转为字符串
2233
+ for (const [key, value] of fetchResponse.headers.entries()) {
2217
2234
  httpxResponse.responseHeaders += `${key}: ${value}\n`;
2218
2235
  }
2219
- /* 如果是流式传输,直接返回 */
2236
+ /** 请求返回的类型 */
2237
+ const fetchResponseType = fetchResponse.headers.get("Content-Type");
2238
+ /* 如果需要stream,且获取到的是stream,那直接返回 */
2220
2239
  if (details.responseType === "stream" ||
2221
- (resp.headers.has("Content-Type") &&
2222
- resp.headers.get("Content-Type").includes("text/event-stream"))) {
2223
- httpxResponse["isStream"] = true;
2224
- httpxResponse.response = resp.body;
2240
+ (fetchResponse.headers.has("Content-Type") &&
2241
+ fetchResponse.headers
2242
+ .get("Content-Type")
2243
+ .includes("text/event-stream"))) {
2244
+ Reflect.set(httpxResponse, "isStream", true);
2245
+ Reflect.set(httpxResponse, "response", fetchResponse.body);
2225
2246
  Reflect.deleteProperty(httpxResponse, "responseText");
2226
2247
  Reflect.deleteProperty(httpxResponse, "responseXML");
2227
2248
  details.onload(httpxResponse);
@@ -2233,42 +2254,57 @@ var Utils = (function () {
2233
2254
  let responseText = "";
2234
2255
  /** 响应xml文档 */
2235
2256
  let responseXML = "";
2236
- let arrayBuffer = await resp.arrayBuffer();
2257
+ /** 先获取二进制数据 */
2258
+ let arrayBuffer = await fetchResponse.arrayBuffer();
2259
+ /** 数据编码 */
2237
2260
  let encoding = "utf-8";
2238
- if (resp.headers.has("Content-Type")) {
2239
- let charsetMatched = resp.headers
2261
+ if (fetchResponse.headers.has("Content-Type")) {
2262
+ let charsetMatched = fetchResponse.headers
2240
2263
  .get("Content-Type")
2241
2264
  ?.match(/charset=(.+)/);
2242
2265
  if (charsetMatched) {
2243
2266
  encoding = charsetMatched[1];
2267
+ encoding = encoding.toLowerCase();
2244
2268
  }
2245
2269
  }
2270
+ // Failed to construct 'TextDecoder': The encoding label provided ('"UTF-8"') is invalid.
2271
+ // 去除引号
2272
+ encoding = encoding.replace(/('|")/gi, "");
2273
+ // 编码
2246
2274
  let textDecoder = new TextDecoder(encoding);
2247
2275
  responseText = textDecoder.decode(arrayBuffer);
2248
2276
  response = responseText;
2249
2277
  if (details.responseType === "arraybuffer") {
2278
+ // response返回格式是二进制流
2250
2279
  response = arrayBuffer;
2251
2280
  }
2252
2281
  else if (details.responseType === "blob") {
2282
+ // response返回格式是blob
2253
2283
  response = new Blob([arrayBuffer]);
2254
2284
  }
2285
+ else if (details.responseType === "json" ||
2286
+ (typeof fetchResponseType === "string" &&
2287
+ fetchResponseType.includes("application/json"))) {
2288
+ // response返回格式是JSON格式
2289
+ response = utils.toJSON(responseText);
2290
+ }
2255
2291
  else if (details.responseType === "document" ||
2256
2292
  details.responseType == null) {
2293
+ // response返回格式是文档格式
2257
2294
  let parser = new DOMParser();
2258
2295
  response = parser.parseFromString(responseText, "text/html");
2259
2296
  }
2260
- else if (details.responseType === "json") {
2261
- response = utils.toJSON(responseText);
2262
- }
2297
+ // 转为XML结构
2263
2298
  let parser = new DOMParser();
2264
2299
  responseXML = parser.parseFromString(responseText, "text/xml");
2265
- httpxResponse.response = response;
2266
- httpxResponse.responseText = responseText;
2267
- httpxResponse.responseXML = responseXML;
2300
+ Reflect.set(httpxResponse, "response", response);
2301
+ Reflect.set(httpxResponse, "responseText", responseText);
2302
+ Reflect.set(httpxResponse, "responseXML", responseXML);
2303
+ // 执行回调
2268
2304
  details.onload(httpxResponse);
2269
2305
  })
2270
- .catch((err) => {
2271
- if (err.name === "AbortError") {
2306
+ .catch((error) => {
2307
+ if (error.name === "AbortError") {
2272
2308
  return;
2273
2309
  }
2274
2310
  details.onerror({
@@ -2279,7 +2315,7 @@ var Utils = (function () {
2279
2315
  statusText: "",
2280
2316
  responseHeaders: "",
2281
2317
  responseText: "",
2282
- error: err,
2318
+ error: error,
2283
2319
  });
2284
2320
  });
2285
2321
  details.onloadstart({
@@ -2342,7 +2378,7 @@ var Utils = (function () {
2342
2378
  */
2343
2379
  constructor(__xmlHttpRequest__) {
2344
2380
  if (typeof __xmlHttpRequest__ !== "function") {
2345
- console.warn("Httpx未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,强制使用window.fetch");
2381
+ console.warn("[Httpx-constructor] 未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,将默认使用window.fetch");
2346
2382
  }
2347
2383
  this.interceptors.request.context = this;
2348
2384
  this.interceptors.response.context = this;
@@ -6406,13 +6442,29 @@ var Utils = (function () {
6406
6442
  * > ()=>{throw new Error('测试错误')}出现错误
6407
6443
  */
6408
6444
  tryCatch = TryCatch;
6409
- uniqueArray(uniqueArrayData = [], compareArrayData = [], compareFun = (item, item2) => {
6410
- // @ts-ignore
6445
+ uniqueArray(uniqueArrayData = [], compareArrayData, compareFun = (item, item2) => {
6411
6446
  return item === item2;
6412
6447
  }) {
6413
- return Array.from(uniqueArrayData).filter((item) => !Array.from(compareArrayData).some(function (item2) {
6414
- return compareFun(item, item2);
6415
- }));
6448
+ if (typeof compareArrayData === "function") {
6449
+ const compareFn = compareArrayData;
6450
+ const seen = new Set();
6451
+ const result = [];
6452
+ for (const item of uniqueArrayData) {
6453
+ // 使用compareFn函数来获取当前对象的唯一标识
6454
+ const identfier = compareFn(item);
6455
+ // 如果Set中还没有这个标识,则添加到结果数组中,并将其标识存入Set
6456
+ if (!seen.has(identfier)) {
6457
+ seen.add(identfier);
6458
+ result.push(item);
6459
+ }
6460
+ }
6461
+ return result;
6462
+ }
6463
+ else {
6464
+ return Array.from(uniqueArrayData).filter((item) => !Array.from(compareArrayData).some(function (item2) {
6465
+ return compareFun(item, item2);
6466
+ }));
6467
+ }
6416
6468
  }
6417
6469
  waitArrayLoopToEnd(data, handleFunc) {
6418
6470
  let UtilsContext = this;