@whitesev/utils 1.0.5 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/index.amd.js +2123 -2269
  2. package/dist/index.amd.js.map +1 -1
  3. package/dist/index.cjs.js +2123 -2269
  4. package/dist/index.cjs.js.map +1 -1
  5. package/dist/index.esm.js +2123 -2269
  6. package/dist/index.esm.js.map +1 -1
  7. package/dist/index.iife.js +2123 -2269
  8. package/dist/index.iife.js.map +1 -1
  9. package/dist/index.system.js +2123 -2269
  10. package/dist/index.system.js.map +1 -1
  11. package/dist/index.umd.js +2123 -2269
  12. package/dist/index.umd.js.map +1 -1
  13. package/dist/src/Dictionary.d.ts +82 -0
  14. package/dist/src/Hooks.d.ts +11 -0
  15. package/dist/src/Httpx.d.ts +1201 -0
  16. package/dist/src/LockFunction.d.ts +31 -0
  17. package/dist/src/Log.d.ts +96 -0
  18. package/dist/src/Progress.d.ts +37 -0
  19. package/dist/src/UtilsGMMenu.d.ts +156 -0
  20. package/dist/src/index.d.ts +20 -27
  21. package/dist/src/indexedDB.d.ts +73 -0
  22. package/dist/src/tryCatch.d.ts +31 -0
  23. package/package.json +36 -36
  24. package/src/Dictionary.ts +152 -0
  25. package/src/{Hooks/Hooks.js → Hooks.ts} +31 -17
  26. package/src/{Httpx/index.d.ts → Httpx.ts} +837 -46
  27. package/src/LockFunction.ts +62 -0
  28. package/src/Log.ts +281 -0
  29. package/src/Progress.ts +143 -0
  30. package/src/UtilsGMMenu.ts +681 -0
  31. package/src/index.ts +17 -29
  32. package/src/indexedDB.ts +421 -0
  33. package/src/tryCatch.ts +107 -0
  34. package/tsconfig.json +1 -1
  35. package/dist/src/Dictionary/Dictionary.d.ts +0 -85
  36. package/dist/src/Hooks/Hooks.d.ts +0 -5
  37. package/dist/src/Httpx/Httpx.d.ts +0 -50
  38. package/dist/src/LockFunction/LockFunction.d.ts +0 -16
  39. package/dist/src/Log/Log.d.ts +0 -66
  40. package/dist/src/Progress/Progress.d.ts +0 -6
  41. package/dist/src/UtilsGMMenu/UtilsGMMenu.d.ts +0 -119
  42. package/dist/src/indexedDB/indexedDB.d.ts +0 -165
  43. package/dist/src/tryCatch/tryCatch.d.ts +0 -31
  44. package/src/Dictionary/Dictionary.js +0 -157
  45. package/src/Dictionary/index.d.ts +0 -52
  46. package/src/Hooks/index.d.ts +0 -16
  47. package/src/Httpx/Httpx.js +0 -747
  48. package/src/LockFunction/LockFunction.js +0 -35
  49. package/src/LockFunction/index.d.ts +0 -47
  50. package/src/Log/Log.js +0 -256
  51. package/src/Log/index.d.ts +0 -91
  52. package/src/Progress/Progress.js +0 -98
  53. package/src/Progress/index.d.ts +0 -30
  54. package/src/UtilsGMMenu/UtilsGMMenu.js +0 -464
  55. package/src/UtilsGMMenu/index.d.ts +0 -224
  56. package/src/indexedDB/index.d.ts +0 -128
  57. package/src/indexedDB/indexedDB.js +0 -355
  58. package/src/tryCatch/index.d.ts +0 -6
  59. package/src/tryCatch/tryCatch.js +0 -100
@@ -1,8 +1,10 @@
1
+ import { AnyObject, Utils } from ".";
2
+
1
3
  /**
2
4
  * 状态码
3
5
  * + https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status
4
6
  */
5
- type HttpxStatus =
7
+ export type HttpxStatus =
6
8
  | 100
7
9
  | 101
8
10
  | 102
@@ -66,7 +68,7 @@ type HttpxStatus =
66
68
  * HTTP 请求方法
67
69
  * + https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods
68
70
  */
69
- type HttpxMethod =
71
+ export type HttpxMethod =
70
72
  | "GET"
71
73
  | "HEAD"
72
74
  | "POST"
@@ -77,21 +79,25 @@ type HttpxMethod =
77
79
  | "TRACE"
78
80
  | "PATCH";
79
81
 
80
- type HttpxRedirect = "follow" | "error" | "manual";
82
+ export type HttpxRedirect = "follow" | "error" | "manual";
81
83
 
82
- type HttpxBinary =
84
+ export type HttpxBinary =
83
85
  | Uint8ArrayConstructor
84
86
  | ArrayBufferConstructor
85
87
  | DataViewConstructor
86
88
  | Blob
87
89
  | File;
88
90
 
89
- type HttpxResponseCallBackType = "onload" | "onerror" | "ontimeout" | "onabort";
91
+ export type HttpxResponseCallBackType =
92
+ | "onload"
93
+ | "onerror"
94
+ | "ontimeout"
95
+ | "onabort";
90
96
 
