forked from denoland/fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_snapshot.ts
More file actions
546 lines (474 loc) · 16.2 KB
/
server_snapshot.ts
File metadata and controls
546 lines (474 loc) · 16.2 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import type {
EnvironmentModuleNode,
Manifest,
Plugin,
ViteDevServer,
} from "vite";
import {
crawlFsItem,
fsAdapter,
type FsRouteFileNoMod,
generateSnapshotServer,
type IslandModChunk,
pathToSpec,
type PendingStaticFile,
specToName,
UniqueNamer,
} from "fresh/internal-dev";
import {
JS_REG,
pathWithRoot,
type ResolvedFreshViteConfig,
} from "../utils.ts";
import * as path from "@std/path";
import { getBuildId } from "./build_id.ts";
export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
const modName = "fresh:server-snapshot";
let isDev = false;
let server: ViteDevServer | undefined;
let clientOutDir = "";
let serverOutDir = "";
let root = "";
let publicDir = "";
const islands = new Map<string, { name: string; chunk: string | null }>();
const islandsByFile = new Set<string>();
const islandSpecByName = new Map<string, string>();
const routeNamer = new UniqueNamer();
const routeFileToName = new Map<string, string>();
// deno-lint-ignore no-explicit-any
const routes: Map<string, FsRouteFileNoMod<any>> = new Map();
return [
{
name: "fresh:server-snapshot",
sharedDuringBuild: true,
applyToEnvironment(env) {
return env.config.consumer === "server";
},
config(_, env) {
isDev = env.command === "serve";
},
configResolved(config) {
root = config.root;
publicDir = pathWithRoot(config.publicDir, config.root);
clientOutDir = pathWithRoot(
config.environments.client.build.outDir,
config.root,
);
serverOutDir = pathWithRoot(
config.environments.ssr.build.outDir,
config.root,
);
options.islandSpecifiers.forEach((name, spec) => {
islands.set(spec, { name, chunk: null });
islandSpecByName.set(name, spec);
// islandsByFile.add(spec);
});
},
configureServer(viteServer) {
server = viteServer;
viteServer.watcher.on("all", (ev, filePath) => {
const { client, ssr } = viteServer.environments;
// We can't just check if it's in the client module graph
// because plugins like tailwindcss import _everything_.
// Instead, we walk up the module graph to see if the file
// is imported by an island or the client entry file.
const mods = client.moduleGraph.getModulesByFile(filePath);
if (mods !== undefined) {
const seen = new Set<EnvironmentModuleNode>();
const maybe = Array.from(mods);
for (let i = 0; i < maybe.length; i++) {
const mod = maybe[i];
const isIslandFile = walkUp(
mod,
(m) => m.file !== null && islandsByFile.has(m.file),
seen,
);
// No need to notify manually, vite takes care of this.
if (isIslandFile) return;
}
}
// Check for route files. We need to invalidate the snapshot if
// they are removed or added.
if (
(ev === "add" || ev === "unlink") &&
!/[\\/]+\(_[^)]+\)[\\/]+/.test(filePath)
) {
const relRoutes = path.relative(options.routeDir, filePath);
if (!relRoutes.startsWith("..")) {
const mod = ssr.moduleGraph.getModuleById(`\0${modName}`);
if (mod !== undefined) {
// Clear state
islands.clear();
islandsByFile.clear();
islandSpecByName.clear();
ssr.moduleGraph.invalidateModule(mod);
}
}
}
// Finally, notify the client
viteServer.ws.send("fresh:reload");
});
},
resolveId: {
filter: {
id: /fresh:server-snapshot/,
},
handler(id) {
if (id === modName) {
return `\0${modName}`;
}
},
},
load: {
filter: {
id: /\0fresh:server-snapshot/,
},
async handler() {
const result = await crawlFsItem({
islandDir: options.islandsDir,
routeDir: options.routeDir,
ignore: options.ignore,
});
for (let i = 0; i < result.islands.length; i++) {
const spec = result.islands[i];
const specName = specToName(spec);
const name = options.namer.getUniqueName(specName);
islands.set(spec, { name, chunk: null });
islandSpecByName.set(name, spec);
islandsByFile.add(spec);
}
for (let i = 0; i < result.routes.length; i++) {
const route = result.routes[i];
const name = routeNamer.getUniqueName(route.id);
routeFileToName.set(route.filePath, name);
routes.set(name, route);
}
const staticFiles: PendingStaticFile[] = [];
let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry";
let buildId = "";
const entryAssets: string[] = [];
if (isDev && server !== undefined) {
for (const id of islands.keys()) {
const mod = server.environments.client.moduleGraph.getModuleById(
id,
);
if (mod !== undefined) {
const def = islands.get(id);
if (def !== undefined) def.chunk = mod.url;
}
}
islandMods = Array.from(islands.entries()).map(([id, def]) => {
return {
name: def.name,
server: id,
browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
css: [],
};
});
} else {
buildId = await getBuildId(false);
const manifest = JSON.parse(
await Deno.readTextFile(
path.join(clientOutDir, ".vite", "manifest.json"),
),
) as Manifest;
const resolvedIslandSpecs = new Map<string, string>();
for (const spec of options.islandSpecifiers.keys()) {
const resolved = await this.resolve(spec);
if (resolved === null) continue;
const id = resolved.id.startsWith("\0")
? resolved.id.slice(1)
: resolved.id;
resolvedIslandSpecs.set(id, spec);
}
const clientEntryName = "client-entry";
for (const chunk of Object.values(manifest)) {
if (chunk.name === clientEntryName) {
clientEntry = pathToSpec(clientOutDir, chunk.file);
}
staticFiles.push({
filePath: path.join(clientOutDir, chunk.file),
pathname: chunk.file,
hash: null,
});
if (chunk.css !== undefined) {
for (let i = 0; i < chunk.css.length; i++) {
const id = chunk.css[i];
const pathname = `/${id}`;
staticFiles.push({
filePath: path.join(clientOutDir, id),
hash: null,
pathname,
});
if (chunk.name === clientEntryName) {
entryAssets.push(pathname);
}
}
}
if (chunk.name?.startsWith("fresh-island__")) {
const name = chunk.name.slice("fresh-island__".length);
let serverPath = path.join(root, chunk.src ?? chunk.file);
const idx = chunk.src?.indexOf("deno::") ?? -1;
if (idx > -1 && chunk.src) {
const src = chunk.src
.slice(idx)
.replace(
/(https?):\/([^/])/,
(_m, protocol, rest) => {
return `${protocol}://${rest}`;
},
);
serverPath = resolvedIslandSpecs.get(src)!;
}
let spec = pathToSpec(clientOutDir, chunk.file);
if (spec.startsWith("./")) {
spec = spec.slice(1);
}
const chunkCss = chunk.css?.map((id) => `/${id}`) ?? [];
islandMods.push({
name,
browser: spec,
server: serverPath,
css: chunkCss,
});
}
}
if (await fsAdapter.isDirectory(publicDir)) {
const entries = await fsAdapter.walk(
publicDir,
{
followSymlinks: false,
includeDirs: false,
includeFiles: true,
skip: options.ignore,
},
);
for await (const entry of entries) {
const relative = path.relative(publicDir, entry.path);
const filePath = path.join(clientOutDir, relative);
try {
await Deno.mkdir(path.dirname(filePath), { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
await Deno.copyFile(entry.path, filePath);
staticFiles.push({
filePath,
hash: null,
pathname: relative,
});
if (path.basename(relative) === "index.html") {
const htmlRelative = path.relative(
publicDir,
path.dirname(entry.path),
);
staticFiles.push({
filePath,
hash: null,
pathname: htmlRelative,
});
}
}
}
}
const code = await generateSnapshotServer({
outDir: path.join(clientOutDir, ".."),
staticFiles,
buildId,
clientEntry,
entryAssets,
fsRoutesFiles: result.routes,
islands: islandMods,
writeSpecifier: (file) => {
const def = islands.get(file);
if (def) {
return `fresh-island::${def.name}`;
}
const routeDef = routeFileToName.get(file);
if (routeDef !== undefined) {
return `fresh-route::${routeDef}`;
}
return path.toFileUrl(file).href;
},
});
return code;
},
},
transform: {
filter: {
id: /\.(css|less|sass|scss)(\?.*)?$/,
},
handler(_code, id) {
if (server) {
const ssrGraph = server.environments.ssr.moduleGraph;
const mod = ssrGraph.getModuleById(id);
if (mod === undefined) return;
const snapshot = ssrGraph.getModuleById("\0fresh:server-snapshot");
if (snapshot === undefined) return;
const queue: EnvironmentModuleNode[] = [mod];
let item: EnvironmentModuleNode | undefined;
while ((item = queue.pop()) !== undefined) {
if (item.file !== null) {
const normalized = path.normalize(item.file);
const name = routeFileToName.get(normalized);
if (name !== undefined) {
const route = routes.get(name);
if (route !== undefined) {
const mod = ssrGraph.getModuleById(id);
if (mod !== undefined) {
route.css.push(mod.url);
}
const routeMod = ssrGraph.getModuleById(
`\0fresh-route-css::${name}`,
);
if (routeMod !== undefined) {
ssrGraph.invalidateModule(routeMod);
}
}
}
}
item.importers.forEach((importer) => queue.push(importer));
}
}
},
},
},
{
name: "fresh:island-resolver",
sharedDuringBuild: true,
resolveId: {
filter: {
id: /^fresh-island::.*/,
},
handler(id) {
let name = id.slice("fresh-island::".length);
if (JS_REG.test(name)) {
name = name.slice(0, name.lastIndexOf("."));
}
const spec = islandSpecByName.get(name);
if (spec !== undefined) return spec;
},
},
},
{
name: "fresh:route-css",
sharedDuringBuild: true,
resolveId: {
filter: {
id: /^(\/@id\/)?fresh-route-css::/,
},
handler(id) {
let name = id.startsWith("/@id/")
? id.slice("/@id/fresh-route-css::".length)
: id.slice("fresh-route-css::".length);
const idx = name.indexOf(".module.");
if (idx > -1) {
name = name.slice(0, idx);
}
return `\0fresh-route-css::${name}`;
},
},
load: {
filter: {
id: /^\0fresh-route-css::/,
},
handler(id) {
const name = id.slice("\0fresh-route-css::".length);
const route = routes.get(name);
if (route === undefined) return;
if (!isDev) {
return `export default ["__FRESH_CSS_PLACEHOLDER__"];`;
}
const imports = route.css.map((css) => `import "${css}";`).join("\n");
return `${imports}
export default ${JSON.stringify(route.css)}
`;
},
},
},
{
name: "fresh-route-css-build-ssr",
sharedDuringBuild: true,
applyToEnvironment(env) {
return env.config.consumer === "server";
},
async writeBundle(_, bundle) {
const asset = bundle[".vite/manifest.json"];
if (asset.type === "asset") {
const manifest = JSON.parse(asset.source as string) as Manifest;
for (const info of Object.values(manifest)) {
if (info.name?.startsWith("_fresh-route___")) {
const filePath = path.join(serverOutDir, info.file);
const content = await Deno.readTextFile(filePath);
const replaced = content.replace(
`["__FRESH_CSS_PLACEHOLDER__"]`,
info.css
? JSON.stringify(info.css.map((css) => `/${css}`))
: "null",
);
await Deno.writeTextFile(filePath, replaced);
}
}
}
},
},
{
name: "fresh:route-resolver",
sharedDuringBuild: true,
resolveId: {
filter: {
id: /^fresh-route::/,
},
handler(id) {
let name = id.slice("fresh-route::".length);
if (JS_REG.test(name)) {
name = name.slice(0, name.lastIndexOf("."));
}
return `\0fresh-route::${name}`;
},
},
load: {
filter: {
id: /^\0fresh-route::.*/,
},
handler(id) {
const name = id.slice("\0fresh-route::".length);
const route = routes.get(name);
if (route === undefined) return;
const fileUrl = path.toFileUrl(route.filePath).href;
const cssId = isDev
? `/@id/fresh-route-css::${name}.module.css`
: `fresh-route-css::${name}.module.css`;
// For some reason doing `export * from "foo"` is broken
// in vite.
const code = `import * as mod from "${fileUrl}";
import routeCss from "${cssId}";
export const css = routeCss;
export const config = mod.config;
export const handler = mod.handler;
export const handlers = mod.handlers;
export default mod.default;
`;
return { code };
},
},
},
];
}
function walkUp(
mod: EnvironmentModuleNode,
fn: (mod: EnvironmentModuleNode) => boolean,
seen: Set<EnvironmentModuleNode>,
): boolean {
if (seen.has(mod)) return false;
if (fn(mod)) return true;
const importers = Array.from(mod.importers);
for (let i = 0; i < importers.length; i++) {
const imp = importers[i];
if (walkUp(imp, fn, seen)) return true;
}
return false;
}