forked from denoland/wasmbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.ts
139 lines (126 loc) · 3.55 KB
/
cache.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
import { default as localDataDir } from "https://deno.land/x/[email protected]/data_local_dir/mod.ts";
export async function cacheToLocalDir(
url: URL,
decompress: (bytes: Uint8Array) => Uint8Array,
) {
const localPath = await getUrlLocalPath(url);
if (localPath == null) {
return undefined;
}
if (!await exists(localPath)) {
const fileBytes = decompress(new Uint8Array(await getUrlBytes(url)));
try {
await Deno.writeFile(localPath, fileBytes);
} catch {
// ignore and return the wasm bytes
return fileBytes;
}
}
return toFileUrl(localPath);
}
async function getUrlLocalPath(url: URL) {
try {
const dataDirPath = await getInitializedLocalDataDirPath();
const hash = await getUrlHash(url);
return `${dataDirPath}/${hash}.wasm`;
} catch {
return undefined;
}
}
async function getInitializedLocalDataDirPath() {
const dataDir = localDataDir();
if (dataDir == null) {
throw new Error(`Could not find local data directory.`);
}
const dirPath = `${dataDir}/deno-wasmbuild`;
await ensureDir(dirPath);
return dirPath;
}
async function exists(filePath: string | URL): Promise<boolean> {
try {
await Deno.lstat(filePath);
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false;
}
throw error;
}
}
async function ensureDir(dir: string) {
try {
const fileInfo = await Deno.lstat(dir);
if (!fileInfo.isDirectory) {
throw new Error(`Path was not a directory '${dir}'`);
}
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
// if dir not exists. then create it.
await Deno.mkdir(dir, { recursive: true });
return;
}
throw err;
}
}
async function getUrlHash(url: URL) {
// Taken from MDN: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
const hashBuffer = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(url.href),
);
// convert buffer to byte array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return hashHex;
}
async function getUrlBytes(url: URL) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Error downloading ${url}: ${response.statusText}`);
}
return await response.arrayBuffer();
}
// the below is extracted from deno_std/path
const WHITESPACE_ENCODINGS: Record<string, string> = {
"\u0009": "%09",
"\u000A": "%0A",
"\u000B": "%0B",
"\u000C": "%0C",
"\u000D": "%0D",
"\u0020": "%20",
};
function encodeWhitespace(string: string): string {
return string.replaceAll(/[\s]/g, (c) => {
return WHITESPACE_ENCODINGS[c] ?? c;
});
}
function toFileUrl(path: string): URL {
return Deno.build.os === "windows"
? windowsToFileUrl(path)
: posixToFileUrl(path);
}
function posixToFileUrl(path: string): URL {
const url = new URL("file:///");
url.pathname = encodeWhitespace(
path.replace(/%/g, "%25").replace(/\\/g, "%5C"),
);
return url;
}
function windowsToFileUrl(path: string): URL {
const [, hostname, pathname] = path.match(
/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/,
)!;
const url = new URL("file:///");
url.pathname = encodeWhitespace(pathname.replace(/%/g, "%25"));
if (hostname != null && hostname != "localhost") {
url.hostname = hostname;
if (!url.hostname) {
throw new TypeError("Invalid hostname.");
}
}
return url;
}