91
- type HttpxResponseMap = {
97
+ export type HttpxResponseMap = {
92
98
  arraybuffer: ArrayBuffer;
93
99
  blob: Blob;
94
- json: UtilsNestedObjectWithToString;
100
+ json: AnyObject;
95
101
  stream: ReadableStream<string>;
96
102
  document: Document;
97
103
  undefined: string;
@@ -101,7 +107,7 @@ type HttpxResponseMap = {
101
107
  * headers的配置
102
108
  * + https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers
103
109
  */
104
- declare interface HttpxHeaders {
110
+ export declare interface HttpxHeaders {
105
111
  /**
106
112
  * Accept 请求头用来告知(服务器)客户端可以处理的内容类型,这种内容类型用MIME 类型来表示。
107
113
  * 借助内容协商机制, 服务器可以从诸多备选项中选择一项进行应用,并使用 Content-Type 应答头通知客户端它的选择。
@@ -915,7 +921,7 @@ declare interface HttpxHeaders {
915
921
  "X-XSS-Protection"?: string;
916
922
  [key: string]: any;
917
923
  }
918
- declare interface HttpxRequestInit extends RequestInit {
924
+ export declare interface HttpxRequestInit extends RequestInit {
919
925
  /**
920
926
  * 请求的 body 信息:可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。
921
927
  *
@@ -995,7 +1001,7 @@ declare interface HttpxRequestInit extends RequestInit {
995
1001
  /**
996
1002
  * 请求的配置
997
1003
  */
998
- declare interface HttpxDetails {
1004
+ export declare interface HttpxDetails {
999
1005
  /**
1000
1006
  * 网址
1001
1007
  */
@@ -1045,7 +1051,7 @@ declare interface HttpxDetails {
1045
1051
  /**
1046
1052
  * 将该对象添加到响应的属性中,可为空
1047
1053
  */
1048
- context?: UtilsNestedObjectWithToString;
1054
+ context?: AnyObject;
1049
1055
  /**
1050
1056
  * 重写mimeType,可为空
1051
1057
  */
@@ -1073,7 +1079,7 @@ declare interface HttpxDetails {
1073
1079
  /**
1074
1080
  * (可选)当请求被取消或中断,触发该回调
1075
1081
  */
1076
- onabort?: () => void;
1082
+ onabort?: (response?: any) => void;
1077
1083
  /**
1078
1084
  * (可选)当请求异常,触发该回调,如404
1079
1085
  */
@@ -1081,29 +1087,29 @@ declare interface HttpxDetails {
1081
1087
  /**
1082
1088
  * (可选)当请求超时,触发该回调
1083
1089
  */
1084
- ontimeout?: () => void;
1090
+ ontimeout?: (...args: any[]) => void;
1085
1091
  /**
1086
1092
  * (可选)当请求开始,触发该回调
1087
1093
  */
1088
- onloadstart?: () => void;
1094
+ onloadstart?: (...args: any[]) => void;
1089
1095
  /**
1090
1096
  * (可选)当请求成功时,触发该回调
1091
1097
  */
1092
- onload?: () => void;
1098
+ onload?: (...args: any[]) => void;
1093
1099
  /**
1094
1100
  * (可选)当请求状态改变,触发该回调
1095
1101
  *
1096
1102
  * fetch为true时该回调不触发
1097
1103
  */
1098
- onreadystatechange?: () => void;
1104
+ onreadystatechange?: (...args: any[]) => void;
1099
1105
  /**
1100
1106
  * (可选)当请求上传文件进度改变,触发该回调
1101
1107
  *
1102
1108
  * fetch为true时该回调不触发
1103
1109
  */
1104
- onprogress?: () => void;
1110
+ onprogress?: (...args: any[]) => void;
1105
1111
  }
1106
- declare interface HttpxDetailsConfig extends HttpxDetails {
1112
+ export declare interface HttpxDetailsConfig extends HttpxDetails {
1107
1113
  /**
1108
1114
  * (可选)是否输出请求配置
1109
1115
  */
@@ -1118,7 +1124,7 @@ declare interface HttpxDetailsConfig extends HttpxDetails {
1118
1124
  /**
1119
1125
  * 响应的数据的data
1120
1126
  */
1121
- declare interface HttpxAsyncResultData<T extends HttpxDetails> {
1127
+ export declare interface HttpxAsyncResultData<T extends HttpxDetails> {
1122
1128
  /**
1123
1129
  * 如果fetch为true,且返回的headers中的Content-Type存在text/event-stream或者是主动设置的responseType为stream
1124
1130
  * 则存在该属性为true
@@ -1179,7 +1185,7 @@ declare interface HttpxAsyncResultData<T extends HttpxDetails> {
1179
1185
  /**
1180
1186
  * 响应的数据
1181
1187
  */
1182
- declare interface HttpxAsyncResult<T extends HttpxDetails> {
1188
+ export declare interface HttpxAsyncResult<T extends HttpxDetails> {
1183
1189
  /**
1184
1190
  * 请求状态,状态码为200为成功true,否则false
1185
1191
  */
@@ -1202,50 +1208,787 @@ declare interface HttpxAsyncResult<T extends HttpxDetails> {
1202
1208
  type: HttpxResponseCallBackType;
1203
1209
  }
1204
1210
 
1205
- /** Httpx */
1206
- declare interface UtilsHttpxConstrustor {
1211
+ class Httpx {
1212
+ private GM_Api = {
1213
+ xmlHttpRequest: null as any,
1214
+ };
1215
+ private HttpxRequestHook = {
1216
+ /**
1217
+ * 发送请求前的回调
1218
+ * 如果返回false则阻止本次返回
1219
+ * @param details 当前的请求配置
1220
+ */
1221
+ beforeRequestCallBack(details: HttpxDetails) {},
1222
+ };
1223
+ private HttpxRequestDetails = {
1224
+ context: this,
1225
+ /**
1226
+ * 根据传入的参数处理获取details配置
1227
+ */
1228
+ handleBeforeRequestDetails(...args: (HttpxDetails | string)[]) {
1229
+ let result: HttpxDetails = {};
1230
+ if (typeof args[0] === "string") {
1231
+ /* 传入的是url,details? */
1232
+ let url = args[0];
1233
+ result.url = url;
1234
+ if (typeof args[1] === "object") {
1235
+ /* 处理第二个参数details */
1236
+ let details = args[1];
1237
+ result = details;
1238
+ result.url = url;
1239
+ }
1240
+ } else {
1241
+ /* 传入的是details */
1242
+ result = args[0];
1243
+ }
1244
+ return result;
1245
+ },
1246
+ /**
1247
+ * 获取请求配置
1248
+ * @param method 当前请求方法,默认get
1249
+ * @param resolve promise回调
1250
+ * @param details 请求配置
1251
+ */
1252
+ getDetails(
1253
+ method: HttpxMethod,
1254
+ resolve: (...rags: any[]) => void,
1255
+ details: HttpxDetails
1256
+ ) {
1257
+ let that = this;
1258
+ let result = <Required<HttpxDetails>>{
1259
+ url: details.url || this.context.#defaultDetails.url,
1260
+ method: (method || "GET").toString().toUpperCase(),
1261
+ timeout: details.timeout || this.context.#defaultDetails.timeout,
1262
+ responseType:
1263
+ details.responseType || this.context.#defaultDetails.responseType,
1264
+ /* 对象使用深拷贝 */
1265
+ headers: Utils.deepClone(this.context.#defaultDetails.headers),
1266
+ data: details.data || this.context.#defaultDetails.data,
1267
+ redirect: details.redirect || this.context.#defaultDetails.redirect,
1268
+ cookie: details.cookie || this.context.#defaultDetails.cookie,
1269
+ binary: details.binary || this.context.#defaultDetails.binary,
1270
+ nocache: details.nocache || this.context.#defaultDetails.nocache,
1271
+ revalidate:
1272
+ details.revalidate || this.context.#defaultDetails.revalidate,
1273
+ /* 对象使用深拷贝 */
1274
+ context: Utils.deepClone(
1275
+ details.context || this.context.#defaultDetails.context
1276
+ ),
1277
+ overrideMimeType:
1278
+ details.overrideMimeType ||
1279
+ this.context.#defaultDetails.overrideMimeType,
1280
+ anonymous: details.anonymous || this.context.#defaultDetails.anonymous,
1281
+ fetch: details.fetch || this.context.#defaultDetails.fetch,
1282
+ /* 对象使用深拷贝 */
1283
+ fetchInit: Utils.deepClone(this.context.#defaultDetails.fetchInit),
1284
+ user: details.user || this.context.#defaultDetails.user,
1285
+ password: details.password || this.context.#defaultDetails.password,
1286
+ onabort(...args) {
1287
+ that.context.HttpxCallBack.onAbort(
1288
+ details as Required<HttpxDetails>,
1289
+ resolve,
1290
+ args
1291
+ );
1292
+ },
1293
+ onerror(...args) {
1294
+ that.context.HttpxCallBack.onError(
1295
+ details as Required<HttpxDetails>,
1296
+ resolve,
1297
+ args
1298
+ );
1299
+ },
1300
+ onloadstart(...args) {
1301
+ that.context.HttpxCallBack.onLoadStart(
1302
+ details as Required<HttpxDetails>,
1303
+ args
1304
+ );
1305
+ },
1306
+ onprogress(...args) {
1307
+ that.context.HttpxCallBack.onProgress(
1308
+ details as Required<HttpxDetails>,
1309
+ args
1310
+ );
1311
+ },
1312
+ onreadystatechange(...args) {
1313
+ that.context.HttpxCallBack.onReadyStateChange(
1314
+ details as Required<HttpxDetails>,
1315
+ args
1316
+ );
1317
+ },
1318
+ ontimeout(...args) {
1319
+ that.context.HttpxCallBack.onTimeout(
1320
+ details as Required<HttpxDetails>,
1321
+ resolve,
1322
+ args
1323
+ );
1324
+ },
1325
+ onload(...args) {
1326
+ that.context.HttpxCallBack.onLoad(
1327
+ details as Required<HttpxDetails>,
1328
+ resolve,
1329
+ args
1330
+ );
1331
+ },
1332
+ };
1333
+ if (typeof this.context.GM_Api.xmlHttpRequest !== "function") {
1334
+ result.fetch = true;
1335
+ }
1336
+ if (typeof result.headers === "object") {
1337
+ if (typeof details.headers === "object") {
1338
+ Object.keys(details.headers).forEach((keyName, index) => {
1339
+ if (
1340
+ keyName in result.headers &&
1341
+ details!.headers?.[keyName] == null
1342
+ ) {
1343
+ /* 在默认的header中存在,且设置它新的值为空,那么就是默认的值 */
1344
+ Reflect.deleteProperty(result.headers, keyName);
1345
+ } else {
1346
+ result.headers[keyName] = details?.headers?.[keyName];
1347
+ }
1348
+ });
1349
+ } else {
1350
+ /* details.headers为空 */
1351
+ /* 不做处理 */
1352
+ }
1353
+ } else {
1354
+ (result as HttpxDetails).headers = details.headers;
1355
+ }
1356
+ if (typeof result.fetchInit === "object") {
1357
+ /* 使用assign替换且添加 */
1358
+ if (typeof details.fetchInit === "object") {
1359
+ Object.keys(details.fetchInit).forEach((keyName, index) => {
1360
+ if (
1361
+ keyName in result.fetchInit &&
1362
+ (details as any).fetchInit[keyName] == null
1363
+ ) {
1364
+ /* 在默认的fetchInit中存在,且设置它新的值为空,那么就是默认的值 */
1365
+ Reflect.deleteProperty(result.fetchInit, keyName);
1366
+ } else {
1367
+ (result as any).fetchInit[keyName] = (details as any).fetchInit[
1368
+ keyName
1369
+ ];
1370
+ }
1371
+ });
1372
+ }
1373
+ } else {
1374
+ (result as any).fetchInit = details.fetchInit;
1375
+ }
1376
+ return result;
1377
+ },
1378
+ /**
1379
+ * 处理发送请求的details,去除值为undefined、空function的值
1380
+ * @param details
1381
+ */
1382
+ handle(details: Required<HttpxDetails>): HttpxDetails {
1383
+ Object.keys(details).forEach((keyName) => {
1384
+ if (
1385
+ details[keyName as keyof HttpxDetails] == null ||
1386
+ (details[keyName as keyof HttpxDetails] instanceof Function &&
1387
+ Utils.isNull(details[keyName as keyof HttpxDetails]))
1388
+ ) {
1389
+ Reflect.deleteProperty(details, keyName);
1390
+ return;
1391
+ }
1392
+ });
1393
+ if (Utils.isNull(details.url)) {
1394
+ throw new TypeError(`Utils.Httpx 参数 url不符合要求: ${details.url}`);
1395
+ }
1396
+ /* method值统一大写,兼容Via */
1397
+ (details as any).method = details.method.toUpperCase();
1398
+ /* 判断是否是以http开头,否则主动加上origin */
1399
+ try {
1400
+ new URL(details.url);
1401
+ } catch (error) {
1402
+ if (details.url.startsWith("//")) {
1403
+ details.url = globalThis.location.protocol + details.url;
1404
+ } else if (details.url.startsWith("/")) {
1405
+ details.url = globalThis.location.origin + details.url;
1406
+ } else {
1407
+ details.url = globalThis.location.origin + "/" + details.url;
1408
+ }
1409
+ }
1410
+ return details;
1411
+ },
1412
+ /**
1413
+ * 处理fetch的配置
1414
+ * @param details
1415
+ */
1416
+ handleFetchDetail(details: Required<HttpxDetails>) {
1417
+ /**
1418
+ * fetch的请求配置
1419
+ **/
1420
+ let fetchRequestInit = <RequestInit>{};
1421
+ if (
1422
+ (details.method === "GET" || details.method === "HEAD") &&
1423
+ details.data != null
1424
+ ) {
1425
+ /* GET 或 HEAD 方法的请求不能包含 body 信息 */
1426
+ Reflect.deleteProperty(details, "data");
1427
+ }
1428
+ /* 中止信号控制器 */
1429
+ let abortController = new AbortController();
1430
+ let signal = abortController.signal;
1431
+ signal.onabort = () => {
1432
+ details.onabort({
1433
+ isFetch: true,
1434
+ responseText: "",
1435
+ response: null,
1436
+ readyState: 4,
1437
+ responseHeaders: "",
1438
+ status: 0,
1439
+ statusText: "",
1440
+ error: "aborted",
1441
+ });
1442
+ };
1443
+ fetchRequestInit.method = details.method ?? "GET";
1444
+ fetchRequestInit.headers = details.headers;
1445
+ fetchRequestInit.body = details.data;
1446
+ fetchRequestInit.mode = "cors";
1447
+ fetchRequestInit.credentials = "include";
1448
+ fetchRequestInit.cache = "no-cache";
1449
+ fetchRequestInit.redirect = "follow";
1450
+ fetchRequestInit.referrerPolicy = "origin-when-cross-origin";
1451
+ fetchRequestInit.signal = signal;
1452
+ Object.assign(fetchRequestInit, details.fetchInit || {});
1453
+ return {
1454
+ fetchDetails: details,
1455
+ fetchRequestInit: fetchRequestInit,
1456
+ abortController: abortController,
1457
+ };
1458
+ },
1459
+ };
1460
+ private HttpxCallBack = {
1461
+ context: this,
1462
+ /**
1463
+ * onabort请求被取消-触发
1464
+ * @param details 配置
1465
+ * @param resolve 回调
1466
+ * @param argumentsList 参数列表
1467
+ */
1468
+ onAbort(
1469
+ details: Required<HttpxDetails>,
1470
+ resolve: (...rags: any[]) => void,
1471
+ argumentsList: any
1472
+ ) {
1473
+ if ("onabort" in details) {
1474
+ details.onabort.apply(this, argumentsList);
1475
+ } else if ("onabort" in this.context.#defaultDetails) {
1476
+ this.context.#defaultDetails!.onabort!.apply(this, argumentsList);
1477
+ }
1478
+ resolve({
1479
+ status: false,
1480
+ data: [...argumentsList],
1481
+ msg: "请求被取消",
1482
+ type: "onabort",
1483
+ });
1484
+ },
1485
+
1486
+ /**
1487
+ * onerror请求异常-触发
1488
+ * @param details 配置
1489
+ * @param resolve 回调
1490
+ * @param argumentsList 响应的参数列表
1491
+ */
1492
+ onError(
1493
+ details: Required<HttpxDetails>,
1494
+ resolve: (...rags: any[]) => void,
1495
+ argumentsList: any
1496
+ ) {
1497
+ if ("onerror" in details) {
1498
+ details.onerror.apply(this, argumentsList);
1499
+ } else if ("onerror" in this.context.#defaultDetails) {
1500
+ this.context.#defaultDetails!.onerror!.apply(this, argumentsList);
1501
+ }
1502
+ let response = argumentsList;
1503
+ if (response.length) {
1504
+ response = response[0];
1505
+ }
1506
+ resolve({
1507
+ status: false,
1508
+ data: response,
1509
+ details: details,
1510
+ msg: "请求异常",
1511
+ type: "onerror",
1512
+ });
1513
+ },
1514
+ /**
1515
+ * ontimeout请求超时-触发
1516
+ * @param details 配置
1517
+ * @param resolve 回调
1518
+ * @param argumentsList 参数列表
1519
+ */
1520
+ onTimeout(
1521
+ details: Required<HttpxDetails>,
1522
+ resolve: (...rags: any[]) => void,
1523
+ argumentsList: any
1524
+ ) {
1525
+ if ("ontimeout" in details) {
1526
+ details.ontimeout.apply(this, argumentsList);
1527
+ } else if ("ontimeout" in this.context.#defaultDetails) {
1528
+ this.context.#defaultDetails!.ontimeout!.apply(this, argumentsList);
1529
+ }
1530
+ resolve({
1531
+ status: false,
1532
+ data: [...argumentsList],
1533
+ msg: "请求超时",
1534
+ type: "ontimeout",
1535
+ });
1536
+ },
1537
+
1538
+ /**
1539
+ * onloadstart请求开始-触发
1540
+ * @param details 配置
1541
+ * @param argumentsList 参数列表
1542
+ */
1543
+ onLoadStart(details: Required<HttpxDetails>, argumentsList: any) {
1544
+ if ("onloadstart" in details) {
1545
+ details.onloadstart.apply(this, argumentsList);
1546
+ } else if ("onloadstart" in this.context.#defaultDetails) {
1547
+ this.context.#defaultDetails!.onloadstart!.apply(this, argumentsList);
1548
+ }
1549
+ },
1550
+ /**
1551
+ * onload加载完毕-触发
1552
+ * @param details 请求的配置
1553
+ * @param resolve 回调
1554
+ * @param argumentsList 参数列表
1555
+ */
1556
+ onLoad(
1557
+ details: Required<HttpxDetails>,
1558
+ resolve: (...rags: any[]) => void,
1559
+ argumentsList: any
1560
+ ) {
1561
+ /* X浏览器会因为设置了responseType导致不返回responseText */
1562
+ let Response: HttpxAsyncResultData<HttpxDetails> = argumentsList[0];
1563
+ /* responseText为空,response不为空的情况 */
1564
+ if (
1565
+ Utils.isNull(Response["responseText"]) &&
1566
+ Utils.isNotNull(Response["response"])
1567
+ ) {
1568
+ if (typeof Response["response"] === "object") {
1569
+ Utils.tryCatch().run(() => {
1570
+ Response["responseText"] = JSON.stringify(Response["response"]);
1571
+ });
1572
+ } else {
1573
+ Response["responseText"] = Response["response"];
1574
+ }
1575
+ }
1576
+
1577
+ /* response为空,responseText不为空的情况 */
1578
+ if (
1579
+ Response["response"] == null &&
1580
+ typeof Response["responseText"] === "string" &&
1581
+ Response["responseText"].trim() !== ""
1582
+ ) {
1583
+ let newResponse = Response["responseText"];
1584
+ if (details.responseType === "json") {
1585
+ (newResponse as any) = Utils.toJSON(Response["responseText"]);
1586
+ } else if (details.responseType === "document") {
1587
+ let parser = new DOMParser();
1588
+ (newResponse as any) = parser.parseFromString(
1589
+ Response["responseText"],
1590
+ "text/html"
1591
+ );
1592
+ } else if (details.responseType === "arraybuffer") {
1593
+ let encoder = new TextEncoder();
1594
+ let arrayBuffer = encoder.encode(Response["responseText"]);
1595
+ (newResponse as any) = arrayBuffer;
1596
+ } else if (details.responseType === "blob") {
1597
+ let encoder = new TextEncoder();
1598
+ let arrayBuffer = encoder.encode(Response["responseText"]);
1599
+ (newResponse as any) = new Blob([arrayBuffer]);
1600
+ } else {
1601
+ newResponse = Response["responseText"];
1602
+ }
1603
+ try {
1604
+ Response["response"] = newResponse;
1605
+ } catch (error) {
1606
+ console.warn("response 无法被覆盖");
1607
+ }
1608
+ }
1609
+ /* Stay扩展中没有finalUrl,对应的是responseURL */
1610
+ if (
1611
+ Response["finalUrl"] == null &&
1612
+ (Response as any)["responseURL"] != null
1613
+ ) {
1614
+ Response["finalUrl"] = (Response as any)["responseURL"];
1615
+ }
1616
+ /* 状态码2xx都是成功的 */
1617
+ if (Math.floor(Response.status / 100) === 2) {
1618
+ resolve({
1619
+ status: true,
1620
+ data: Response,
1621
+ details: details,
1622
+ msg: "请求完毕",
1623
+ type: "onload",
1624
+ });
1625
+ } else {
1626
+ this.context.HttpxCallBack.onError(details, resolve, argumentsList);
1627
+ }
1628
+ },
1629
+ /**
1630
+ * onprogress上传进度-触发
1631
+ * @param details 配置
1632
+ * @param argumentsList 参数列表
1633
+ */
1634
+ onProgress(details: Required<HttpxDetails>, argumentsList: any) {
1635
+ if ("onprogress" in details) {
1636
+ details.onprogress.apply(this, argumentsList);
1637
+ } else if ("onprogress" in this.context.#defaultDetails) {
1638
+ this.context.#defaultDetails!.onprogress!.apply(this, argumentsList);
1639
+ }
1640
+ },
1641
+ /**
1642
+ * onreadystatechange准备状态改变-触发
1643
+ * @param details 配置
1644
+ * @param argumentsList 参数列表
1645
+ */
1646
+ onReadyStateChange(details: Required<HttpxDetails>, argumentsList: any) {
1647
+ if ("onreadystatechange" in details) {
1648
+ details.onreadystatechange.apply(this, argumentsList);
1649
+ } else if ("onreadystatechange" in this.context.#defaultDetails) {
1650
+ this.context.#defaultDetails!.onreadystatechange!.apply(
1651
+ this,
1652
+ argumentsList
1653
+ );
1654
+ }
1655
+ },
1656
+ };
1657
+ private HttpxRequest = {
1658
+ context: this,
1659
+ /**
1660
+ * 发送请求
1661
+ * @param details
1662
+ */
1663
+ request(details: Required<HttpxDetails>) {
1664
+ if (this.context.#LOG_DETAILS) {
1665
+ console.log("Httpx请求配置👇", details);
1666
+ }
1667
+ if (
1668
+ typeof this.context.HttpxRequestHook.beforeRequestCallBack ===
1669
+ "function"
1670
+ ) {
1671
+ let hookResult =
1672
+ this.context.HttpxRequestHook.beforeRequestCallBack(details);
1673
+ if (typeof hookResult === "boolean" && !hookResult) {
1674
+ return;
1675
+ }
1676
+ }
1677
+ if (details.fetch) {
1678
+ const { fetchDetails, fetchRequestInit, abortController } =
1679
+ this.context.HttpxRequestDetails.handleFetchDetail(details);
1680
+ this.fetch(fetchDetails, fetchRequestInit, abortController);
1681
+ } else {
1682
+ Reflect.deleteProperty(details, "fetchInit");
1683
+ this.xmlHttpRequest(details);
1684
+ }
1685
+ },
1686
+ /**
1687
+ * 使用油猴函数GM_xmlhttpRequest发送请求
1688
+ * @param details
1689
+ */
1690
+ xmlHttpRequest(details: Required<HttpxDetails>) {
1691
+ this.context.GM_Api.xmlHttpRequest(details);
1692
+ },
1693
+ /**
1694
+ * 使用fetch发送请求
1695
+ * @param details
1696
+ * @param fetchRequestInit
1697
+ * @param abortController
1698
+ */
1699
+ fetch(
1700
+ details: Required<HttpxDetails>,
1701
+ fetchRequestInit: RequestInit,
1702
+ abortController: AbortController
1703
+ ) {
1704
+ fetch(details.url, fetchRequestInit)
1705
+ .then(async (resp) => {
1706
+ /**
1707
+ * @type {HttpxAsyncResultData}
1708
+ */
1709
+ let httpxResponse = {
1710
+ isFetch: true,
1711
+ finalUrl: resp.url,
1712
+ readyState: 4,
1713
+ status: resp.status,
1714
+ statusText: resp.statusText,
1715
+ response: void 0,
1716
+ responseFetchHeaders: resp.headers,
1717
+ responseHeaders: "",
1718
+ responseText: void 0,
1719
+ responseType: details.responseType,
1720
+ responseXML: void 0,
1721
+ };
1722
+ Object.assign(httpxResponse, details.context || {});
1723
+
1724
+ for (const [key, value] of (resp.headers as any).entries()) {
1725
+ httpxResponse.responseHeaders += `${key}: ${value}\n`;
1726
+ }
1727
+
1728
+ /* 如果是流式传输,直接返回 */
1729
+ if (
1730
+ details.responseType === "stream" ||
1731
+ (resp.headers.has("Content-Type") &&
1732
+ resp.headers.get("Content-Type")!.includes("text/event-stream"))
1733
+ ) {
1734
+ (httpxResponse as any)["isStream"] = true;
1735
+ (httpxResponse as any).response = resp.body;
1736
+ Reflect.deleteProperty(httpxResponse, "responseText");
1737
+ Reflect.deleteProperty(httpxResponse, "responseXML");
1738
+ details.onload(httpxResponse);
1739
+ return;
1740
+ }
1741
+
1742
+ /** 响应 */
1743
+ let response = "";
1744
+ /** 响应字符串 */
1745
+ let responseText = "";
1746
+ /** 响应xml文档 */
1747
+ let responseXML = "";
1748
+
1749
+ let arrayBuffer = await resp.arrayBuffer;
1750
+
1751
+ let encoding = "utf-8";
1752
+ if (resp.headers.has("Content-Type")) {
1753
+ let charsetMatched = resp.headers
1754
+ .get("Content-Type")
1755
+ ?.match(/charset=(.+)/);
1756
+ if (charsetMatched) {
1757
+ encoding = charsetMatched[1];
1758
+ }
1759
+ }
1760
+ let textDecoder = new TextDecoder(encoding);
1761
+ responseText = textDecoder.decode(await resp.arrayBuffer());
1762
+ response = responseText;
1763
+
1764
+ if (details.responseType === "arraybuffer") {
1765
+ (response as any) = arrayBuffer;
1766
+ } else if (details.responseType === "blob") {
1767
+ (response as any) = new Blob([arrayBuffer as any]);
1768
+ } else if (
1769
+ details.responseType === "document" ||
1770
+ details.responseType == null
1771
+ ) {
1772
+ let parser = new DOMParser();
1773
+ (response as any) = parser.parseFromString(
1774
+ responseText,
1775
+ "text/html"
1776
+ );
1777
+ } else if (details.responseType === "json") {
1778
+ (response as any) = Utils.toJSON(responseText);
1779
+ }
1780
+ let parser = new DOMParser();
1781
+ (responseXML as any) = parser.parseFromString(
1782
+ responseText,
1783
+ "text/xml"
1784
+ );
1785
+
1786
+ (httpxResponse as any).response = response;
1787
+ (httpxResponse as any).responseText = responseText;
1788
+ (httpxResponse as any).responseXML = responseXML;
1789
+
1790
+ details.onload(httpxResponse);
1791
+ })
1792
+ .catch((err) => {
1793
+ if (err.name === "AbortError") {
1794
+ return;
1795
+ }
1796
+ details.onerror({
1797
+ isFetch: true,
1798
+ finalUrl: details.url,
1799
+ readyState: 4,
1800
+ status: 0,
1801
+ statusText: "",
1802
+ responseHeaders: "",
1803
+ responseText: "",
1804
+ error: err,
1805
+ });
1806
+ });
1807
+ details.onloadstart({
1808
+ isFetch: true,
1809
+ finalUrl: details.url,
1810
+ readyState: 1,
1811
+ responseHeaders: "",
1812
+ responseText: "",
1813
+ status: 0,
1814
+ statusText: "",
1815
+ });
1816
+ return {
1817
+ abort() {
1818
+ abortController.abort();
1819
+ },
1820
+ };
1821
+ },
1822
+ };
1823
+ /**
1824
+ * 默认配置
1825
+ */
1826
+ #defaultDetails = <HttpxDetails>{
1827
+ url: void 0,
1828
+ timeout: 5000,
1829
+ async: false,
1830
+ responseType: void 0,
1831
+ headers: void 0,
1832
+ data: void 0,
1833
+ redirect: void 0,
1834
+ cookie: void 0,
1835
+ binary: void 0,
1836
+ nocache: void 0,
1837
+ revalidate: void 0,
1838
+ context: void 0,
1839
+ overrideMimeType: void 0,
1840
+ anonymous: void 0,
1841
+ fetch: void 0,
1842
+ fetchInit: void 0,
1843
+ user: void 0,
1844
+ password: void 0,
1845
+ onabort() {},
1846
+ onerror() {},
1847
+ ontimeout() {},
1848
+ onloadstart() {},
1849
+ onreadystatechange() {},
1850
+ onprogress() {},
1851
+ };
1852
+ /**
1853
+ * 当前使用请求时,输出请求的配置
1854
+ */
1855
+ #LOG_DETAILS = false;
1856
+ constructor(__xmlHttpRequest__?: any) {
1857
+ let that = this;
1858
+ if (typeof __xmlHttpRequest__ !== "function") {
1859
+ console.warn(
1860
+ "Httpx未传入GM_xmlhttpRequest函数或传入的GM_xmlhttpRequest不是Function,强制使用window.fetch"
1861
+ );
1862
+ }
1863
+ this.GM_Api.xmlHttpRequest = __xmlHttpRequest__;
1864
+ }
1865
+
1866
+ /**
1867
+ * 覆盖全局配置
1868
+ * @param details 配置
1869
+ */
1870
+ config(details?: {
1871
+ [K in keyof HttpxDetailsConfig]?: HttpxDetailsConfig[K];
1872
+ }): void;
1873
+ /**
1874
+ * 覆盖当前配置
1875
+ * @param details
1876
+ */
1877
+ config(details = <HttpxDetailsConfig>{}) {
1878
+ if ("logDetails" in details && typeof details["logDetails"] === "boolean") {
1879
+ this.#LOG_DETAILS = details["logDetails"];
1880
+ }
1881
+ this.#defaultDetails = Utils.assign(this.#defaultDetails, details);
1882
+ }
1883
+ /**
1884
+ * 修改xmlHttpRequest
1885
+ * @param httpRequest 网络请求函数
1886
+ */
1887
+ setXMLHttpRequest(httpRequest: any) {
1888
+ this.GM_Api.xmlHttpRequest = httpRequest;
1889
+ }
1207
1890
  /**
1208
1891
  * GET 请求
1209
1892
  * @param details 配置
1210
1893
  */
1211
- get<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
1894
+ async get<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
1212
1895
  /**
1213
1896
  * GET 请求
1214
1897
  * @param url 网址
1215
1898
  * @param details 配置
1216
1899
  */
1217
- get<T extends HttpxDetails>(
1900
+ async get<T extends HttpxDetails>(
1218
1901
  url: string,
1219
1902
  details: T
1220
1903
  ): Promise<HttpxAsyncResult<T>>;
1904
+ /**
1905
+ * GET 请求
1906
+ */
1907
+ async get(
1908
+ ...args: (HttpxDetails | string)[]
1909
+ ): Promise<HttpxAsyncResult<HttpxDetails>> {
1910
+ let that = this;
1911
+ let details = this.HttpxRequestDetails.handleBeforeRequestDetails(...args);
1912
+
1913
+ return new Promise((resolve) => {
1914
+ let requestDetails = that.HttpxRequestDetails.getDetails(
1915
+ "get" as any,
1916
+ resolve,
1917
+ details
1918
+ );
1919
+ Reflect.deleteProperty(requestDetails, "onprogress");
1920
+ (requestDetails as any) = that.HttpxRequestDetails.handle(requestDetails);
1921
+ that.HttpxRequest.request(requestDetails);
1922
+ });
1923
+ }
1221
1924
  /**
1222
1925
  * POST 请求
1223
1926
  * @param details 配置
1224
1927
  */
1225
- post<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
1928
+ async post<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
1226
1929
  /**
1227
1930
  * POST 请求
1228
1931
  * @param url 网址
1229
1932
  * @param details 配置
1230
1933
  */
1231
- post<T extends HttpxDetails>(
1934
+ async post<T extends HttpxDetails>(
1232
1935
  url: string,
1233
1936
  details: T
1234
1937
  ): Promise<HttpxAsyncResult<T>>;
1938
+ /**
1939
+ * POST 请求
1940
+ */
1941
+ async post(
1942
+ ...args: (HttpxDetails | string)[]
1943
+ ): Promise<HttpxAsyncResult<HttpxDetails>> {
1944
+ let that = this;
1945
+ let details = this.HttpxRequestDetails.handleBeforeRequestDetails(...args);
1946
+
1947
+ return new Promise((resolve) => {
1948
+ let requestDetails = that.HttpxRequestDetails.getDetails(
1949
+ "post" as any,
1950
+ resolve,
1951
+ details
1952
+ );
1953
+ (requestDetails as any) = that.HttpxRequestDetails.handle(requestDetails);
1954
+ that.HttpxRequest.request(requestDetails);
1955
+ });
1956
+ }
1235
1957
  /**
1236
1958
  * HEAD 请求
1237
1959
  * @param details 配置
1238
1960
  */
1239
- head<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
1961
+ async head<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
1240
1962
  /**
1241
1963
  * HEAD 请求
1242
1964
  * @param url 网址
1243
1965
  * @param details 配置
1244
1966
  */
1245
- head<T extends HttpxDetails>(
1967
+ async head<T extends HttpxDetails>(
1246
1968
  url: string,
1247
1969
  details: T
1248
1970
  ): Promise<HttpxAsyncResult<T>>;
1971
+ /**
1972
+ * HEAD 请求
1973
+ */
1974
+ async head(
1975
+ ...args: (HttpxDetails | string)[]
1976
+ ): Promise<HttpxAsyncResult<HttpxDetails>> {
1977
+ let that = this;
1978
+ let details = this.HttpxRequestDetails.handleBeforeRequestDetails(...args);
1979
+
1980
+ return new Promise((resolve) => {
1981
+ let requestDetails = that.HttpxRequestDetails.getDetails(
1982
+ "head" as any,
1983
+ resolve,
1984
+ details
1985
+ );
1986
+ Reflect.deleteProperty(requestDetails, "onprogress");
1987
+ (requestDetails as any) = that.HttpxRequestDetails.handle(requestDetails);
1988
+ that.HttpxRequest.request(requestDetails);
1989
+ });
1990
+ }
1991
+
1249
1992
  /**
1250
1993
  * OPTIONS 请求
1251
1994
  * @param details 配置
@@ -1260,49 +2003,97 @@ declare interface UtilsHttpxConstrustor {
1260
2003
  url: string,
1261
2004
  details: T
1262
2005
  ): Promise<HttpxAsyncResult<T>>;
2006
+ /**
2007
+ * OPTIONS 请求
2008
+ */
2009
+ async options(
2010
+ ...args: (HttpxDetails | string)[]
2011
+ ): Promise<HttpxAsyncResult<HttpxDetails>> {
2012
+ let that = this;
2013
+ let details = this.HttpxRequestDetails.handleBeforeRequestDetails(...args);
2014
+
2015
+ return new Promise((resolve) => {
2016
+ let requestDetails = that.HttpxRequestDetails.getDetails(
2017
+ "options" as any,
2018
+ resolve,
2019
+ details
2020
+ );
2021
+ Reflect.deleteProperty(requestDetails, "onprogress");
2022
+ (requestDetails as any) = that.HttpxRequestDetails.handle(requestDetails);
2023
+ that.HttpxRequest.request(requestDetails);
2024
+ });
2025
+ }
2026
+
1263
2027
  /**
1264
2028
  * DELETE 请求
1265
2029
  * @param details 配置
1266
2030
  */
1267
- delete<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
2031
+ async delete<T extends HttpxDetails>(
2032
+ details: T
2033
+ ): Promise<HttpxAsyncResult<T>>;
1268
2034
  /**
1269
2035
  * DELETE 请求
1270
2036
  * @param url 网址
1271
2037
  * @param details 配置
1272
2038
  */
1273
- delete<T extends HttpxDetails>(
2039
+ async delete<T extends HttpxDetails>(
1274
2040
  url: string,
1275
2041
  details: T
1276
2042
  ): Promise<HttpxAsyncResult<T>>;
2043
+ /**
2044
+ * DELETE 请求
2045
+ */
2046
+ async delete(
2047
+ ...args: (HttpxDetails | string)[]
2048
+ ): Promise<HttpxAsyncResult<HttpxDetails>> {
2049
+ let that = this;
2050
+ let details = this.HttpxRequestDetails.handleBeforeRequestDetails(...args);
2051
+
2052
+ return new Promise((resolve) => {
2053
+ let requestDetails = that.HttpxRequestDetails.getDetails(
2054
+ "delete" as any,
2055
+ resolve,
2056
+ details
2057
+ );
2058
+ Reflect.deleteProperty(requestDetails, "onprogress");
2059
+ (requestDetails as any) = that.HttpxRequestDetails.handle(requestDetails);
2060
+ that.HttpxRequest.request(requestDetails);
2061
+ });
2062
+ }
2063
+
1277
2064
  /**
1278
2065
  * PUT 请求
1279
2066
  * @param details 配置
1280
2067
  */
1281
- put<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
2068
+ async put<T extends HttpxDetails>(details: T): Promise<HttpxAsyncResult<T>>;
1282
2069
  /**
1283
2070
  * PUT 请求
1284
2071
  * @param url 网址
1285
2072
  * @param details 配置
1286
2073
  */
1287
- put<T extends HttpxDetails>(
2074
+ async put<T extends HttpxDetails>(
1288
2075
  url: string,
1289
2076
  details: T
1290
2077
  ): Promise<HttpxAsyncResult<T>>;
1291
2078
  /**
1292
- * 覆盖全局配置
1293
- * @param details 配置
1294
- */
1295
- config(details?: {
1296
- [K in keyof HttpxDetailsConfig]?: HttpxDetailsConfig[K];
1297
- }): void;
1298
- /**
1299
- * 修改xmlHttpRequest
1300
- * @param httpRequest 网络请求函数
2079
+ * PUT 请求
1301
2080
  */
1302
- setXMLHttpRequest(httpRequest: Function): void;
1303
- }
2081
+ async put(
2082
+ ...args: (HttpxDetails | string)[]
2083
+ ): Promise<HttpxAsyncResult<HttpxDetails>> {
2084
+ let that = this;
2085
+ let details = this.HttpxRequestDetails.handleBeforeRequestDetails(...args);
1304
2086
 
1305
- /** Httpx */
1306
- declare interface UtilsHttpx {
1307
- new (xmlHttpRequest: Function): UtilsHttpxConstrustor;
2087
+ return new Promise((resolve) => {
2088
+ let requestDetails = that.HttpxRequestDetails.getDetails(
2089
+ "put" as any,
2090
+ resolve,
2091
+ details
2092
+ );
2093
+ (requestDetails as any) = that.HttpxRequestDetails.handle(requestDetails);
2094
+ that.HttpxRequest.request(requestDetails);
2095
+ });
2096
+ }
1308
2097
  }
2098
+
2099
+ export { Httpx };