-
Notifications
You must be signed in to change notification settings - Fork 742
Expand file tree
/
Copy pathdev_build_cache.ts
More file actions
306 lines (264 loc) · 8.32 KB
/
dev_build_cache.ts
File metadata and controls
306 lines (264 loc) · 8.32 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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import type { BuildCache, StaticFile } from "../build_cache.ts";
import * as path from "@std/path";
import { SEPARATOR as WINDOWS_SEPARATOR } from "@std/path/windows/constants";
import { getSnapshotPath, type ResolvedFreshConfig } from "../config.ts";
import type { BuildSnapshot } from "../build_cache.ts";
import { encodeHex } from "@std/encoding/hex";
import { crypto } from "@std/crypto";
import type { FreshFileTransformer } from "./file_transformer.ts";
import { assertInDir } from "../utils.ts";
import { ensureDir } from "@std/fs/ensure-dir";
import { walk } from "@std/fs/walk";
export interface MemoryFile {
hash: string | null;
content: Uint8Array;
}
export interface DevBuildCache extends BuildCache {
islands: Map<string, string>;
addUnprocessedFile(pathname: string): void;
addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
): Promise<void>;
flush(): Promise<void>;
}
export class MemoryBuildCache implements DevBuildCache {
hasSnapshot = true;
islands = new Map<string, string>();
#processedFiles = new Map<string, MemoryFile>();
#unprocessedFiles = new Map<string, string>();
#ready = Promise.withResolvers<void>();
constructor(
public config: ResolvedFreshConfig,
public buildId: string,
public transformer: FreshFileTransformer,
public target: string | string[],
) {
}
async readFile(pathname: string): Promise<StaticFile | null> {
await this.#ready.promise;
const processed = this.#processedFiles.get(pathname);
if (processed !== undefined) {
return {
hash: processed.hash,
readable: processed.content,
size: processed.content.byteLength,
close: () => {},
};
}
const unprocessed = this.#unprocessedFiles.get(pathname);
if (unprocessed !== undefined) {
try {
const [stat, file] = await Promise.all([
Deno.stat(unprocessed),
Deno.open(unprocessed, { read: true }),
]);
return {
hash: null,
size: stat.size,
readable: file.readable,
close: () => file.close(),
};
} catch (_err) {
return null;
}
}
let entry = pathname.startsWith("/") ? pathname.slice(1) : pathname;
entry = path.join(this.config.staticDir, entry);
const relative = path.relative(this.config.staticDir, entry);
if (relative.startsWith("..")) {
throw new Error(
`Processed file resolved outside of static dir ${entry}`,
);
}
// Might be a file that we still need to process
const transformed = await this.transformer.process(
entry,
"development",
this.target,
);
if (transformed !== null) {
for (let i = 0; i < transformed.length; i++) {
const file = transformed[i];
const relative = path.relative(this.config.staticDir, file.path);
if (relative.startsWith(".")) {
throw new Error(
`Processed file resolved outside of static dir ${file.path}`,
);
}
const pathname = `/${relative}`;
this.addProcessedFile(pathname, file.content, null);
}
if (this.#processedFiles.has(pathname)) {
return this.readFile(pathname);
}
} else {
try {
const filePath = path.join(this.config.staticDir, pathname);
const relative = path.relative(this.config.staticDir, filePath);
if (!relative.startsWith(".") && (await Deno.stat(filePath)).isFile) {
this.addUnprocessedFile(pathname);
return this.readFile(pathname);
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
return null;
}
getIslandChunkName(islandName: string): string | null {
return this.islands.get(islandName) ?? null;
}
addUnprocessedFile(pathname: string): void {
this.#unprocessedFiles.set(
pathname,
path.join(this.config.staticDir, pathname),
);
}
// deno-lint-ignore require-await
async addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
): Promise<void> {
this.#processedFiles.set(pathname, { content, hash });
}
// deno-lint-ignore require-await
async flush(): Promise<void> {
this.#ready.resolve();
}
}
// await fsAdapter.mkdirp(staticOutDir);
export class DiskBuildCache implements DevBuildCache {
hasSnapshot = true;
islands = new Map<string, string>();
#processedFiles = new Map<string, string | null>();
#unprocessedFiles = new Map<string, string>();
#transformer: FreshFileTransformer;
#target: string | string[];
constructor(
public config: ResolvedFreshConfig,
public buildId: string,
transformer: FreshFileTransformer,
target: string | string[],
) {
this.#transformer = transformer;
this.#target = target;
}
getIslandChunkName(islandName: string): string | null {
return this.islands.get(islandName) ?? null;
}
addUnprocessedFile(pathname: string): void {
this.#unprocessedFiles.set(
pathname.replaceAll(WINDOWS_SEPARATOR, "/"),
path.join(this.config.staticDir, pathname),
);
}
async addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
) {
this.#processedFiles.set(pathname, hash);
const outDir = pathname === "/metafile.json"
? this.config.build.outDir
: path.join(this.config.build.outDir, "static");
const filePath = path.join(outDir, pathname);
assertInDir(filePath, outDir);
await ensureDir(path.dirname(filePath));
await Deno.writeFile(filePath, content);
}
// deno-lint-ignore require-await
async readFile(_pathname: string): Promise<StaticFile | null> {
throw new Error("Not implemented in build mode");
}
async flush(): Promise<void> {
const staticDir = this.config.staticDir;
const outDir = this.config.build.outDir;
try {
const entries = walk(staticDir, {
includeDirs: false,
includeFiles: true,
followSymlinks: false,
// Skip any folder or file starting with a "."
skip: [/\/\.[^/]+(\/|$)/],
});
for await (const entry of entries) {
// OutDir might be inside static dir
if (!path.relative(outDir, entry.path).startsWith("..")) {
continue;
}
const result = await this.#transformer.process(
entry.path,
"production",
this.#target,
);
if (result !== null) {
for (let i = 0; i < result.length; i++) {
const file = result[i];
assertInDir(file.path, staticDir);
const pathname = `/${path.relative(staticDir, file.path)}`;
await this.addProcessedFile(pathname, file.content, null);
}
} else {
const relative = path.relative(staticDir, entry.path);
const pathname = `/${relative}`;
this.addUnprocessedFile(pathname);
}
}
} catch (error) {
if (!(error instanceof Deno.errors.NotFound)) {
throw error;
}
}
const snapshot: BuildSnapshot = {
version: 1,
buildId: this.buildId,
islands: {},
staticFiles: {},
};
for (const [name, chunk] of this.islands.entries()) {
snapshot.islands[name] = chunk;
}
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
const file = await Deno.open(filePath);
const hash = await hashContent(file.readable);
snapshot.staticFiles[name] = {
hash,
generated: false,
};
}
for (const [name, maybeHash] of this.#processedFiles.entries()) {
let hash = maybeHash;
// Ignore esbuild meta file. It's not intended for serving
if (name === "/metafile.json") {
continue;
}
if (maybeHash === null) {
const filePath = path.join(this.config.build.outDir, "static", name);
const file = await Deno.open(filePath);
hash = await hashContent(file.readable);
}
snapshot.staticFiles[name] = {
hash,
generated: true,
};
}
await Deno.writeTextFile(
getSnapshotPath(this.config),
JSON.stringify(snapshot, null, 2),
);
}
}
async function hashContent(
content: Uint8Array | ReadableStream<Uint8Array>,
): Promise<string> {
const hashBuf = await crypto.subtle.digest(
"SHA-256",
content,
);
return encodeHex(hashBuf);
}