@netlify/remix-adapter
Version:
Remix Adapter for Netlify Functions
96 lines (92 loc) • 3.09 kB
JavaScript
// src/vite/plugin.ts
import { mkdir, writeFile } from "node:fs/promises";
import { join, relative, sep } from "node:path";
import { sep as posixSep } from "node:path/posix";
// package.json
var name = "@netlify/remix-adapter";
var version = "2.6.1";
// src/vite/plugin.ts
var NETLIFY_FUNCTIONS_DIR = ".netlify/functions-internal";
var FUNCTION_FILENAME = "remix-server.mjs";
var FUNCTION_HANDLER_CHUNK = "server";
var FUNCTION_HANDLER_MODULE_ID = "virtual:netlify-server";
var RESOLVED_FUNCTION_HANDLER_MODULE_ID = `\0${FUNCTION_HANDLER_MODULE_ID}`;
var toPosixPath = (path) => path.split(sep).join(posixSep);
var FUNCTION_HANDLER = (
/* js */
`
import { createRequestHandler } from "@netlify/remix-adapter";
import * as build from "virtual:remix/server-build";
export default createRequestHandler({
build,
getLoadContext: async (_req, ctx) => ctx,
});
`
);
function generateNetlifyFunction(handlerPath) {
return (
/* js */
`
export { default } from "${handlerPath}";
export const config = {
name: "Remix server handler",
generator: "${name}@${version}",
path: "/*",
preferStatic: true,
};
`
);
}
function netlifyPlugin() {
let resolvedConfig;
let currentCommand;
let isSsr;
return {
name: "vite-plugin-remix-netlify-functions",
config(config, { command, isSsrBuild }) {
var _a, _b;
currentCommand = command;
isSsr = isSsrBuild;
if (command === "build") {
if (isSsrBuild) {
if (typeof ((_b = (_a = config.build) == null ? void 0 : _a.rollupOptions) == null ? void 0 : _b.input) === "string") {
config.build.rollupOptions.input = {
[FUNCTION_HANDLER_CHUNK]: FUNCTION_HANDLER_MODULE_ID,
index: config.build.rollupOptions.input
};
if (config.build.rollupOptions.output && !Array.isArray(config.build.rollupOptions.output)) {
config.build.rollupOptions.output.entryFileNames = "[name].js";
}
}
}
}
},
async resolveId(source) {
if (source === FUNCTION_HANDLER_MODULE_ID) {
return RESOLVED_FUNCTION_HANDLER_MODULE_ID;
}
},
// See https://vitejs.dev/guide/api-plugin#virtual-modules-convention.
load(id) {
if (id === RESOLVED_FUNCTION_HANDLER_MODULE_ID) {
return FUNCTION_HANDLER;
}
},
async configResolved(config) {
resolvedConfig = config;
},
// See https://rollupjs.org/plugin-development/#writebundle.
async writeBundle() {
if (currentCommand === "build" && isSsr) {
const functionsDirectory = join(resolvedConfig.root, NETLIFY_FUNCTIONS_DIR);
await mkdir(functionsDirectory, { recursive: true });
const handlerPath = join(resolvedConfig.build.outDir, `${FUNCTION_HANDLER_CHUNK}.js`);
const relativeHandlerPath = toPosixPath(relative(functionsDirectory, handlerPath));
await writeFile(join(functionsDirectory, FUNCTION_FILENAME), generateNetlifyFunction(relativeHandlerPath));
}
}
};
}
export {
netlifyPlugin
};