From 18332ed8b1fcfd073adfe142f2b06aa912c4de2d Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Tue, 19 Dec 2023 15:47:02 +1100 Subject: [PATCH 01/15] feat(remix-dev/vite): Add unstable_serverBundles --- .changeset/five-peaches-attend.md | 5 + docs/future/server-bundles.md | 54 ++++ docs/future/vite.md | 39 ++- integration/helpers/vite.ts | 10 +- integration/vite-server-bundles-test.ts | 364 ++++++++++++++++++++++++ packages/remix-dev/cli/commands.ts | 6 +- packages/remix-dev/index.ts | 1 + packages/remix-dev/vite/build.ts | 185 +++++++++++- packages/remix-dev/vite/index.ts | 1 + packages/remix-dev/vite/plugin.ts | 104 ++++--- 10 files changed, 713 insertions(+), 56 deletions(-) create mode 100644 .changeset/five-peaches-attend.md create mode 100644 docs/future/server-bundles.md create mode 100644 integration/vite-server-bundles-test.ts diff --git a/.changeset/five-peaches-attend.md b/.changeset/five-peaches-attend.md new file mode 100644 index 00000000000..e74339d6647 --- /dev/null +++ b/.changeset/five-peaches-attend.md @@ -0,0 +1,5 @@ +--- +"@remix-run/dev": patch +--- + +Remove Vite plugin config option `serverBuildPath` in favor of separate `serverBuildDirectory` and `serverBuildFile` options diff --git a/docs/future/server-bundles.md b/docs/future/server-bundles.md new file mode 100644 index 00000000000..769adcc48ba --- /dev/null +++ b/docs/future/server-bundles.md @@ -0,0 +1,54 @@ +--- +title: Server Bundles (Unstable) +--- + +# Server Bundles (Unstable) + +This is an advanced feature designed for hosting provider integrations. When a Remix app is compiled into multiple request handlers, there will need to be a custom routing layer in front of your app directing requests to the correct handler. Hosting providers that want to make use of this feature are expected to implement this custom routing layer, not the average Remix developer. This feature is currently unstable and only designed to gather early feedback. + +Remix typically builds your server code into a single request handler function. However, there are some scenarios where you might want to split your route tree into multiple request handlers that each accept a subset of requests. To provide this level of flexibility, the [Remix Vite plugin][remix-vite] supports an `unstable_serverBundles` option which is a function for assigning routes to different server bundles. + +The provided `unstable_serverBundles` function is called for each route in the tree (except for routes that aren't addressable, e.g. pathless layout routes) and returns a server bundle ID that you'd like to assign it to. These bundle IDs will be used as directory names in your server build directory. + +The function is passed a route `branch` which is a root-first array of `route` objects leading to and including the target route which which allows you to create server bundles for different portions of the route tree. For example, you could use this to create a server bundle containing all routes within a particular layout route: + +```ts filename=vite.config.ts lines=[7-10] +import { unstable_vitePlugin as remix } from "@remix-run/dev"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [ + remix({ + unstable_serverBundles: ({ branch }) => { + const isAuthenticatedRoute = branch.some( + (route) => route.id === "routes/_authenticated" + ); + + return isAuthenticatedRoute + ? "authenticated" + : "unauthenticated"; + }, + }), + ], +}); +``` + +Each `route` object in the `branch` array contains the following properties: + +- `id` — The unique ID for this route, named like its `file` but relative to the app directory and without the extension, e.g. `app/routes/gists.$username.tsx` will have an `id` of `routes/gists.$username`. +- `path` — The path this route uses to match on the URL pathname. +- `file` — The absolute path to the entry point for this route. +- `index` — Whether or not this route is an index route. +- `caseSensitive` — Whether or not the `path` is case-sensitive. +- `parentId` — The unique `id` for this route's parent route, if there is one. + +## Server bundle manifest + +When the build is complete, Remix will generate a `bundles.json` manifest file in your server build directory containing an object with the following properties: + +- `serverBundles` — An object mapping bundle IDs to an object containing the bundle's `id` and `file`. +- `routeIdToServerBundleId` — An object mapping route IDs to server bundle ID. +- `routes` — A route manifest mapping route IDs to route metadata. This can be used to drive a custom routing layer in front of your Remix request handlers. + +[remix-vite]: ./vite.md +[pathless-layout-route]: ../file-conventions/routes#nested-layouts-without-nested-urls diff --git a/docs/future/vite.md b/docs/future/vite.md index 15a77df7db2..ce4bb44fca4 100644 --- a/docs/future/vite.md +++ b/docs/future/vite.md @@ -34,15 +34,7 @@ These templates include a `vite.config.ts` file which is where the Remix Vite pl ## Configuration -The Vite plugin does not use [`remix.config.js`][remix-config]. Instead, the plugin directly accepts the following subset of Remix config options: - -- [appDirectory][app-directory] -- [assetsBuildDirectory][assets-build-directory] -- [ignoredRouteFiles][ignored-route-files] -- [publicPath][public-path] -- [routes][routes] -- [serverBuildPath][server-build-path] -- [serverModuleFormat][server-module-format] +The Vite plugin does not use [`remix.config.js`][remix-config]. Instead, the plugin accepts options directly. For example, to configure `ignoredRouteFiles`: @@ -61,6 +53,32 @@ export default defineConfig({ All other bundling-related options are now [configured with Vite][vite-config]. This means you have much greater control over the bundling process. +#### Supported Remix config options + +The following subset of Remix config options are supported: + +- [appDirectory][app-directory] +- [assetsBuildDirectory][assets-build-directory] +- [ignoredRouteFiles][ignored-route-files] +- [publicPath][public-path] +- [routes][routes] +- [serverBuildPath][server-build-path] +- [serverModuleFormat][server-module-format] + +The Vite plugin also accepts the following additional options: + +#### serverBuildDirectory + +The path to the server build directory, relative to the project root. Defaults to `"build/server"`. + +#### serverBuildFile + +The name of the server file generated in the server build directory. Defaults to `"index.js"`. + +#### unstable_serverBundles + +A function for assigning addressable routes to [server bundles][server-bundles]. + ## New build output paths There is a notable difference with the way Vite manages the `public` directory compared to the existing Remix compiler. During the build, Vite copies files from the `public` directory into `build/client`, whereas the Remix compiler left the `public` directory untouched and used a subdirectory (`public/build`) as the client build directory. @@ -74,7 +92,7 @@ This means that the following configuration defaults have been changed: - [assetsBuildDirectory][assets-build-directory] defaults to `"build/client"` rather than `"public/build"` - [publicPath][public-path] defaults to `"/"` rather than `"/build/"` -- [serverBuildPath][server-build-path] defaults to `"build/server/index.js"` rather than `"build/index.js"` +- [serverBuildPath][server-build-path] has been split into `serverBuildDirectory` and `serverBuildFile`, with the equivalent default for `serverBuildDirectory` being `"build/server"` rather than `"build"` ## Additional features & plugins @@ -875,3 +893,4 @@ We're definitely late to the Vite party, but we're excited to be here now! [server-dependencies-to-bundle]: https://remix.run/docs/en/main/file-conventions/remix-config#serverdependenciestobundle [blues-stack]: https://github.com/remix-run/blues-stack [global-node-polyfills]: ../other-api/node#polyfills +[server-bundles]: ./server-bundles diff --git a/integration/helpers/vite.ts b/integration/helpers/vite.ts index 3f82cbf3938..0a6978d88df 100644 --- a/integration/helpers/vite.ts +++ b/integration/helpers/vite.ts @@ -16,6 +16,7 @@ const __dirname = url.fileURLToPath(new URL(".", import.meta.url)); export const VITE_CONFIG = async (args: { port: number; + pluginOptions?: string; vitePlugins?: string; }) => { let hmrPort = await getPort(); @@ -31,7 +32,7 @@ export const VITE_CONFIG = async (args: { port: ${hmrPort} } }, - plugins: [remix(),${args.vitePlugins ?? ""}], + plugins: [remix(${args.pluginOptions}),${args.vitePlugins ?? ""}], }); `; }; @@ -136,14 +137,19 @@ export const viteBuild = ({ cwd }: { cwd: string }) => { export const viteRemixServe = async ({ cwd, port, + serverBundle, }: { cwd: string; port: number; + serverBundle?: string; }) => { let nodeBin = process.argv[0]; let serveProc = spawn( nodeBin, - ["node_modules/@remix-run/serve/dist/cli.js", "build/server/index.js"], + [ + "node_modules/@remix-run/serve/dist/cli.js", + `build/server/${serverBundle ? serverBundle + "/" : ""}index.js`, + ], { cwd, stdio: "pipe", diff --git a/integration/vite-server-bundles-test.ts b/integration/vite-server-bundles-test.ts new file mode 100644 index 00000000000..290cea8247e --- /dev/null +++ b/integration/vite-server-bundles-test.ts @@ -0,0 +1,364 @@ +import fs from "node:fs"; +import path from "node:path"; +import { test, expect } from "@playwright/test"; +import getPort from "get-port"; + +import { + createProject, + viteBuild, + viteRemixServe, + VITE_CONFIG, +} from "./helpers/vite.js"; + +const withBundleServer = async ( + cwd: string, + serverBundle: string, + callback: (port: number) => Promise +): Promise => { + let port = await getPort(); + let stop = await viteRemixServe({ cwd, port, serverBundle }); + await callback(port); + stop(); +}; + +const ROUTE_FILE_COMMENT = "// THIS IS A ROUTE FILE"; + +function createRoute(path: string) { + return { + [`app/routes/${path}`]: ` + ${ROUTE_FILE_COMMENT} + import { Links, Meta, Outlet, Scripts, LiveReload } from "@remix-run/react"; + import { useState, useEffect } from "react"; + + export default function Route() { + const [mounted, setMounted] = useState(false); + useEffect(() => { + setMounted(true); + }, []); + return ( + <> +
+ Route: ${path} + {mounted ? (Mounted) : null} +
+ + + ); + } + `, + }; +} + +const files = { + "app/root.tsx": ` + ${ROUTE_FILE_COMMENT} + import { Links, Meta, Outlet, Scripts, LiveReload } from "@remix-run/react"; + + export default function Root() { + return ( + + + + + + + + + + + + ); + } + `, + ...createRoute("_index.tsx"), + + // Bundle A has an index route + ...createRoute("bundle-a.tsx"), + ...createRoute("bundle-a._index.tsx"), + ...createRoute("bundle-a.route-a.tsx"), + ...createRoute("bundle-a.route-b.tsx"), + + // Bundle B doesn't have an index route + ...createRoute("bundle-b.tsx"), + ...createRoute("bundle-b.route-a.tsx"), + ...createRoute("bundle-b.route-b.tsx"), + + // Bundle C is nested in a pathless route + ...createRoute("_pathless.tsx"), + ...createRoute("_pathless.bundle-c.tsx"), + ...createRoute("_pathless.bundle-c.route-a.tsx"), + ...createRoute("_pathless.bundle-c.route-b.tsx"), +}; + +test.describe(() => { + test.describe(async () => { + let cwd: string; + + test.beforeAll(async () => { + cwd = await createProject({ + "vite.config.ts": await VITE_CONFIG({ + port: -1, // Port only used for dev but we're testing the build + pluginOptions: `{ + unstable_serverBundles: async ({ branch }) => { + // Smoke test to ensure we can read the route files via 'route.file' + await Promise.all(branch.map(async (route) => { + const fs = await import("node:fs/promises"); + const routeFileContents = await fs.readFile(route.file, "utf8"); + if (!routeFileContents.includes(${JSON.stringify( + ROUTE_FILE_COMMENT + )})) { + throw new Error("Couldn't file route file test comment"); + } + })); + + if (branch.some((route) => route.id === "routes/_index")) { + return "root"; + } + + if (branch.some((route) => route.id === "routes/bundle-a")) { + return "bundle-a"; + } + + if (branch.some((route) => route.id === "routes/bundle-b")) { + return "bundle-b"; + } + + if (branch.some((route) => route.id === "routes/_pathless.bundle-c")) { + return "bundle-c"; + } + + throw new Error("No bundle defined for route " + branch[branch.length - 1].id); + } + }`, + }), + ...files, + }); + + await viteBuild({ cwd }); + }); + + test("Vite / server bundles", async ({ page }) => { + let pageErrors: Error[] = []; + page.on("pageerror", (error) => pageErrors.push(error)); + + await withBundleServer(cwd, "root", async (port) => { + await page.goto(`http://localhost:${port}/`); + await expect( + page.locator('[data-route-file="_index.tsx"] [data-mounted]') + ).toBeVisible(); + + let _404s = ["/bundle-a", "/bundle-b", "/bundle-c"]; + for (let path of _404s) { + let response = await page.goto(`http://localhost:${port}${path}`); + expect(response?.status()).toBe(404); + } + }); + + await withBundleServer(cwd, "bundle-a", async (port) => { + await page.goto(`http://localhost:${port}/bundle-a`); + await expect( + page.locator('[data-route-file="bundle-a._index.tsx"] [data-mounted]') + ).toBeVisible(); + + await page.goto(`http://localhost:${port}/bundle-a`); + await expect( + page.locator('[data-route-file="bundle-a._index.tsx"] [data-mounted]') + ).toBeVisible(); + + await page.goto(`http://localhost:${port}/bundle-a/route-a`); + await expect( + page.locator( + '[data-route-file="bundle-a.route-a.tsx"] [data-mounted]' + ) + ).toBeVisible(); + + await page.goto(`http://localhost:${port}/bundle-a/route-b`); + await expect( + page.locator( + '[data-route-file="bundle-a.route-b.tsx"] [data-mounted]' + ) + ).toBeVisible(); + + let _404s = ["/bundle-b", "/bundle-c"]; + for (let path of _404s) { + let response = await page.goto(`http://localhost:${port}${path}`); + expect(response?.status()).toBe(404); + } + }); + + await withBundleServer(cwd, "bundle-b", async (port) => { + await page.goto(`http://localhost:${port}/bundle-b/route-a`); + await expect( + page.locator( + '[data-route-file="bundle-b.route-a.tsx"] [data-mounted]' + ) + ).toBeVisible(); + + await page.goto(`http://localhost:${port}/bundle-b/route-b`); + await expect( + page.locator( + '[data-route-file="bundle-b.route-b.tsx"] [data-mounted]' + ) + ).toBeVisible(); + + let _404s = ["/bundle-a", "/bundle-c"]; + for (let path of _404s) { + let response = await page.goto(`http://localhost:${port}${path}`); + expect(response?.status()).toBe(404); + } + }); + + await withBundleServer(cwd, "bundle-c", async (port) => { + await page.goto(`http://localhost:${port}/bundle-c/route-a`); + await expect( + page.locator('[data-route-file="_pathless.tsx"] [data-mounted]') + ).toBeVisible(); + await expect( + page.locator( + '[data-route-file="_pathless.bundle-c.route-a.tsx"] [data-mounted]' + ) + ).toBeVisible(); + + await page.goto(`http://localhost:${port}/bundle-c/route-b`); + await expect( + page.locator('[data-route-file="_pathless.tsx"] [data-mounted]') + ).toBeVisible(); + await expect( + page.locator( + '[data-route-file="_pathless.bundle-c.tsx"] [data-mounted]' + ) + ).toBeVisible(); + await expect( + page.locator( + '[data-route-file="_pathless.bundle-c.route-b.tsx"] [data-mounted]' + ) + ).toBeVisible(); + + let _404s = ["/bundle-a", "/bundle-b"]; + for (let path of _404s) { + let response = await page.goto(`http://localhost:${port}${path}`); + expect(response?.status()).toBe(404); + } + }); + + expect(pageErrors).toHaveLength(0); + }); + + test("Vite / server bundles / manifest", async () => { + expect( + JSON.parse( + fs.readFileSync(path.join(cwd, "build/server/bundles.json"), "utf8") + ) + ).toEqual({ + serverBundles: { + "bundle-c": { + id: "bundle-c", + file: "build/server/bundle-c/index.js", + }, + "bundle-a": { + id: "bundle-a", + file: "build/server/bundle-a/index.js", + }, + "bundle-b": { + id: "bundle-b", + file: "build/server/bundle-b/index.js", + }, + root: { + id: "root", + file: "build/server/root/index.js", + }, + }, + routeIdToBundleId: { + "routes/_pathless.bundle-c.route-a": "bundle-c", + "routes/_pathless.bundle-c.route-b": "bundle-c", + "routes/_pathless.bundle-c": "bundle-c", + "routes/bundle-a.route-a": "bundle-a", + "routes/bundle-a.route-b": "bundle-a", + "routes/bundle-b.route-a": "bundle-b", + "routes/bundle-b.route-b": "bundle-b", + "routes/bundle-a._index": "bundle-a", + "routes/bundle-b": "bundle-b", + "routes/_index": "root", + }, + routes: { + root: { + path: "", + id: "root", + file: "app/root.tsx", + }, + "routes/_pathless.bundle-c.route-a": { + file: "app/routes/_pathless.bundle-c.route-a.tsx", + id: "routes/_pathless.bundle-c.route-a", + path: "route-a", + parentId: "routes/_pathless.bundle-c", + }, + "routes/_pathless.bundle-c.route-b": { + file: "app/routes/_pathless.bundle-c.route-b.tsx", + id: "routes/_pathless.bundle-c.route-b", + path: "route-b", + parentId: "routes/_pathless.bundle-c", + }, + "routes/_pathless.bundle-c": { + file: "app/routes/_pathless.bundle-c.tsx", + id: "routes/_pathless.bundle-c", + path: "bundle-c", + parentId: "routes/_pathless", + }, + "routes/bundle-a.route-a": { + file: "app/routes/bundle-a.route-a.tsx", + id: "routes/bundle-a.route-a", + path: "route-a", + parentId: "routes/bundle-a", + }, + "routes/bundle-a.route-b": { + file: "app/routes/bundle-a.route-b.tsx", + id: "routes/bundle-a.route-b", + path: "route-b", + parentId: "routes/bundle-a", + }, + "routes/bundle-b.route-a": { + file: "app/routes/bundle-b.route-a.tsx", + id: "routes/bundle-b.route-a", + path: "route-a", + parentId: "routes/bundle-b", + }, + "routes/bundle-b.route-b": { + file: "app/routes/bundle-b.route-b.tsx", + id: "routes/bundle-b.route-b", + path: "route-b", + parentId: "routes/bundle-b", + }, + "routes/bundle-a._index": { + file: "app/routes/bundle-a._index.tsx", + id: "routes/bundle-a._index", + index: true, + parentId: "routes/bundle-a", + }, + "routes/_pathless": { + file: "app/routes/_pathless.tsx", + id: "routes/_pathless", + parentId: "root", + }, + "routes/bundle-a": { + file: "app/routes/bundle-a.tsx", + id: "routes/bundle-a", + path: "bundle-a", + parentId: "root", + }, + "routes/bundle-b": { + file: "app/routes/bundle-b.tsx", + id: "routes/bundle-b", + path: "bundle-b", + parentId: "root", + }, + "routes/_index": { + file: "app/routes/_index.tsx", + id: "routes/_index", + index: true, + parentId: "root", + }, + }, + }); + }); + }); +}); diff --git a/packages/remix-dev/cli/commands.ts b/packages/remix-dev/cli/commands.ts index 5aae527544c..596635ff0da 100644 --- a/packages/remix-dev/cli/commands.ts +++ b/packages/remix-dev/cli/commands.ts @@ -135,9 +135,13 @@ export async function build( } export async function viteBuild( - root: string, + root?: string, options: ViteBuildOptions = {} ): Promise { + if (!root) { + root = process.env.REMIX_ROOT || process.cwd(); + } + let { build } = await import("../vite/build"); await build(root, options); } diff --git a/packages/remix-dev/index.ts b/packages/remix-dev/index.ts index 4dbdb3faf21..7785e0c8587 100644 --- a/packages/remix-dev/index.ts +++ b/packages/remix-dev/index.ts @@ -6,4 +6,5 @@ export * as cli from "./cli/index"; export type { Manifest as AssetsManifest } from "./manifest"; export { getDependenciesToBundle } from "./dependencies"; +export type { Unstable_ServerBundlesManifest } from "./vite"; export { unstable_vitePlugin } from "./vite"; diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index 006e4a98e70..7374e07c8dd 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -1,9 +1,16 @@ import type * as Vite from "vite"; +import path from "node:path"; +import fse from "fs-extra"; import colors from "picocolors"; -import type { ResolvedRemixVitePluginConfig } from "./plugin"; +import type { + ResolvedRemixVitePluginConfig, + ServerBuildConfig, +} from "./plugin"; +import type { ConfigRoute, RouteManifest } from "../config/routes"; +import invariant from "../invariant"; -async function extractRemixPluginConfig({ +async function extractConfig({ configFile, mode, root, @@ -11,7 +18,7 @@ async function extractRemixPluginConfig({ configFile?: string; mode?: string; root: string; -}): Promise { +}) { let vite = await import("vite"); // Leverage the Vite config as a way to configure the entire multi-step build @@ -29,7 +36,141 @@ async function extractRemixPluginConfig({ process.exit(1); } - return pluginConfig; + return { pluginConfig, viteConfig }; +} + +function getAddressableRoutes(routes: RouteManifest): ConfigRoute[] { + let nonAddressableIds = new Set(); + + for (let id in routes) { + let route = routes[id]; + + // We omit the parent route of index routes since the index route takes ownership of its parent's path + if (route.index) { + invariant( + route.parentId, + `Expected index route "${route.id}" to have "parentId" set` + ); + nonAddressableIds.add(route.parentId); + } + + // We omit pathless routes since they can only be addressed via descendant routes + if (typeof route.path !== "string" && !route.index) { + nonAddressableIds.add(id); + } + } + + return Object.values(routes).filter( + (route) => !nonAddressableIds.has(route.id) + ); +} + +function getRouteBranch(routes: RouteManifest, routeId: string) { + let branch: ConfigRoute[] = []; + let currentRouteId: string | undefined = routeId; + + while (currentRouteId) { + let route: ConfigRoute = routes[currentRouteId]; + invariant(route, `Missing route for ${currentRouteId}`); + branch.push(route); + currentRouteId = route.parentId; + } + + return branch.reverse(); +} + +export type ServerBundlesManifest = { + serverBundles: { + [serverBundleId: string]: { + id: string; + file: string; + }; + }; + routeIdToBundleId: Record; + routes: RouteManifest; +}; + +async function getServerBundles({ + routes, + serverBuildDirectory, + serverBuildFile, + serverBundles: getServerBundles, + rootDirectory, + appDirectory, +}: ResolvedRemixVitePluginConfig): Promise<{ + serverBundles: ServerBuildConfig[]; + serverBundlesManifest?: ServerBundlesManifest; +}> { + if (!getServerBundles) { + return { serverBundles: [{ routes, serverBuildDirectory }] }; + } + + let resolvedAppDirectory = path.resolve(rootDirectory, appDirectory); + let rootRelativeRoutes = Object.fromEntries( + Object.entries(routes).map(([id, route]) => { + let filePath = path.join(resolvedAppDirectory, route.file); + let rootRelativeFilePath = path.relative(rootDirectory, filePath); + return [id, { ...route, file: rootRelativeFilePath }]; + }) + ); + + let serverBundlesManifest: ServerBundlesManifest = { + serverBundles: {}, + routeIdToBundleId: {}, + routes: rootRelativeRoutes, + }; + + let serverBundles = new Map(); + + await Promise.all( + getAddressableRoutes(routes).map(async (route) => { + let branch = getRouteBranch(routes, route.id); + let bundleId = await getServerBundles({ + branch: branch.map((route) => ({ + ...route, + // Ensure absolute paths are passed to the serverBundles function + file: path.join(resolvedAppDirectory, route.file), + })), + }); + serverBundlesManifest.routeIdToBundleId[route.id] = bundleId; + + let serverBundleDirectory = path.join(serverBuildDirectory, bundleId); + let serverBuildConfig = serverBundles.get(bundleId); + if (!serverBuildConfig) { + serverBundlesManifest.serverBundles[bundleId] = { + id: bundleId, + file: path.join(serverBundleDirectory, serverBuildFile), + }; + serverBuildConfig = { + routes: {}, + serverBuildDirectory: serverBundleDirectory, + }; + serverBundles.set(bundleId, serverBuildConfig); + } + for (let route of branch) { + serverBuildConfig.routes[route.id] = route; + } + }) + ); + + return { + serverBundles: Array.from(serverBundles.values()), + serverBundlesManifest, + }; +} + +async function cleanServerBuildDirectory( + viteConfig: Vite.ResolvedConfig, + { rootDirectory, serverBuildDirectory }: ResolvedRemixVitePluginConfig +) { + let isWithinRoot = () => { + let relativePath = path.relative(rootDirectory, serverBuildDirectory); + return !relativePath.startsWith("..") && !path.isAbsolute(relativePath); + }; + + if (viteConfig.build.emptyOutDir ?? isWithinRoot()) { + await fse.remove(serverBuildDirectory); + } } export interface ViteBuildOptions { @@ -56,10 +197,7 @@ export async function build( mode, }: ViteBuildOptions ) { - // For now we just use this function to validate that the Vite config is - // targeting Remix, but in the future the return value can be used to - // configure the entire multi-step build process. - await extractRemixPluginConfig({ + let { pluginConfig, viteConfig } = await extractConfig({ configFile, mode, root, @@ -67,7 +205,8 @@ export async function build( let vite = await import("vite"); - async function viteBuild({ ssr }: { ssr: boolean }) { + async function viteBuild(serverBuildConfig?: ServerBuildConfig) { + let ssr = Boolean(serverBuildConfig); await vite.build({ root, mode, @@ -76,9 +215,33 @@ export async function build( optimizeDeps: { force }, clearScreen, logLevel, + ...(serverBuildConfig + ? { __remixServerBuildConfig: serverBuildConfig } + : {}), }); } - await viteBuild({ ssr: false }); - await viteBuild({ ssr: true }); + // Since we're potentially running multiple Vite server builds with different + // output directories, we need to clean the root server build directory + // ourselves rather than relying on Vite to do it, otherwise you can end up + // with stale server bundle directories in your build output + await cleanServerBuildDirectory(viteConfig, pluginConfig); + + // Run the Vite client build first + await viteBuild(); + + // Then run Vite SSR builds in parallel + let { serverBundles, serverBundlesManifest } = await getServerBundles( + pluginConfig + ); + + await Promise.all(serverBundles.map(viteBuild)); + + if (serverBundlesManifest) { + await fse.writeFile( + path.join(pluginConfig.serverBuildDirectory, "bundles.json"), + JSON.stringify(serverBundlesManifest, null, 2), + "utf-8" + ); + } } diff --git a/packages/remix-dev/vite/index.ts b/packages/remix-dev/vite/index.ts index 1bcb08bb692..91344d70e29 100644 --- a/packages/remix-dev/vite/index.ts +++ b/packages/remix-dev/vite/index.ts @@ -2,6 +2,7 @@ // don't need to have Vite installed as a peer dependency. Only types should // be imported at the top level. import type { RemixVitePlugin } from "./plugin"; +export type { ServerBundlesManifest as Unstable_ServerBundlesManifest } from "./build"; export const unstable_vitePlugin: RemixVitePlugin = (...args) => { // eslint-disable-next-line @typescript-eslint/consistent-type-imports diff --git a/packages/remix-dev/vite/plugin.ts b/packages/remix-dev/vite/plugin.ts index f5598bc460a..f18ae1c472a 100644 --- a/packages/remix-dev/vite/plugin.ts +++ b/packages/remix-dev/vite/plugin.ts @@ -17,7 +17,7 @@ import jsesc from "jsesc"; import pick from "lodash/pick"; import colors from "picocolors"; -import { type RouteManifest } from "../config/routes"; +import { type ConfigRoute, type RouteManifest } from "../config/routes"; import { type AppConfig as RemixUserConfig, type RemixConfig as ResolvedRemixConfig, @@ -40,7 +40,6 @@ const supportedRemixConfigKeys = [ "ignoredRouteFiles", "publicPath", "routes", - "serverBuildPath", "serverModuleFormat", ] as const satisfies ReadonlyArray; type SupportedRemixConfigKey = typeof supportedRemixConfigKeys[number]; @@ -76,16 +75,21 @@ type RemixConfigJsdocOverrides = { * `"/"`. This is the path the browser will use to find assets. */ publicPath?: SupportedRemixConfig["publicPath"]; - /** - * The path to the server build file, relative to the project. This file - * should end in a `.js` extension and should be deployed to your server. - * Defaults to `"build/server/index.js"`. - */ - serverBuildPath?: SupportedRemixConfig["serverBuildPath"]; }; +type ServerBundlesFunction = (args: { + branch: ConfigRoute[]; +}) => string | Promise; + export type RemixVitePluginOptions = RemixConfigJsdocOverrides & - Omit; + Omit & { + /** + * TODO: Add descriptions + */ + serverBuildDirectory?: string; + serverBuildFile?: string; + unstable_serverBundles?: ServerBundlesFunction; + }; export type ResolvedRemixVitePluginConfig = Pick< ResolvedRemixConfig, @@ -98,9 +102,20 @@ export type ResolvedRemixVitePluginConfig = Pick< | "publicPath" | "relativeAssetsBuildDirectory" | "routes" - | "serverBuildPath" | "serverModuleFormat" ->; +> & { + /** + * TODO: Add descriptions + */ + serverBuildDirectory: string; + serverBuildFile: string; + serverBundles?: ServerBundlesFunction; +}; + +export type ServerBuildConfig = { + routes: RouteManifest; + serverBuildDirectory: string; +}; let serverBuildId = VirtualModule.id("server-build"); let serverManifestId = VirtualModule.id("server-manifest"); @@ -111,9 +126,8 @@ let injectHmrRuntimeId = VirtualModule.id("inject-hmr-runtime"); const isJsFile = (filePath: string) => /\.[cm]?[jt]sx?$/i.test(filePath); -type Route = RouteManifest[string]; const resolveRelativeRouteFilePath = ( - route: Route, + route: ConfigRoute, pluginConfig: ResolvedRemixVitePluginConfig ) => { let vite = importViteEsmSync(); @@ -301,22 +315,43 @@ export const remixVitePlugin: RemixVitePlugin = (options = {}) => { let viteChildCompiler: Vite.ViteDevServer | null = null; let cachedPluginConfig: ResolvedRemixVitePluginConfig | undefined; + let resolveServerBuildConfig = (): ServerBuildConfig | null => { + if ( + !("__remixServerBuildConfig" in viteUserConfig) || + !viteUserConfig.__remixServerBuildConfig + ) { + return null; + } + + let { routes, serverBuildDirectory } = + viteUserConfig.__remixServerBuildConfig as ServerBuildConfig; + + // Ensure extra config values can't sneak through + return { routes, serverBuildDirectory }; + }; + let resolvePluginConfig = async (): Promise => { - let defaults: Partial = { - serverBuildPath: "build/server/index.js", + let defaults = { assetsBuildDirectory: "build/client", + serverBuildDirectory: "build/server", + serverBuildFile: "index.js", publicPath: "/", - }; + } as const satisfies Partial; - let config = { + let pluginConfig = { ...defaults, - ...pick(options, supportedRemixConfigKeys), // Avoid leaking any config options that the Vite plugin doesn't support + ...options, }; let rootDirectory = viteUserConfig.root ?? process.env.REMIX_ROOT ?? process.cwd(); + let resolvedRemixConfig = await resolveConfig( + pick(pluginConfig, supportedRemixConfigKeys), + { rootDirectory } + ); + // Only select the Remix config options that the Vite plugin uses let { appDirectory, @@ -325,11 +360,17 @@ export const remixVitePlugin: RemixVitePlugin = (options = {}) => { publicPath, routes, entryServerFilePath, - serverBuildPath, + serverBuildDirectory, + serverBuildFile, + unstable_serverBundles, serverModuleFormat, relativeAssetsBuildDirectory, future, - } = await resolveConfig(config, { rootDirectory }); + } = { + ...pluginConfig, + ...resolvedRemixConfig, + ...resolveServerBuildConfig(), + }; return { appDirectory, @@ -339,7 +380,9 @@ export const remixVitePlugin: RemixVitePlugin = (options = {}) => { publicPath, routes, entryServerFilePath, - serverBuildPath, + serverBuildDirectory, + serverBuildFile, + serverBundles: unstable_serverBundles, serverModuleFormat, relativeAssetsBuildDirectory, future, @@ -617,15 +660,13 @@ export const remixVitePlugin: RemixVitePlugin = (options = {}) => { ssrEmitAssets: true, copyPublicDir: false, // Assets in the public directory are only used by the client manifest: true, // We need the manifest to detect SSR-only assets - outDir: path.dirname(pluginConfig.serverBuildPath), + outDir: pluginConfig.serverBuildDirectory, rollupOptions: { ...viteUserConfig.build?.rollupOptions, preserveEntrySignatures: "exports-only", input: serverBuildId, output: { - entryFileNames: path.basename( - pluginConfig.serverBuildPath - ), + entryFileNames: pluginConfig.serverBuildFile, format: pluginConfig.serverModuleFormat, }, }, @@ -830,11 +871,10 @@ export const remixVitePlugin: RemixVitePlugin = (options = {}) => { invariant(cachedPluginConfig); invariant(viteConfig); - let { assetsBuildDirectory, serverBuildPath, rootDirectory } = + let { assetsBuildDirectory, serverBuildDirectory, rootDirectory } = cachedPluginConfig; - let serverBuildDir = path.dirname(serverBuildPath); - let ssrViteManifest = await loadViteManifest(serverBuildDir); + let ssrViteManifest = await loadViteManifest(serverBuildDirectory); let clientViteManifest = await loadViteManifest(assetsBuildDirectory); let clientAssetPaths = new Set( @@ -857,7 +897,7 @@ export const remixVitePlugin: RemixVitePlugin = (options = {}) => { // unnecessary assets don't get deployed alongside the server code. let movedAssetPaths: string[] = []; for (let ssrAssetPath of ssrAssetPaths) { - let src = path.join(serverBuildDir, ssrAssetPath); + let src = path.join(serverBuildDirectory, ssrAssetPath); if (!clientAssetPaths.has(ssrAssetPath)) { let dest = path.join(assetsBuildDirectory, ssrAssetPath); await fse.move(src, dest); @@ -874,7 +914,7 @@ export const remixVitePlugin: RemixVitePlugin = (options = {}) => { ); await Promise.all( ssrCssPaths.map((cssPath) => - fse.remove(path.join(serverBuildDir, cssPath)) + fse.remove(path.join(serverBuildDirectory, cssPath)) ) ); @@ -1288,7 +1328,7 @@ if (import.meta.hot && !inWebWorker && window.__remixLiveReloadEnabled) { function getRoute( pluginConfig: ResolvedRemixVitePluginConfig, file: string -): Route | undefined { +): ConfigRoute | undefined { let vite = importViteEsmSync(); if (!file.startsWith(vite.normalizePath(pluginConfig.appDirectory))) return; let routePath = vite.normalizePath( @@ -1303,7 +1343,7 @@ function getRoute( async function getRouteMetadata( pluginConfig: ResolvedRemixVitePluginConfig, viteChildCompiler: Vite.ViteDevServer | null, - route: Route + route: ConfigRoute ) { let sourceExports = await getRouteModuleExports( viteChildCompiler, From 5b7422af205fee84a9a97109927ce1defb4908cd Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Tue, 19 Dec 2023 16:08:59 +1100 Subject: [PATCH 02/15] Normalize server bundle manifest paths --- packages/remix-dev/vite/build.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index 7374e07c8dd..6a314f0772e 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -79,6 +79,10 @@ function getRouteBranch(routes: RouteManifest, routeId: string) { return branch.reverse(); } +function normalizePath(filePath: string) { + return filePath.replace(/\\/g, "/"); +} + export type ServerBundlesManifest = { serverBundles: { [serverBundleId: string]: { @@ -129,7 +133,7 @@ async function getServerBundles({ branch: branch.map((route) => ({ ...route, // Ensure absolute paths are passed to the serverBundles function - file: path.join(resolvedAppDirectory, route.file), + file: normalizePath(path.join(resolvedAppDirectory, route.file)), })), }); serverBundlesManifest.routeIdToBundleId[route.id] = bundleId; @@ -139,7 +143,9 @@ async function getServerBundles({ if (!serverBuildConfig) { serverBundlesManifest.serverBundles[bundleId] = { id: bundleId, - file: path.join(serverBundleDirectory, serverBuildFile), + file: normalizePath( + path.join(serverBundleDirectory, serverBuildFile) + ), }; serverBuildConfig = { routes: {}, From b5c88d04520a473ada3419bcf5317ea6056a2965 Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Tue, 19 Dec 2023 16:37:59 +1100 Subject: [PATCH 03/15] Normalize route manifest paths --- packages/remix-dev/vite/build.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index 6a314f0772e..660eb517416 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -133,7 +133,7 @@ async function getServerBundles({ branch: branch.map((route) => ({ ...route, // Ensure absolute paths are passed to the serverBundles function - file: normalizePath(path.join(resolvedAppDirectory, route.file)), + file: path.join(resolvedAppDirectory, route.file), })), }); serverBundlesManifest.routeIdToBundleId[route.id] = bundleId; @@ -154,7 +154,10 @@ async function getServerBundles({ serverBundles.set(bundleId, serverBuildConfig); } for (let route of branch) { - serverBuildConfig.routes[route.id] = route; + serverBuildConfig.routes[route.id] = { + ...route, + file: normalizePath(route.file), + }; } }) ); From ef1e6c35c57c046759100ddb55714d9687fa1842 Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Tue, 19 Dec 2023 17:17:58 +1100 Subject: [PATCH 04/15] Fix route normalization --- packages/remix-dev/vite/build.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index 660eb517416..c30075fc762 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -113,7 +113,9 @@ async function getServerBundles({ let rootRelativeRoutes = Object.fromEntries( Object.entries(routes).map(([id, route]) => { let filePath = path.join(resolvedAppDirectory, route.file); - let rootRelativeFilePath = path.relative(rootDirectory, filePath); + let rootRelativeFilePath = normalizePath( + path.relative(rootDirectory, filePath) + ); return [id, { ...route, file: rootRelativeFilePath }]; }) ); @@ -154,10 +156,7 @@ async function getServerBundles({ serverBundles.set(bundleId, serverBuildConfig); } for (let route of branch) { - serverBuildConfig.routes[route.id] = { - ...route, - file: normalizePath(route.file), - }; + serverBuildConfig.routes[route.id] = route; } }) ); From 762c96dd74a350b7899f5b47b1cb204b8c72d31e Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Wed, 20 Dec 2023 10:46:23 +1100 Subject: [PATCH 05/15] Docs review feedback Co-authored-by: Pedro Cattori --- docs/future/server-bundles.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/future/server-bundles.md b/docs/future/server-bundles.md index 769adcc48ba..bf2fb06def5 100644 --- a/docs/future/server-bundles.md +++ b/docs/future/server-bundles.md @@ -4,13 +4,13 @@ title: Server Bundles (Unstable) # Server Bundles (Unstable) -This is an advanced feature designed for hosting provider integrations. When a Remix app is compiled into multiple request handlers, there will need to be a custom routing layer in front of your app directing requests to the correct handler. Hosting providers that want to make use of this feature are expected to implement this custom routing layer, not the average Remix developer. This feature is currently unstable and only designed to gather early feedback. +This is an advanced feature designed for hosting provider integrations. When compiling your app into multiple server bundles, there will need to be a custom routing layer in front of your app directing requests to the correct bundle. This feature is currently unstable and only designed to gather early feedback. -Remix typically builds your server code into a single request handler function. However, there are some scenarios where you might want to split your route tree into multiple request handlers that each accept a subset of requests. To provide this level of flexibility, the [Remix Vite plugin][remix-vite] supports an `unstable_serverBundles` option which is a function for assigning routes to different server bundles. +Remix typically builds your server code into a bundle that exposes a single request handler function. However, there are some scenarios where you might want to split your route tree into multiple server bundles that expose a request handler function for a subset of routes. To provide this level of flexibility, the [Remix Vite plugin][remix-vite] supports an `unstable_serverBundles` option which is a function for assigning routes to different server bundles. The provided `unstable_serverBundles` function is called for each route in the tree (except for routes that aren't addressable, e.g. pathless layout routes) and returns a server bundle ID that you'd like to assign it to. These bundle IDs will be used as directory names in your server build directory. -The function is passed a route `branch` which is a root-first array of `route` objects leading to and including the target route which which allows you to create server bundles for different portions of the route tree. For example, you could use this to create a server bundle containing all routes within a particular layout route: +For each route, this function is passed an array of routes leading to and including that route, referred to as the route `branch`. This allows you to create server bundles for different portions of the route tree. For example, you could use this to create a separate server bundle containing all routes within a particular layout route: ```ts filename=vite.config.ts lines=[7-10] import { unstable_vitePlugin as remix } from "@remix-run/dev"; @@ -33,7 +33,7 @@ export default defineConfig({ }); ``` -Each `route` object in the `branch` array contains the following properties: +Each `route` in the `branch` array contains the following properties: - `id` — The unique ID for this route, named like its `file` but relative to the app directory and without the extension, e.g. `app/routes/gists.$username.tsx` will have an `id` of `routes/gists.$username`. - `path` — The path this route uses to match on the URL pathname. From 7183097d3f6da9a99a453b5c1dcde1806844edfe Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Wed, 20 Dec 2023 11:24:02 +1100 Subject: [PATCH 06/15] Refactor tests, assert non-rendered routes --- integration/vite-server-bundles-test.ts | 549 ++++++++++++------------ 1 file changed, 276 insertions(+), 273 deletions(-) diff --git a/integration/vite-server-bundles-test.ts b/integration/vite-server-bundles-test.ts index 290cea8247e..5ab7f18f975 100644 --- a/integration/vite-server-bundles-test.ts +++ b/integration/vite-server-bundles-test.ts @@ -1,6 +1,6 @@ import fs from "node:fs"; import path from "node:path"; -import { test, expect } from "@playwright/test"; +import { type Page, test, expect } from "@playwright/test"; import getPort from "get-port"; import { @@ -30,7 +30,7 @@ function createRoute(path: string) { import { Links, Meta, Outlet, Scripts, LiveReload } from "@remix-run/react"; import { useState, useEffect } from "react"; - export default function Route() { + export default function Route() { const [mounted, setMounted] = useState(false); useEffect(() => { setMounted(true); @@ -49,6 +49,27 @@ function createRoute(path: string) { }; } +const TEST_ROUTES = [ + "_index.tsx", + + // Bundle A has an index route + "bundle-a.tsx", + "bundle-a._index.tsx", + "bundle-a.route-a.tsx", + "bundle-a.route-b.tsx", + + // Bundle B doesn't have an index route + "bundle-b.tsx", + "bundle-b.route-a.tsx", + "bundle-b.route-b.tsx", + + // Bundle C is nested in a pathless route + "_pathless.tsx", + "_pathless.bundle-c.tsx", + "_pathless.bundle-c.route-a.tsx", + "_pathless.bundle-c.route-b.tsx", +]; + const files = { "app/root.tsx": ` ${ROUTE_FILE_COMMENT} @@ -70,295 +91,277 @@ const files = { ); } `, - ...createRoute("_index.tsx"), - - // Bundle A has an index route - ...createRoute("bundle-a.tsx"), - ...createRoute("bundle-a._index.tsx"), - ...createRoute("bundle-a.route-a.tsx"), - ...createRoute("bundle-a.route-b.tsx"), - - // Bundle B doesn't have an index route - ...createRoute("bundle-b.tsx"), - ...createRoute("bundle-b.route-a.tsx"), - ...createRoute("bundle-b.route-b.tsx"), + ...Object.assign({}, ...TEST_ROUTES.map(createRoute)), +}; - // Bundle C is nested in a pathless route - ...createRoute("_pathless.tsx"), - ...createRoute("_pathless.bundle-c.tsx"), - ...createRoute("_pathless.bundle-c.route-a.tsx"), - ...createRoute("_pathless.bundle-c.route-b.tsx"), +const expectRenderedRoutes = async (page: Page, routeFiles: string[]) => { + await Promise.all( + TEST_ROUTES.map(async (routeFile) => { + let locator = page.locator( + `[data-route-file="${routeFile}"] [data-mounted]` + ); + if (routeFiles.includes(routeFile)) { + await expect(locator).toBeAttached(); + } else { + // Assert no other routes are rendered + await expect(locator).not.toBeAttached(); + } + }) + ); }; test.describe(() => { - test.describe(async () => { - let cwd: string; - - test.beforeAll(async () => { - cwd = await createProject({ - "vite.config.ts": await VITE_CONFIG({ - port: -1, // Port only used for dev but we're testing the build - pluginOptions: `{ - unstable_serverBundles: async ({ branch }) => { - // Smoke test to ensure we can read the route files via 'route.file' - await Promise.all(branch.map(async (route) => { - const fs = await import("node:fs/promises"); - const routeFileContents = await fs.readFile(route.file, "utf8"); - if (!routeFileContents.includes(${JSON.stringify( - ROUTE_FILE_COMMENT - )})) { - throw new Error("Couldn't file route file test comment"); - } - })); - - if (branch.some((route) => route.id === "routes/_index")) { - return "root"; + let cwd: string; + + test.beforeAll(async () => { + cwd = await createProject({ + "vite.config.ts": await VITE_CONFIG({ + port: -1, // Port only used for dev but we're testing the build + pluginOptions: `{ + unstable_serverBundles: async ({ branch }) => { + // Smoke test to ensure we can read the route files via 'route.file' + await Promise.all(branch.map(async (route) => { + const fs = await import("node:fs/promises"); + const routeFileContents = await fs.readFile(route.file, "utf8"); + if (!routeFileContents.includes(${JSON.stringify( + ROUTE_FILE_COMMENT + )})) { + throw new Error("Couldn't file route file test comment"); } + })); - if (branch.some((route) => route.id === "routes/bundle-a")) { - return "bundle-a"; - } + if (branch.some((route) => route.id === "routes/_index")) { + return "root"; + } - if (branch.some((route) => route.id === "routes/bundle-b")) { - return "bundle-b"; - } + if (branch.some((route) => route.id === "routes/bundle-a")) { + return "bundle-a"; + } - if (branch.some((route) => route.id === "routes/_pathless.bundle-c")) { - return "bundle-c"; - } + if (branch.some((route) => route.id === "routes/bundle-b")) { + return "bundle-b"; + } - throw new Error("No bundle defined for route " + branch[branch.length - 1].id); + if (branch.some((route) => route.id === "routes/_pathless.bundle-c")) { + return "bundle-c"; } - }`, - }), - ...files, - }); - await viteBuild({ cwd }); + throw new Error("No bundle defined for route " + branch[branch.length - 1].id); + } + }`, + }), + ...files, }); - test("Vite / server bundles", async ({ page }) => { - let pageErrors: Error[] = []; - page.on("pageerror", (error) => pageErrors.push(error)); - - await withBundleServer(cwd, "root", async (port) => { - await page.goto(`http://localhost:${port}/`); - await expect( - page.locator('[data-route-file="_index.tsx"] [data-mounted]') - ).toBeVisible(); - - let _404s = ["/bundle-a", "/bundle-b", "/bundle-c"]; - for (let path of _404s) { - let response = await page.goto(`http://localhost:${port}${path}`); - expect(response?.status()).toBe(404); - } - }); - - await withBundleServer(cwd, "bundle-a", async (port) => { - await page.goto(`http://localhost:${port}/bundle-a`); - await expect( - page.locator('[data-route-file="bundle-a._index.tsx"] [data-mounted]') - ).toBeVisible(); - - await page.goto(`http://localhost:${port}/bundle-a`); - await expect( - page.locator('[data-route-file="bundle-a._index.tsx"] [data-mounted]') - ).toBeVisible(); - - await page.goto(`http://localhost:${port}/bundle-a/route-a`); - await expect( - page.locator( - '[data-route-file="bundle-a.route-a.tsx"] [data-mounted]' - ) - ).toBeVisible(); - - await page.goto(`http://localhost:${port}/bundle-a/route-b`); - await expect( - page.locator( - '[data-route-file="bundle-a.route-b.tsx"] [data-mounted]' - ) - ).toBeVisible(); - - let _404s = ["/bundle-b", "/bundle-c"]; - for (let path of _404s) { - let response = await page.goto(`http://localhost:${port}${path}`); - expect(response?.status()).toBe(404); - } - }); - - await withBundleServer(cwd, "bundle-b", async (port) => { - await page.goto(`http://localhost:${port}/bundle-b/route-a`); - await expect( - page.locator( - '[data-route-file="bundle-b.route-a.tsx"] [data-mounted]' - ) - ).toBeVisible(); - - await page.goto(`http://localhost:${port}/bundle-b/route-b`); - await expect( - page.locator( - '[data-route-file="bundle-b.route-b.tsx"] [data-mounted]' - ) - ).toBeVisible(); - - let _404s = ["/bundle-a", "/bundle-c"]; - for (let path of _404s) { - let response = await page.goto(`http://localhost:${port}${path}`); - expect(response?.status()).toBe(404); - } - }); - - await withBundleServer(cwd, "bundle-c", async (port) => { - await page.goto(`http://localhost:${port}/bundle-c/route-a`); - await expect( - page.locator('[data-route-file="_pathless.tsx"] [data-mounted]') - ).toBeVisible(); - await expect( - page.locator( - '[data-route-file="_pathless.bundle-c.route-a.tsx"] [data-mounted]' - ) - ).toBeVisible(); - - await page.goto(`http://localhost:${port}/bundle-c/route-b`); - await expect( - page.locator('[data-route-file="_pathless.tsx"] [data-mounted]') - ).toBeVisible(); - await expect( - page.locator( - '[data-route-file="_pathless.bundle-c.tsx"] [data-mounted]' - ) - ).toBeVisible(); - await expect( - page.locator( - '[data-route-file="_pathless.bundle-c.route-b.tsx"] [data-mounted]' - ) - ).toBeVisible(); - - let _404s = ["/bundle-a", "/bundle-b"]; - for (let path of _404s) { - let response = await page.goto(`http://localhost:${port}${path}`); - expect(response?.status()).toBe(404); - } - }); - - expect(pageErrors).toHaveLength(0); + await viteBuild({ cwd }); + }); + + test("Vite / server bundles", async ({ page }) => { + let pageErrors: Error[] = []; + page.on("pageerror", (error) => pageErrors.push(error)); + + await withBundleServer(cwd, "root", async (port) => { + await page.goto(`http://localhost:${port}/`); + await expectRenderedRoutes(page, ["_index.tsx"]); + + let _404s = ["/bundle-a", "/bundle-b", "/bundle-c"]; + for (let path of _404s) { + let response = await page.goto(`http://localhost:${port}${path}`); + expect(response?.status()).toBe(404); + } }); - test("Vite / server bundles / manifest", async () => { - expect( - JSON.parse( - fs.readFileSync(path.join(cwd, "build/server/bundles.json"), "utf8") - ) - ).toEqual({ - serverBundles: { - "bundle-c": { - id: "bundle-c", - file: "build/server/bundle-c/index.js", - }, - "bundle-a": { - id: "bundle-a", - file: "build/server/bundle-a/index.js", - }, - "bundle-b": { - id: "bundle-b", - file: "build/server/bundle-b/index.js", - }, - root: { - id: "root", - file: "build/server/root/index.js", - }, + await withBundleServer(cwd, "bundle-a", async (port) => { + await page.goto(`http://localhost:${port}/bundle-a`); + await expectRenderedRoutes(page, ["bundle-a.tsx", "bundle-a._index.tsx"]); + + await page.goto(`http://localhost:${port}/bundle-a/route-a`); + await expectRenderedRoutes(page, [ + "bundle-a.tsx", + "bundle-a.route-a.tsx", + ]); + + await page.goto(`http://localhost:${port}/bundle-a/route-b`); + await expectRenderedRoutes(page, [ + "bundle-a.tsx", + "bundle-a.route-b.tsx", + ]); + + let _404s = ["/bundle-b", "/bundle-c"]; + for (let path of _404s) { + let response = await page.goto(`http://localhost:${port}${path}`); + expect(response?.status()).toBe(404); + } + }); + + await withBundleServer(cwd, "bundle-b", async (port) => { + await page.goto(`http://localhost:${port}/bundle-b`); + await expectRenderedRoutes(page, ["bundle-b.tsx"]); + + await page.goto(`http://localhost:${port}/bundle-b/route-a`); + await expectRenderedRoutes(page, [ + "bundle-b.tsx", + "bundle-b.route-a.tsx", + ]); + + await page.goto(`http://localhost:${port}/bundle-b/route-b`); + await expectRenderedRoutes(page, [ + "bundle-b.tsx", + "bundle-b.route-b.tsx", + ]); + + let _404s = ["/bundle-a", "/bundle-c"]; + for (let path of _404s) { + let response = await page.goto(`http://localhost:${port}${path}`); + expect(response?.status()).toBe(404); + } + }); + + await withBundleServer(cwd, "bundle-c", async (port) => { + await page.goto(`http://localhost:${port}/bundle-c`); + await expectRenderedRoutes(page, [ + "_pathless.tsx", + "_pathless.bundle-c.tsx", + ]); + + await page.goto(`http://localhost:${port}/bundle-c/route-a`); + await expectRenderedRoutes(page, [ + "_pathless.tsx", + "_pathless.bundle-c.tsx", + "_pathless.bundle-c.route-a.tsx", + ]); + + await page.goto(`http://localhost:${port}/bundle-c/route-b`); + await expectRenderedRoutes(page, [ + "_pathless.tsx", + "_pathless.bundle-c.tsx", + "_pathless.bundle-c.route-b.tsx", + ]); + + let _404s = ["/bundle-a", "/bundle-b"]; + for (let path of _404s) { + let response = await page.goto(`http://localhost:${port}${path}`); + expect(response?.status()).toBe(404); + } + }); + + expect(pageErrors).toHaveLength(0); + }); + + test("Vite / server bundles / manifest", async () => { + expect( + JSON.parse( + fs.readFileSync(path.join(cwd, "build/server/bundles.json"), "utf8") + ) + ).toEqual({ + serverBundles: { + "bundle-c": { + id: "bundle-c", + file: "build/server/bundle-c/index.js", + }, + "bundle-a": { + id: "bundle-a", + file: "build/server/bundle-a/index.js", + }, + "bundle-b": { + id: "bundle-b", + file: "build/server/bundle-b/index.js", + }, + root: { + id: "root", + file: "build/server/root/index.js", + }, + }, + routeIdToBundleId: { + "routes/_pathless.bundle-c.route-a": "bundle-c", + "routes/_pathless.bundle-c.route-b": "bundle-c", + "routes/_pathless.bundle-c": "bundle-c", + "routes/bundle-a.route-a": "bundle-a", + "routes/bundle-a.route-b": "bundle-a", + "routes/bundle-b.route-a": "bundle-b", + "routes/bundle-b.route-b": "bundle-b", + "routes/bundle-a._index": "bundle-a", + "routes/bundle-b": "bundle-b", + "routes/_index": "root", + }, + routes: { + root: { + path: "", + id: "root", + file: "app/root.tsx", + }, + "routes/_pathless.bundle-c.route-a": { + file: "app/routes/_pathless.bundle-c.route-a.tsx", + id: "routes/_pathless.bundle-c.route-a", + path: "route-a", + parentId: "routes/_pathless.bundle-c", + }, + "routes/_pathless.bundle-c.route-b": { + file: "app/routes/_pathless.bundle-c.route-b.tsx", + id: "routes/_pathless.bundle-c.route-b", + path: "route-b", + parentId: "routes/_pathless.bundle-c", + }, + "routes/_pathless.bundle-c": { + file: "app/routes/_pathless.bundle-c.tsx", + id: "routes/_pathless.bundle-c", + path: "bundle-c", + parentId: "routes/_pathless", + }, + "routes/bundle-a.route-a": { + file: "app/routes/bundle-a.route-a.tsx", + id: "routes/bundle-a.route-a", + path: "route-a", + parentId: "routes/bundle-a", + }, + "routes/bundle-a.route-b": { + file: "app/routes/bundle-a.route-b.tsx", + id: "routes/bundle-a.route-b", + path: "route-b", + parentId: "routes/bundle-a", + }, + "routes/bundle-b.route-a": { + file: "app/routes/bundle-b.route-a.tsx", + id: "routes/bundle-b.route-a", + path: "route-a", + parentId: "routes/bundle-b", + }, + "routes/bundle-b.route-b": { + file: "app/routes/bundle-b.route-b.tsx", + id: "routes/bundle-b.route-b", + path: "route-b", + parentId: "routes/bundle-b", + }, + "routes/bundle-a._index": { + file: "app/routes/bundle-a._index.tsx", + id: "routes/bundle-a._index", + index: true, + parentId: "routes/bundle-a", + }, + "routes/_pathless": { + file: "app/routes/_pathless.tsx", + id: "routes/_pathless", + parentId: "root", + }, + "routes/bundle-a": { + file: "app/routes/bundle-a.tsx", + id: "routes/bundle-a", + path: "bundle-a", + parentId: "root", }, - routeIdToBundleId: { - "routes/_pathless.bundle-c.route-a": "bundle-c", - "routes/_pathless.bundle-c.route-b": "bundle-c", - "routes/_pathless.bundle-c": "bundle-c", - "routes/bundle-a.route-a": "bundle-a", - "routes/bundle-a.route-b": "bundle-a", - "routes/bundle-b.route-a": "bundle-b", - "routes/bundle-b.route-b": "bundle-b", - "routes/bundle-a._index": "bundle-a", - "routes/bundle-b": "bundle-b", - "routes/_index": "root", + "routes/bundle-b": { + file: "app/routes/bundle-b.tsx", + id: "routes/bundle-b", + path: "bundle-b", + parentId: "root", }, - routes: { - root: { - path: "", - id: "root", - file: "app/root.tsx", - }, - "routes/_pathless.bundle-c.route-a": { - file: "app/routes/_pathless.bundle-c.route-a.tsx", - id: "routes/_pathless.bundle-c.route-a", - path: "route-a", - parentId: "routes/_pathless.bundle-c", - }, - "routes/_pathless.bundle-c.route-b": { - file: "app/routes/_pathless.bundle-c.route-b.tsx", - id: "routes/_pathless.bundle-c.route-b", - path: "route-b", - parentId: "routes/_pathless.bundle-c", - }, - "routes/_pathless.bundle-c": { - file: "app/routes/_pathless.bundle-c.tsx", - id: "routes/_pathless.bundle-c", - path: "bundle-c", - parentId: "routes/_pathless", - }, - "routes/bundle-a.route-a": { - file: "app/routes/bundle-a.route-a.tsx", - id: "routes/bundle-a.route-a", - path: "route-a", - parentId: "routes/bundle-a", - }, - "routes/bundle-a.route-b": { - file: "app/routes/bundle-a.route-b.tsx", - id: "routes/bundle-a.route-b", - path: "route-b", - parentId: "routes/bundle-a", - }, - "routes/bundle-b.route-a": { - file: "app/routes/bundle-b.route-a.tsx", - id: "routes/bundle-b.route-a", - path: "route-a", - parentId: "routes/bundle-b", - }, - "routes/bundle-b.route-b": { - file: "app/routes/bundle-b.route-b.tsx", - id: "routes/bundle-b.route-b", - path: "route-b", - parentId: "routes/bundle-b", - }, - "routes/bundle-a._index": { - file: "app/routes/bundle-a._index.tsx", - id: "routes/bundle-a._index", - index: true, - parentId: "routes/bundle-a", - }, - "routes/_pathless": { - file: "app/routes/_pathless.tsx", - id: "routes/_pathless", - parentId: "root", - }, - "routes/bundle-a": { - file: "app/routes/bundle-a.tsx", - id: "routes/bundle-a", - path: "bundle-a", - parentId: "root", - }, - "routes/bundle-b": { - file: "app/routes/bundle-b.tsx", - id: "routes/bundle-b", - path: "bundle-b", - parentId: "root", - }, - "routes/_index": { - file: "app/routes/_index.tsx", - id: "routes/_index", - index: true, - parentId: "root", - }, + "routes/_index": { + file: "app/routes/_index.tsx", + id: "routes/_index", + index: true, + parentId: "root", }, - }); + }, }); }); }); From 63cd59e524058ebbb17d9cc51bf5a8f84982e7ae Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Wed, 20 Dec 2023 11:24:27 +1100 Subject: [PATCH 07/15] Normalize manifest paths with Vite --- packages/remix-dev/vite/build.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index c30075fc762..51ba08acdea 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -9,6 +9,7 @@ import type { } from "./plugin"; import type { ConfigRoute, RouteManifest } from "../config/routes"; import invariant from "../invariant"; +import { importViteEsmSync } from "./import-vite-esm-sync"; async function extractConfig({ configFile, @@ -79,10 +80,6 @@ function getRouteBranch(routes: RouteManifest, routeId: string) { return branch.reverse(); } -function normalizePath(filePath: string) { - return filePath.replace(/\\/g, "/"); -} - export type ServerBundlesManifest = { serverBundles: { [serverBundleId: string]: { @@ -109,6 +106,8 @@ async function getServerBundles({ return { serverBundles: [{ routes, serverBuildDirectory }] }; } + let { normalizePath } = importViteEsmSync(); + let resolvedAppDirectory = path.resolve(rootDirectory, appDirectory); let rootRelativeRoutes = Object.fromEntries( Object.entries(routes).map(([id, route]) => { From f515fcc340621fd8b0d66e3a53f9d66004043a89 Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Wed, 20 Dec 2023 11:51:34 +1100 Subject: [PATCH 08/15] Expose subset of route properties to serverBundles --- docs/future/server-bundles.md | 2 -- packages/remix-dev/vite/build.ts | 19 +++++++++++-------- packages/remix-dev/vite/plugin.ts | 15 ++++++++++++++- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/docs/future/server-bundles.md b/docs/future/server-bundles.md index bf2fb06def5..36bad43e4ba 100644 --- a/docs/future/server-bundles.md +++ b/docs/future/server-bundles.md @@ -39,8 +39,6 @@ Each `route` in the `branch` array contains the following properties: - `path` — The path this route uses to match on the URL pathname. - `file` — The absolute path to the entry point for this route. - `index` — Whether or not this route is an index route. -- `caseSensitive` — Whether or not the `path` is case-sensitive. -- `parentId` — The unique `id` for this route's parent route, if there is one. ## Server bundle manifest diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index 51ba08acdea..6a11d8d3411 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -3,9 +3,10 @@ import path from "node:path"; import fse from "fs-extra"; import colors from "picocolors"; -import type { - ResolvedRemixVitePluginConfig, - ServerBuildConfig, +import { + type ResolvedRemixVitePluginConfig, + type ServerBuildConfig, + configRouteToBranchRoute, } from "./plugin"; import type { ConfigRoute, RouteManifest } from "../config/routes"; import invariant from "../invariant"; @@ -131,11 +132,13 @@ async function getServerBundles({ getAddressableRoutes(routes).map(async (route) => { let branch = getRouteBranch(routes, route.id); let bundleId = await getServerBundles({ - branch: branch.map((route) => ({ - ...route, - // Ensure absolute paths are passed to the serverBundles function - file: path.join(resolvedAppDirectory, route.file), - })), + branch: branch.map((route) => + configRouteToBranchRoute({ + ...route, + // Ensure absolute paths are passed to the serverBundles function + file: path.join(resolvedAppDirectory, route.file), + }) + ), }); serverBundlesManifest.routeIdToBundleId[route.id] = bundleId; diff --git a/packages/remix-dev/vite/plugin.ts b/packages/remix-dev/vite/plugin.ts index f18ae1c472a..8056eeb2a41 100644 --- a/packages/remix-dev/vite/plugin.ts +++ b/packages/remix-dev/vite/plugin.ts @@ -77,8 +77,21 @@ type RemixConfigJsdocOverrides = { publicPath?: SupportedRemixConfig["publicPath"]; }; +// Only expose a subset of route properties to the "serverBundles" function +const branchRouteProperties = [ + "id", + "path", + "file", + "index", +] as const satisfies ReadonlyArray; +type BranchRoute = Pick; + +export const configRouteToBranchRoute = ( + configRoute: ConfigRoute +): BranchRoute => pick(configRoute, branchRouteProperties); + type ServerBundlesFunction = (args: { - branch: ConfigRoute[]; + branch: BranchRoute[]; }) => string | Promise; export type RemixVitePluginOptions = RemixConfigJsdocOverrides & From 2982018748b285b708add413c8fee7e784ee9549 Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Wed, 20 Dec 2023 11:58:45 +1100 Subject: [PATCH 09/15] Refactor --- packages/remix-dev/vite/build.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index 6a11d8d3411..639e9e4b478 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -92,19 +92,19 @@ export type ServerBundlesManifest = { routes: RouteManifest; }; -async function getServerBundles({ +async function getServerBuilds({ routes, serverBuildDirectory, serverBuildFile, - serverBundles: getServerBundles, + serverBundles, rootDirectory, appDirectory, }: ResolvedRemixVitePluginConfig): Promise<{ - serverBundles: ServerBuildConfig[]; + serverBuilds: ServerBuildConfig[]; serverBundlesManifest?: ServerBundlesManifest; }> { - if (!getServerBundles) { - return { serverBundles: [{ routes, serverBuildDirectory }] }; + if (!serverBundles) { + return { serverBuilds: [{ routes, serverBuildDirectory }] }; } let { normalizePath } = importViteEsmSync(); @@ -126,12 +126,12 @@ async function getServerBundles({ routes: rootRelativeRoutes, }; - let serverBundles = new Map(); + let serverBuildConfigByBundleId = new Map(); await Promise.all( getAddressableRoutes(routes).map(async (route) => { let branch = getRouteBranch(routes, route.id); - let bundleId = await getServerBundles({ + let bundleId = await serverBundles({ branch: branch.map((route) => configRouteToBranchRoute({ ...route, @@ -143,7 +143,7 @@ async function getServerBundles({ serverBundlesManifest.routeIdToBundleId[route.id] = bundleId; let serverBundleDirectory = path.join(serverBuildDirectory, bundleId); - let serverBuildConfig = serverBundles.get(bundleId); + let serverBuildConfig = serverBuildConfigByBundleId.get(bundleId); if (!serverBuildConfig) { serverBundlesManifest.serverBundles[bundleId] = { id: bundleId, @@ -155,7 +155,7 @@ async function getServerBundles({ routes: {}, serverBuildDirectory: serverBundleDirectory, }; - serverBundles.set(bundleId, serverBuildConfig); + serverBuildConfigByBundleId.set(bundleId, serverBuildConfig); } for (let route of branch) { serverBuildConfig.routes[route.id] = route; @@ -164,7 +164,7 @@ async function getServerBundles({ ); return { - serverBundles: Array.from(serverBundles.values()), + serverBuilds: Array.from(serverBuildConfigByBundleId.values()), serverBundlesManifest, }; } @@ -241,11 +241,11 @@ export async function build( await viteBuild(); // Then run Vite SSR builds in parallel - let { serverBundles, serverBundlesManifest } = await getServerBundles( + let { serverBuilds, serverBundlesManifest } = await getServerBuilds( pluginConfig ); - await Promise.all(serverBundles.map(viteBuild)); + await Promise.all(serverBuilds.map(viteBuild)); if (serverBundlesManifest) { await fse.writeFile( From 47f6411c35a6b46b5e8be0e38bcbdec838df9d2c Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Wed, 20 Dec 2023 12:14:55 +1100 Subject: [PATCH 10/15] Add JSDoc descriptions to new plugin options --- packages/remix-dev/vite/plugin.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/remix-dev/vite/plugin.ts b/packages/remix-dev/vite/plugin.ts index 8056eeb2a41..6ad91a0b0ff 100644 --- a/packages/remix-dev/vite/plugin.ts +++ b/packages/remix-dev/vite/plugin.ts @@ -97,10 +97,22 @@ type ServerBundlesFunction = (args: { export type RemixVitePluginOptions = RemixConfigJsdocOverrides & Omit & { /** - * TODO: Add descriptions + * The path to the server build directory, relative to the project. This + * directory should be deployed to your server. Defaults to + * `"build/server"`. */ serverBuildDirectory?: string; + /** + * The file name of the server build output. This file + * should end in a `.js` extension and should be deployed to your server. + * Defaults to `"index.js"`. + */ serverBuildFile?: string; + /** + * A function for assigning routes to different server bundles. This + * function should return a server bundle ID which will be used as the + * bundle's directory name within the server build directory. + */ unstable_serverBundles?: ServerBundlesFunction; }; @@ -117,9 +129,6 @@ export type ResolvedRemixVitePluginConfig = Pick< | "routes" | "serverModuleFormat" > & { - /** - * TODO: Add descriptions - */ serverBuildDirectory: string; serverBuildFile: string; serverBundles?: ServerBundlesFunction; From 78235b2e687ee296088065d3eacd6ed98e58c9d5 Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Wed, 20 Dec 2023 12:58:36 +1100 Subject: [PATCH 11/15] Tweak docs formatting, fix highlighted lines --- docs/future/server-bundles.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/future/server-bundles.md b/docs/future/server-bundles.md index 36bad43e4ba..f385d528e3f 100644 --- a/docs/future/server-bundles.md +++ b/docs/future/server-bundles.md @@ -12,7 +12,7 @@ The provided `unstable_serverBundles` function is called for each route in the t For each route, this function is passed an array of routes leading to and including that route, referred to as the route `branch`. This allows you to create server bundles for different portions of the route tree. For example, you could use this to create a separate server bundle containing all routes within a particular layout route: -```ts filename=vite.config.ts lines=[7-10] +```ts filename=vite.config.ts lines=[7-15] import { unstable_vitePlugin as remix } from "@remix-run/dev"; import { defineConfig } from "vite"; @@ -44,9 +44,9 @@ Each `route` in the `branch` array contains the following properties: When the build is complete, Remix will generate a `bundles.json` manifest file in your server build directory containing an object with the following properties: -- `serverBundles` — An object mapping bundle IDs to an object containing the bundle's `id` and `file`. -- `routeIdToServerBundleId` — An object mapping route IDs to server bundle ID. -- `routes` — A route manifest mapping route IDs to route metadata. This can be used to drive a custom routing layer in front of your Remix request handlers. +- `serverBundles` — An object that maps bundle IDs to the bundle's `id` and `file`. +- `routeIdToServerBundleId` — An object that maps route IDs to its server bundle ID. +- `routes` — A route manifest that maps route IDs to route metadata. This can be used to drive a custom routing layer in front of your Remix request handlers. [remix-vite]: ./vite.md [pathless-layout-route]: ../file-conventions/routes#nested-layouts-without-nested-urls From 282d9ebcee55bacf38433771c3a494f7b1235d29 Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Wed, 20 Dec 2023 14:35:13 +1100 Subject: [PATCH 12/15] Add changeset --- .changeset/flat-toys-hope.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .changeset/flat-toys-hope.md diff --git a/.changeset/flat-toys-hope.md b/.changeset/flat-toys-hope.md new file mode 100644 index 00000000000..ade0e6982c3 --- /dev/null +++ b/.changeset/flat-toys-hope.md @@ -0,0 +1,30 @@ +--- +"@remix-run/dev": patch +--- + +Add `unstable_serverBundles` option to Vite plugin to support splitting server code into multiple request handlers. + +This is an advanced feature designed for hosting provider integrations. When compiling your app into multiple server bundles, there will need to be a custom routing layer in front of your app directing requests to the correct bundle. This feature is currently unstable and only designed to gather early feedback. + +**Example usage:** + +```ts +import { unstable_vitePlugin as remix } from "@remix-run/dev"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [ + remix({ + unstable_serverBundles: ({ branch }) => { + const isAuthenticatedRoute = branch.some( + (route) => route.id === "routes/_authenticated" + ); + + return isAuthenticatedRoute + ? "authenticated" + : "unauthenticated"; + }, + }), + ], +}); +``` From ce3e407576cd69b7890653eb04556e5c5a9cbf34 Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Thu, 21 Dec 2023 11:29:38 +1100 Subject: [PATCH 13/15] Fix Vite sync import error --- packages/remix-dev/vite/build.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index 639e9e4b478..892fe28ea68 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -107,7 +107,7 @@ async function getServerBuilds({ return { serverBuilds: [{ routes, serverBuildDirectory }] }; } - let { normalizePath } = importViteEsmSync(); + let { normalizePath } = await import("vite"); let resolvedAppDirectory = path.resolve(rootDirectory, appDirectory); let rootRelativeRoutes = Object.fromEntries( From 3340871d7062fb787bfc1bf44f145555f6d51b65 Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Thu, 21 Dec 2023 11:30:13 +1100 Subject: [PATCH 14/15] Throw error when bundle ID isn't a string --- packages/remix-dev/vite/build.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/remix-dev/vite/build.ts b/packages/remix-dev/vite/build.ts index 892fe28ea68..1569d186d03 100644 --- a/packages/remix-dev/vite/build.ts +++ b/packages/remix-dev/vite/build.ts @@ -10,7 +10,6 @@ import { } from "./plugin"; import type { ConfigRoute, RouteManifest } from "../config/routes"; import invariant from "../invariant"; -import { importViteEsmSync } from "./import-vite-esm-sync"; async function extractConfig({ configFile, @@ -140,6 +139,11 @@ async function getServerBuilds({ }) ), }); + if (typeof bundleId !== "string") { + throw new Error( + `The "unstable_serverBundles" function must return a string` + ); + } serverBundlesManifest.routeIdToBundleId[route.id] = bundleId; let serverBundleDirectory = path.join(serverBuildDirectory, bundleId); From a1a41b5493ac10a3fb24278bfc46ba1e6395918d Mon Sep 17 00:00:00 2001 From: Mark Dalgleish Date: Fri, 22 Dec 2023 07:27:54 +1100 Subject: [PATCH 15/15] Bump to minor release --- .changeset/flat-toys-hope.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/flat-toys-hope.md b/.changeset/flat-toys-hope.md index ade0e6982c3..deb48581f62 100644 --- a/.changeset/flat-toys-hope.md +++ b/.changeset/flat-toys-hope.md @@ -1,5 +1,5 @@ --- -"@remix-run/dev": patch +"@remix-run/dev": minor --- Add `unstable_serverBundles` option to Vite plugin to support splitting server code into multiple request handlers.