|
1 |
| -function getFetch() { |
2 |
| - if (typeof window != "undefined" && window.fetch) return window.fetch; |
3 |
| - else return eval("require")("node-fetch"); |
| 1 | +function isHostTrusted(url, trustedHosts) { |
| 2 | + // TODO: |
| 3 | + return false; |
| 4 | +} |
| 5 | +function isHttpURL(uri) { |
| 6 | + return !!uri.match(/^https?\:\/\//); |
4 | 7 | }
|
5 | 8 |
|
6 |
| -async function defaultImportReader(moduleName, importPaths = []) { |
7 |
| - const fetch = getFetch(); |
| 9 | +async function defaultImportReader( |
| 10 | + moduleName, |
| 11 | + importPaths = [], |
| 12 | + requestOptions = {} |
| 13 | +) { |
| 14 | + const { |
| 15 | + allowHttp = false, |
| 16 | + trustedHosts = [], |
| 17 | + requestTimeout = 2000 |
| 18 | + } = requestOptions; |
8 | 19 |
|
9 | 20 | if (typeof importPaths === "string") importPaths = [importPaths];
|
10 | 21 |
|
11 | 22 | for (dir of importPaths) {
|
12 |
| - const filepath = dir + "/" + moduleName + ".wy"; |
13 |
| - if (filepath.match(/^\w+\:\/\//)) { |
| 23 | + const uri = dir + "/" + moduleName + ".wy"; |
| 24 | + if (isHttpURL(uri)) { |
| 25 | + if (!allowHttp && !isHostTrusted(uri, trustedHosts)) { |
| 26 | + throw new Error( |
| 27 | + `URL request "${uri}" is blocked by default for security purpose.` + |
| 28 | + `You can turn it on by specify the "allowHttp" option.` |
| 29 | + ); |
| 30 | + } |
| 31 | + |
14 | 32 | try {
|
15 |
| - const data = await fetch(filepath); |
16 |
| - const text = await data.text(); |
17 |
| - return text; |
| 33 | + const res = await axios(uri, { |
| 34 | + responseType: "text", |
| 35 | + timeout: requestTimeout |
| 36 | + }); |
| 37 | + return res.data; |
18 | 38 | } catch (e) {}
|
19 | 39 | } else {
|
20 | 40 | try {
|
21 |
| - return eval("require")("fs").readFileSync(filepath, "utf-8"); |
| 41 | + return await eval("require")("fs").promises.readFile(uri, "utf-8"); |
22 | 42 | } catch (e) {}
|
23 | 43 | }
|
24 | 44 | }
|
|
0 commit comments