Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(viteroll): inline @rolldown/client #73

Merged
merged 4 commits into from
Nov 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 12 additions & 26 deletions viteroll/viteroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,19 +81,6 @@ export function viteroll(viterollOptions: ViterollOptions = {}): Plugin {
sirv(environments.client.outDir, { dev: true, extensions: ["html"] }),
);

// reuse /@vite/client for Websocket API but serve it on our own
// TODO: include it in `rolldown_runtime`?
const rolldownClientCode = getRolldownClientCode();
server.middlewares.use((req, res, next) => {
const url = new URL(req.url ?? "", "https://rolldown.rs");
if (url.pathname === "/@rolldown/client") {
res.setHeader("content-type", "text/javascript;charset=utf-8");
res.end(rolldownClientCode);
return;
}
next();
});

// full build on non self accepting entry
server.ws.on("rolldown:hmr-deadend", async (data) => {
logger.info(`hmr-deadend '${data.moduleId}'`, { timestamp: true });
Expand Down Expand Up @@ -125,23 +112,28 @@ export function viteroll(viterollOptions: ViterollOptions = {}): Plugin {
};
}

function getRolldownClientCode() {
// reuse /@vite/client for Websocket API and inject to rolldown:runtime
function getRolldownClientCode(config: ResolvedConfig) {
config.base;
const viteClientPath = require.resolve("vite/dist/client/client.mjs");
let code = fs.readFileSync(viteClientPath, "utf-8");
const replacements = {
// https://github.com/vitejs/vite/blob/55461b43329db6a5e737eab591163a8681ba9230/packages/vite/src/node/plugins/clientInjections.ts
__BASE__: `"/"`,
// TODO: https://github.com/vitejs/vite/blob/55461b43329db6a5e737eab591163a8681ba9230/packages/vite/src/node/plugins/clientInjections.ts
__BASE__: JSON.stringify(config.base),
__SERVER_HOST__: `""`,
__HMR_PROTOCOL__: `null`,
__HMR_HOSTNAME__: `null`,
__HMR_PORT__: `new URL(import.meta.url).port`,
__HMR_PORT__: `new URL(self.location.href).port`,
__HMR_DIRECT_TARGET__: `""`,
__HMR_BASE__: `"/"`,
__HMR_TIMEOUT__: `30000`,
__HMR_ENABLE_OVERLAY__: `true`,
__HMR_CONFIG_NAME__: `""`,
// runtime define is not necessary
[`import '@vite/env';`]: ``,
// remove esm code since this runs as classic script
[`export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle };`]: ``,
"import.meta.url": "self.location.href",
};
for (const [k, v] of Object.entries(replacements)) {
code = code.replaceAll(k, v);
Expand All @@ -154,7 +146,7 @@ hot.on("rolldown:hmr", (data) => {
});
window.__rolldown_hot = hot;
`;
return code;
return `(() => {/*** @vite/client for rolldown ***/\n${code}}\n)()`;
}

export class RolldownEnvironment extends DevEnvironment {
Expand Down Expand Up @@ -345,8 +337,8 @@ function viterollEntryPlugin(
// patch rolldown_runtime to workaround a few things
if (code.includes("//#region rolldown:runtime")) {
const output = new MagicString(code);
// patch out hard-coded WebSocket setup "const socket = WebSocket(`ws://localhost:8080`)"
output.replace(/const socket =.*?\n};/s, "");
// replace hard-coded WebSocket setup with custom one
output.replace(/const socket =.*?\n};/s, getRolldownClientCode(config));
// trigger full rebuild on non-accepting entry invalidation
output
.replace("parents: [parent],", "parents: parent ? [parent] : [],")
Expand Down Expand Up @@ -379,12 +371,6 @@ function viterollEntryPlugin(
`<script src="/${chunk.fileName}"></script>`,
);

// inject client
htmlOutput.appendLeft(
htmlOutput.original.indexOf(`</head>`),
`<script type="module" src="/@rolldown/client"></script>`,
);

this.emitFile({
type: "asset",
fileName: path.relative(config.root, htmlId),
Expand Down