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

ctual work: #7

Merged
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
4 changes: 2 additions & 2 deletions packages/vinxi-references/server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readFileSync } from "fs";
import { join } from "vinxi/lib/path";
import { handlerModule, join } from "vinxi/lib/path";

import { CLIENT_REFERENCES_MANIFEST, hash } from "./constants.js";

Expand Down Expand Up @@ -37,7 +37,7 @@ export function server({
);

input = {
entry: "#vinxi/handler",
entry: handlerModule(router),
...Object.fromEntries(
reactClientManifest.server.map((key) => {
return [`c_${hash(key)}`, key];
Expand Down
53 changes: 27 additions & 26 deletions packages/vinxi/lib/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { createIncomingMessage, createServerResponse } from "./http-stream.js";
import invariant from "./invariant.js";
import { consola, withLogger } from "./logger.js";
import { createSPAManifest } from "./manifest/spa-manifest.js";
import { join, relative } from "./path.js";
import { handlerModule, join, relative, virtualId } from "./path.js";
import { config } from "./plugins/config.js";
import { manifest } from "./plugins/manifest.js";
import { routes } from "./plugins/routes.js";
Expand Down Expand Up @@ -79,19 +79,22 @@ export async function createBuild(app, buildConfig) {
...app.config.routers
.map((router) => {
if (router.mode === "handler") {
invariant(router.handler, "Missing router.handler");
const bundlerManifest = JSON.parse(
readFileSync(
join(router.outDir, router.base, ".vite", "manifest.json"),
"utf-8",
),
);

const virtualHandlerId = virtualId(handlerModule(router));

const handler = join(
router.outDir,
router.base,
bundlerManifest[
"virtual:#vinxi/handler" in bundlerManifest
? "virtual:#vinxi/handler"
virtualHandlerId in bundlerManifest
? virtualHandlerId
: relative(app.config.root, router.handler)
].file,
);
Expand Down Expand Up @@ -121,6 +124,7 @@ export async function createBuild(app, buildConfig) {
.map((router) => {
if (router.mode === "static") {
return {
// @ts-expect-error
dir: router.dir,
baseURL: router.base,
passthrough: true,
Expand Down Expand Up @@ -291,7 +295,7 @@ async function createViteBuild(config) {
/**
*
* @param {import("./app.js").App} app
* @param {Exclude<import("./router-modes.js").RouterSchema, import("./router-modes.js").StaticRouterSchema>} router
* @param {import("./router-mode.js").Router} router
*/
async function createRouterBuild(app, router) {
let buildRouter = router;
Expand Down Expand Up @@ -347,9 +351,9 @@ async function createRouterBuild(app, router) {
router: buildRouter,
app,
plugins: [
routerModePlugin[buildRouter.internals.mode.name]?.() ?? [],
buildTargetPlugin[buildRouter.target]?.() ?? [],
...((await buildRouter.plugins?.()) ?? []),
routerModePlugin[buildRouter.internals.mode.name]?.(buildRouter) ?? [],
buildTargetPlugin[buildRouter.target]?.(buildRouter) ?? [],
...((await buildRouter.plugins?.(buildRouter)) ?? []),
],
});

Expand Down Expand Up @@ -409,10 +413,10 @@ const spaManifest = () => {

const routerModePlugin = {
static: () => [],
build: () => [
build: (router) => [
virtual(
{
"#vinxi/handler": ({ config }) => {
[handlerModule(router)]: ({ config }) => {
invariant(
config.router.mode === "build",
"#vinxi/handler is only supported in build mode",
Expand Down Expand Up @@ -444,10 +448,10 @@ const routerModePlugin = {
},
}),
],
handler: () => [
handler: (router) => [
virtual(
{
"#vinxi/handler": ({ config }) => {
[handlerModule(router)]: ({ config }) => {
invariant(
config.router.mode === "handler",
"#vinxi/handler is only supported in handler mode",
Expand Down Expand Up @@ -520,12 +524,12 @@ function toRouteId(route) {

/**
*
* @param {Exclude<import("./router-modes.js").RouterSchema, import("./router-modes.js").StaticRouterSchema>} router
* @param {import("./router-mode.js").Router<{ handler: string }>} router
* @returns
*/
export async function getEntries(router) {
return [
router.handler.endsWith(".html") ? router.handler : "#vinxi/handler",
router.handler.endsWith(".html") ? router.handler : handlerModule(router),
...(
(await router.internals.routes?.getRoutes())?.map((r) =>
Object.entries(r)
Expand All @@ -542,15 +546,15 @@ export async function getEntries(router) {
function handerBuild() {
return {
name: "react-rsc:handler",
async config(inlineConfig, env) {
async config({ router }, env) {
if (env.command === "build") {
invariant(
inlineConfig.router && inlineConfig.router.mode !== "static",
router && router.mode !== "static" && router.handler,
"Invalid router",
);
const { builtinModules } = await import("module");
const { join } = await import("./path.js");
const input = await getEntries(inlineConfig.router);
const input = await getEntries(router);
return {
build: {
rollupOptions: {
Expand All @@ -565,10 +569,10 @@ function handerBuild() {
manifest: true,
target: "node18",
ssrEmitAssets: true,
outDir: join(inlineConfig.router.outDir, inlineConfig.router.base),
outDir: join(router.outDir, router.base),
emptyOutDir: false,
},
base: inlineConfig.router.base,
base: router.base,
publicDir: false,
};
}
Expand All @@ -582,25 +586,22 @@ function handerBuild() {
function browserBuild() {
return {
name: "build:browser",
async config(inlineConfig, env) {
async config({ router }, env) {
if (env.command === "build") {
invariant(
inlineConfig.router && inlineConfig.router.mode !== "static",
"Invalid router",
);
invariant(router && router.mode !== "static", "Invalid router");
const { join } = await import("./path.js");
return {
build: {
rollupOptions: {
input: await getEntries(inlineConfig.router),
input: await getEntries(router),
treeshake: true,
},
manifest: true,
outDir: join(inlineConfig.router.outDir, inlineConfig.router.base),
outDir: join(router.outDir, router.base),
target: "esnext",
emptyOutDir: false,
},
base: inlineConfig.router.base,
base: router.base,
publicDir: false,
};
}
Expand Down
13 changes: 7 additions & 6 deletions packages/vinxi/lib/manifest/client-manifest.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
/// <reference types="vite/client" />
/// <reference types="./client" />
/// <reference types="../../types/client" />
import { invariant } from "../invariant";
import { join } from "../path.js";
import { handlerModule, join, virtualId } from "../path.js";

const manifest = new Proxy(
{},
{
get(target, bundlerName) {
get(target, routerName) {
invariant(
typeof bundlerName === "string",
typeof routerName === "string",
"Bundler name should be a string",
);
return {
handler: import.meta.env.DEV
? join(import.meta.env.CWD, import.meta.env.ROUTER_HANDLER)
: "virtual:#vinxi/handler",
: // @ts-ignore
virtualId(handlerModule({ name: routerName })),
chunks: new Proxy(
{},
{
Expand Down Expand Up @@ -46,7 +47,7 @@ const manifest = new Proxy(
const assetsPath =
join(
import.meta.env.BASE_URL,
`@manifest/${bundlerName}/${Date.now()}/assets`,
`@manifest/${routerName}/${Date.now()}/assets`,
) + `?id=${input}`;
return (await import(/* @vite-ignore */ assetsPath))
.default;
Expand Down
8 changes: 5 additions & 3 deletions packages/vinxi/lib/manifest/prod-server-manifest.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import invariant from "vinxi/lib/invariant";
import { join } from "vinxi/lib/path";
import { handlerModule, join, virtualId } from "vinxi/lib/path";

import findAssetsInViteManifest from "./vite-manifest.js";

Expand Down Expand Up @@ -84,7 +84,9 @@ export function createProdManifest(app) {
const id = input;
if (router.target === "server") {
const id =
input === router.handler ? "virtual:#vinxi/handler" : input;
input === router.handler
? virtualId(handlerModule(router))
: input;
return {
assets() {
return findAssetsInViteManifest(bundlerManifest, id)
Expand All @@ -110,7 +112,7 @@ export function createProdManifest(app) {
} else if (router.target === "browser") {
const id =
input === router.handler && !input.endsWith(".html")
? "virtual:#vinxi/handler"
? virtualId(handlerModule(router))
: input;
return {
assets() {
Expand Down
10 changes: 10 additions & 0 deletions packages/vinxi/lib/path.js
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
export * from "pathe";

export function virtualId(/** @type {string} */ moduleName) {
return `virtual:${moduleName}`;
}

export function handlerModule(
/** @type {import("./router-mode").Router} */ router,
) {
return `#vinxi/handler/${router.name}`;
}
32 changes: 16 additions & 16 deletions packages/vinxi/lib/router-dev-plugins.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { devEntries } from "./dev-server.js";
import invariant from "./invariant.js";
import { join } from "./path.js";
import { handlerModule, join } from "./path.js";
import { config } from "./plugins/config.js";
import { css } from "./plugins/css.js";
import { fileSystemWatcher } from "./plugins/fs-watcher.js";
Expand Down Expand Up @@ -34,21 +34,24 @@ export const ROUTER_MODE_DEV_PLUGINS = {
/** @type {import("./router-modes.js").HandlerRouterSchema} */ router,
) => [
virtual({
"#vinxi/handler": ({ config }) => {
// invariant(
// config.router.mode === "handler",
// "#vinxi/handler is only supported in handler mode",
// );
if (config.router.middleware) {
[handlerModule(router)]: ({ config }) => {
/** @type {import("./router-mode.js").Router<{ middleware?: string; }>} */
const router = config.router;
invariant(
router.handler === "handler",
"#vinxi/handler is only supported in handler mode",
);

if (router.middleware) {
return `
import middleware from "${join(config.router.root, config.router.middleware)}";
import handler from "${join(config.router.root, config.router.handler)}";
import middleware from "${join(router.root, router.middleware)}";
import handler from "${join(router.root, router.handler)}";
import { eventHandler } from "vinxi/server";
export default eventHandler({ onRequest: middleware.onRequest, onBeforeResponse: middleware.onBeforeResponse, handler});`;
}
return `import handler from "${join(
config.router.root,
config.router.handler,
router.root,
router.handler,
)}"; export default handler;`;
},
}),
Expand Down Expand Up @@ -76,11 +79,8 @@ export const ROUTER_MODE_DEV_PLUGINS = {
css(),
virtual(
{
"#vinxi/handler": ({ config }) => {
invariant(
config.router.mode === "build",
"#vinxi/handler is only supported in build mode",
);
[handlerModule(router)]: ({ config }) => {
invariant(config.router.handler, "");
return `import * as mod from "${join(
config.router.root,
config.router.handler,
Expand Down
1 change: 1 addition & 0 deletions packages/vinxi/lib/router-mode.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type DevHandler = {

type Router<T = {}> = T & {
base: string;
mode: string;
internals: Internals;
order: number;
outDir: string;
Expand Down
28 changes: 4 additions & 24 deletions packages/vinxi/lib/router-modes.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const spaRouterSchema = v.object({
routes: v.optional(v.custom((value) => value !== null)),
handler: v.string(),
outDir: v.string().optional(),
target: v.literal("browser"),
target: v.literal("browser").optional().default("browser"),
plugins: v.optional(v.custom((value) => typeof value === "function")),
});
const customRouterSchema = v.object({
Expand Down Expand Up @@ -148,10 +148,6 @@ const routerModes = {
return {
route: router.base,
handler: eventHandler({
onRequest: async (event) => {
setHeader(event, "Cross-Origin-Embedder-Policy", "require-corp");
setHeader(event, "Cross-Origin-Opener-Policy", "same-origin");
},
handler: fromNodeMiddleware(viteDevServer.middlewares),
}),
};
Expand Down Expand Up @@ -227,10 +223,10 @@ const routerModes = {
}

const { createViteHandler } = await import("./dev-server.js");
const viteDevServer = await createViteHandler(router, app, serveConfig);
const viteServer = await createViteHandler(router, app, serveConfig);
const handler = eventHandler(async (event) => {
const { default: handler } = await viteDevServer.ssrLoadModule(
"#vinxi/handler",
const { default: handler } = await viteServer.ssrLoadModule(
router.handler,
);
return handler(event);
});
Expand Down Expand Up @@ -303,28 +299,12 @@ const routerModes = {
{
route: `${router.base}/**`,
handler: defineEventHandler({
onRequest: async (event) => {
setHeader(
event,
"Cross-Origin-Embedder-Policy",
"require-corp",
);
setHeader(event, "Cross-Origin-Opener-Policy", "same-origin");
},
handler: fromNodeMiddleware(viteDevServer.middlewares),
}),
},
{
route: router.base,
handler: defineEventHandler({
onRequest: async (event) => {
setHeader(
event,
"Cross-Origin-Embedder-Policy",
"require-corp",
);
setHeader(event, "Cross-Origin-Opener-Policy", "same-origin");
},
handler: fromNodeMiddleware(viteDevServer.middlewares),
}),
},
Expand Down
Loading