Skip to content
Draft
Show file tree
Hide file tree
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
7 changes: 7 additions & 0 deletions .changeset/astro-render-boot-uxf-916.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@unframework.dev/target-astro": patch
---

Start the render server when Vitest configures an Astro browser project, before any test runs. A host outside Vitest, like the preview, still starts it on the first render.

The server used to start on the first render, so the first test of each spec file waited for it. In a busy run, that start took up to 75 seconds, and those tests timed out.
6 changes: 4 additions & 2 deletions packages/target-astro/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,10 @@ Its toolchain, for tests and tooling (the target's main entry never loads it):
(`ToolchainContext.plugins`), so a styling engine's plugin resolves its `virtual:` modules,
and the engine's stylesheet goes before the markup too (ADR-0064). A module of composables a
component imports (`/abs/useToggle.uf.ts`, ADR-0069) is served as the browser project compiles
it, read again on each render. The toolchain names that command as `renderCommandName`, and
`close()` stops its render servers. The mount adapter (`/toolchain/client`) renders through
it, read again on each render. In a Vitest browser project, the render server starts when
Vitest configures the project, before any test runs, so no test waits for the start. Another
host, like the preview, starts it on the first render. The toolchain names that command as
`renderCommandName`, and `close()` stops its render servers. The mount adapter (`/toolchain/client`) renders through
`MountOptions.renderCommand` when a host outside Vitest passes one, like the preview, which runs
the command behind an endpoint of its own (ADR-0088), and through Vitest's command otherwise.
The checks:
Expand Down
13 changes: 10 additions & 3 deletions packages/target-astro/src/toolchain/browser.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { ToolchainContext } from "@unframework.dev/codegen";
// Vitest's `Plugin` is Vite's, with the `configureVitest` hook declared.
import type { Plugin } from "vitest/config";

import { ASTRO_VIRTUAL_ID, astroComponentRef } from "./protocol.ts";
import { closeAstroRenderServers } from "./render.ts";
import { closeAstroRenderServers, startAstroRenderServer } from "./render.ts";
import { recordAstroSource } from "./sources.ts";

/**
Expand All @@ -12,9 +13,12 @@ import { recordAstroSource } from "./sources.ts";
*
* It records the Astro source the unframework plugin loaded for each virtual id, then replaces
* the module with a serialisable reference (`AstroComponentRef`) that the mount adapter sends to
* `ufAstroRender`. When Vitest closes, it closes the render servers.
* `ufAstroRender`. When Vitest configures the project, it starts the render server for the
* context's root, with the context's plugins, so no test waits for the start (UXF-916); without
* a context, the first render starts it. When Vitest closes, it closes the render servers.
* Outside Vitest, as in the preview (ADR-0088), the hook never runs, and nothing starts early.
*/
export function astroBrowserRef(): Plugin {
export function astroBrowserRef(context?: Pick<ToolchainContext, "root" | "plugins">): Plugin {
return {
name: "unframework:astro-browser-ref",
enforce: "pre",
Expand All @@ -28,6 +32,9 @@ export function astroBrowserRef(): Plugin {
},
configureVitest({ vitest }) {
vitest.onClose(closeAstroRenderServers);
if (context) {
startAstroRenderServer(context.root, context.plugins);
}
},
};
}
5 changes: 3 additions & 2 deletions packages/target-astro/src/toolchain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ export const toolchain: Toolchain = {
return astroViteConfig(context.root);
}
// Nothing to pre-bundle: in the browser a compiled component is a plain reference that
// imports nothing, and the unframework plugin keeps virtual ids out of the dep scan.
return { plugins: [astroBrowserRef()] };
// imports nothing, and the unframework plugin keeps virtual ids out of the dep scan. The
// plugin starts the render server when Vitest configures the project, for the context's root.
return { plugins: [astroBrowserRef(context)] };
},
browserCommands: (context) => ({ ufAstroRender: createAstroRenderCommand(context) }),
renderCommandName: "ufAstroRender",
Expand Down
13 changes: 13 additions & 0 deletions packages/target-astro/src/toolchain/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,19 @@ function invalidate(ssr: RunnableDevEnvironment, id: string): void {
}
}

/**
* Starts the render server for a root now, rather than on the first render (UXF-916). A Vitest
* browser project calls it when Vitest configures the project (`astroBrowserRef`), so the start
* runs before any test, not inside the first test's render, where every Astro file that waits
* in the render queue would pay for it under a busy run. The first render awaits the same
* server; a server that fails to start fails that render with its error, as a lazy start does.
*/
export function startAstroRenderServer(root: string, plugins?: () => Promise<Array<Plugin>>): void {
// Handled here so a failed start with no render yet is not an unhandled rejection: the render
// that awaits the server still rejects with the error.
renderServer(root, plugins).catch(() => undefined);
}

