-
Notifications
You must be signed in to change notification settings - Fork 750
Expand file tree
/
Copy pathserver_entry.ts
More file actions
186 lines (163 loc) · 4.97 KB
/
server_entry.ts
File metadata and controls
186 lines (163 loc) · 4.97 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
import type { Manifest, Plugin } from "vite";
import {
generateServerEntry,
type PendingStaticFile,
prepareStaticFile,
writeCompiledEntry,
} from "fresh/internal-dev";
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
import * as path from "@std/path";
export function serverEntryPlugin(
options: ResolvedFreshViteConfig,
): Plugin {
const modName = "fresh:server_entry";
let serverEntry = "";
let serverEntryFilename = "";
let serverOutDir = "";
let clientOutDir = "";
let root = "";
let basePath = "";
let isDev = false;
const getAssetPath = (id: string): string => {
if (basePath === "/") {
return `/${id}`;
}
// Ensure basePath ends with / and construct the path manually to avoid platform-specific path issues
const normalizedBase = basePath.endsWith("/") ? basePath : basePath + "/";
return normalizedBase + id;
};
return {
name: "fresh:server_entry",
sharedDuringBuild: true,
applyToEnvironment(env) {
return env.config.consumer === "server";
},
config(_, env) {
isDev = env.command === "serve";
},
configResolved(config) {
root = config.root;
basePath = config.base || "/";
if (basePath !== "/" && !basePath.endsWith("/")) {
basePath += "/";
}
serverEntry = pathWithRoot(options.serverEntry, config.root);
serverOutDir = pathWithRoot(
config.environments.ssr.build.outDir,
config.root,
);
clientOutDir = pathWithRoot(
config.environments.client.build.outDir,
config.root,
);
},
resolveId: {
filter: {
id: /fresh:server_entry/,
},
handler(id) {
if (id === modName) {
return `\0${modName}`;
}
},
},
load: {
filter: {
id: /\0fresh:server_entry/,
},
handler() {
let code = generateServerEntry({
root: isDev ? path.relative(serverOutDir, root) : "..",
serverEntry: path.toFileUrl(serverEntry).href,
snapshotSpecifier: "fresh:server-snapshot",
});
code += `
export function registerStaticFile(prepared) {
snapshot.staticFiles.set(prepared.name, {
name: prepared.name,
contentType: prepared.contentType,
filePath: prepared.filePath,
hash: prepared.hash ?? null,
immutable: prepared.immutable,
});
}
`;
if (isDev) {
code = `import "preact/debug";
import { setErrorInterceptor as internalErrorIntercept } from "fresh/internal";
${code}
export function setErrorInterceptor(fn) {
internalErrorIntercept(app, fn);
refreshHandler();
}
if (import.meta.hot) import.meta.hot.accept();`;
}
return code;
},
},
async writeBundle(_options, bundle) {
// Find server entry filename directly from bundle chunks.
// This is more reliable than the manifest when rollupOptions
// override output.entryFileNames.
for (const chunk of Object.values(bundle)) {
if (chunk.type === "chunk" && chunk.isEntry) {
serverEntryFilename = chunk.fileName;
break;
}
}
const manifest = bundle[".vite/manifest.json"];
const staticFiles: PendingStaticFile[] = [];
if (
manifest && manifest.type === "asset" &&
typeof manifest.source === "string"
) {
const json = JSON.parse(manifest.source) as Manifest;
for (const item of Object.values(json)) {
if (item.assets) {
for (let i = 0; i < item.assets.length; i++) {
const id = item.assets[i];
staticFiles.push({
filePath: path.join(serverOutDir, id),
hash: null,
pathname: getAssetPath(id),
immutable: true,
});
}
}
if (item.css) {
for (let i = 0; i < item.css.length; i++) {
const id = item.css[i];
staticFiles.push({
filePath: path.join(serverOutDir, id),
hash: null,
pathname: getAssetPath(id),
immutable: true,
});
}
}
}
}
const registered = await Promise.all(staticFiles.map(async (file) => {
const prepared = await prepareStaticFile(file, serverOutDir);
const rel = path.relative(serverOutDir, file.filePath);
const target = path.join(clientOutDir, rel);
await Deno.rename(file.filePath, target);
prepared.filePath = path.join("client", prepared.filePath);
return `registerStaticFile(${JSON.stringify(prepared)});`;
}));
const outDir = path.dirname(serverOutDir);
await Deno.writeTextFile(
path.join(outDir, "server.js"),
`import server, { registerStaticFile } from "./server/${
serverEntryFilename || "server-entry.mjs"
}";
${registered.join("\n")}
export default {
fetch: server.fetch
};
`,
);
await writeCompiledEntry(outDir);
},
};
}