-
Notifications
You must be signed in to change notification settings - Fork 36
/
loader.ts
73 lines (68 loc) · 1.99 KB
/
loader.ts
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
import type { LoadResponse } from "./types.d.ts";
const hasPermissions = "permissions" in Deno;
let readRequested = false;
const netRequested = new Set<string>();
async function requestRead(path: URL): Promise<void> {
if (readRequested || !hasPermissions) {
return;
}
readRequested = true;
await Deno.permissions.request({ name: "read", path });
}
async function requestNet(host: string): Promise<void> {
if (!hasPermissions || netRequested.has(host)) {
return;
}
netRequested.add(host);
await Deno.permissions.request({ name: "net", host });
}
/** A Deno specific loader function that can be passed to the
* `createModuleGraph` which will use `Deno.readTextFile` for local files, or
* use `fetch()` for remote modules.
*
* @param specifier The string module specifier from the module graph.
*/
export async function load(
specifier: string,
): Promise<LoadResponse | undefined> {
const url = new URL(specifier);
try {
switch (url.protocol) {
case "file:": {
await requestRead(url);
const content = await Deno.readTextFile(url);
return {
kind: "module",
specifier,
content,
};
}
case "http:":
case "https:": {
await requestNet(url.host);
const response = await fetch(String(url), { redirect: "follow" });
if (response.status !== 200) {
// ensure the body is read as to not leak resources
await response.arrayBuffer();
return undefined;
}
const content = await response.text();
const headers: Record<string, string> = {};
for (const [key, value] of response.headers) {
headers[key.toLowerCase()] = value;
}
return {
kind: "module",
specifier: response.url,
headers,
content,
};
}
default:
return undefined;
}
} catch {
return undefined;
}
}