function renderServer(
root: string,
plugins: (() => Promise<Array<Plugin>>) | undefined,
Expand Down
115 changes: 115 additions & 0 deletions packages/target-astro/test/render-boot.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// When the render server starts (UXF-916): a Vitest browser project starts it when Vitest
// configures the project, so no test's render waits for the start in the render queue.
import { mkdirSync, rmSync } from "node:fs";
import { join } from "node:path";

import type { Plugin } from "vite";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";

import { astroBrowserRef } from "../src/toolchain/browser.ts";
import { closeAstroRenderServers, renderAstroComponent } from "../src/toolchain/render.ts";

const base = join(import.meta.dirname, "..", ".uf-tmp", `render-boot-${process.pid}`);

/** A browser project's plugin, as Vitest configures it: only `vitest.onClose` is read. */
function configure(plugin: Plugin): ReturnType<typeof vi.fn> {
const onClose = vi.fn();
const hook = plugin.configureVitest as unknown as (context: {
vitest: { onClose: (close: () => unknown) => void };
}) => void;
hook({ vitest: { onClose } });
return onClose;
}

/** What a browser project does when it imports a component: the ref plugin's transform. */
function compile(plugin: Plugin, id: string, source: string): void {
const transform = plugin.transform as { handler(code: string, id: string): unknown };
transform.handler.call(undefined, source, id);
}

/**
* The project's plugins, as `ToolchainContext.plugins`: the render server asks for them once,
* as it starts, so each call is one server start.
*/
function projectPlugins(start?: () => void) {
return vi.fn(async (): Promise<Array<Plugin>> => {
start?.();
return [];
});
}

describe("the render server's start", { timeout: 60_000 }, () => {
beforeAll(() => mkdirSync(base, { recursive: true }));
afterAll(async () => {
await closeAstroRenderServers();
rmSync(base, { recursive: true, force: true });
});

it("starts when Vitest configures the browser project, before any render asks for it", async () => {
const root = join(base, "eager");
mkdirSync(root, { recursive: true });
const plugins = projectPlugins();
const plugin = astroBrowserRef({ root, plugins });
const onClose = configure(plugin);
expect(onClose).toHaveBeenCalledWith(closeAstroRenderServers);
// No render was asked for: only the configure hook can have started the server.
await vi.waitFor(() => expect(plugins).toHaveBeenCalledTimes(1), { timeout: 30_000 });

const id = join(root, "Hello.uf.tsx.astro");
compile(plugin, id, "<p>hello</p>\n");
const result = await renderAstroComponent(root, { id, props: {} }, undefined, plugins);
expect(result).toEqual({ html: "<p>hello</p>", console: [] });
// The render used the server the configure hook started, and started no second one.
expect(plugins).toHaveBeenCalledTimes(1);
});

it("starts one server for two projects on one root, as browser:astro and hydrate:astro are", async () => {
const root = join(base, "shared");
mkdirSync(root, { recursive: true });
const browser = projectPlugins();
const hydrate = projectPlugins();
configure(astroBrowserRef({ root, plugins: browser }));
configure(astroBrowserRef({ root, plugins: hydrate }));
await vi.waitFor(() => expect(browser).toHaveBeenCalledTimes(1), { timeout: 30_000 });
expect(hydrate).not.toHaveBeenCalled();
});

it("fails the first render with the error of a start that failed, and raises nothing before", async () => {
const root = join(base, "broken");
mkdirSync(root, { recursive: true });
const plugins = projectPlugins(() => {
throw new Error("the styling engine's plugin cannot load");
});
const plugin = astroBrowserRef({ root, plugins });
configure(plugin);
await vi.waitFor(() => expect(plugins).toHaveBeenCalledTimes(1), { timeout: 30_000 });
// A rejection nobody handled yet would fail this file as an unhandled error here.
await new Promise((resolve) => {
setTimeout(resolve, 50);
});

const id = join(root, "Hello.uf.tsx.astro");
compile(plugin, id, "<p>hello</p>\n");
await expect(renderAstroComponent(root, { id, props: {} }, undefined, plugins)).rejects.toThrow(
"the styling engine's plugin cannot load",
);
});

it("starts nothing for a plugin made without a context, until the first render", async () => {
const root = join(base, "lazy");
mkdirSync(root, { recursive: true });
const plugins = projectPlugins();
const plugin = astroBrowserRef();
configure(plugin);
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
expect(plugins).not.toHaveBeenCalled();

const id = join(root, "Hello.uf.tsx.astro");
compile(plugin, id, "<p>lazy</p>\n");
const result = await renderAstroComponent(root, { id, props: {} }, undefined, plugins);
expect(result.html).toBe("<p>lazy</p>");
expect(plugins).toHaveBeenCalledTimes(1);
});
});
Loading