forked from magicoflolis/Userscript-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwork.js
More file actions
73 lines (71 loc) 路 2.43 KB
/
Copy pathnetwork.js
File metadata and controls
73 lines (71 loc) 路 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
import { isEmpty, isFN } from './util.js';
/**
* @type { import("../typings/UserJS.d.ts").Network }
*/
const Network = {
async req(url, method = 'GET', responseType = 'json', data = {}) {
if (isEmpty(url)) {
throw new Error('"url" parameter is empty');
}
method = Network.bscStr(method, false);
responseType = Network.bscStr(responseType);
const params = {
method,
...data
};
return await new Promise((resolve, reject) => {
/**
* @param { Response } response
* @returns { Response | Document }
*/
const fetchResp = (response_1) => {
if (!response_1.ok) reject(response_1);
const check = (str_2 = 'text') => {
return isFN(response_1[str_2]) ? response_1[str_2]() : response_1;
};
if (responseType.match(/buffer/i)) {
resolve(check('arrayBuffer'));
} else if (responseType.match(/json/i)) {
resolve(check('json'));
} else if (responseType.match(/text/i)) {
resolve(check('text'));
} else if (responseType.match(/blob/i)) {
resolve(check('blob'));
} else if (responseType.match(/formdata/i)) {
resolve(check('formData'));
} else if (responseType.match(/clone/i)) {
resolve(check('clone'));
} else if (responseType.match(/document/i) && isFN(response_1.text)) {
const domParser = new DOMParser();
const respTxt = response_1.text();
if (respTxt instanceof Promise) {
respTxt.then((txt) => {
const doc = domParser.parseFromString(txt, 'text/html');
resolve(doc);
});
} else {
const doc = domParser.parseFromString(respTxt, 'text/html');
resolve(doc);
}
} else {
resolve(response_1);
}
};
fetch(url, params).then(fetchResp).catch(reject);
});
},
format(bytes, decimals = 2) {
if (Number.isNaN(bytes)) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${Network.sizes[i]}`;
},
sizes: ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
bscStr(str = '', lowerCase = true) {
const txt = str[lowerCase ? 'toLowerCase' : 'toUpperCase']();
return txt.replaceAll(/\W/g, '');
}
};
export default Network;