0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-13 22:11:20 -05:00
astro/packages/integrations/vercel/src/index.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

73 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-03-28 10:05:55 -03:00
import type { AstroIntegration, AstroConfig } from 'astro';
import fs from 'fs/promises';
import type { PathLike } from 'fs';
2022-03-28 15:13:14 -03:00
import { fileURLToPath } from 'url';
import { globby } from 'globby';
import esbuild from 'esbuild';
2022-03-28 10:05:55 -03:00
export type { VercelApiHandler, VercelRequest, VercelRequestBody, VercelRequestCookies, VercelRequestQuery, VercelResponse } from '@vercel/node';
const writeJson = (path: PathLike, data: any) => fs.writeFile(path, JSON.stringify(data), { encoding: 'utf-8' });
2022-03-28 15:13:14 -03:00
const ENDPOINT_GLOB = 'api/**/*.{js,ts,tsx}';
2022-03-28 10:05:55 -03:00
export function vercelFunctions(): AstroIntegration {
let _config: AstroConfig;
let output: URL;
2022-03-28 15:13:14 -03:00
2022-03-28 10:05:55 -03:00
return {
name: '@astrojs/vercel',
hooks: {
2022-03-28 15:13:14 -03:00
'astro:config:setup': ({ config, ignorePages }) => {
2022-03-28 10:05:55 -03:00
output = new URL('./.output/', config.projectRoot);
config.dist = new URL('./static/', output);
config.buildOptions.pageUrlFormat = 'directory';
2022-03-28 15:13:14 -03:00
ignorePages(ENDPOINT_GLOB);
2022-03-28 10:05:55 -03:00
},
2022-03-28 15:13:14 -03:00
'astro:config:done': async ({ config }) => {
2022-03-28 10:05:55 -03:00
_config = config;
},
'astro:build:start': async () => {
2022-03-28 15:13:14 -03:00
await fs.rm(output, { recursive: true, force: true });
2022-03-28 10:05:55 -03:00
},
'astro:build:done': async ({ pages }) => {
2022-03-28 15:13:14 -03:00
// Split pages from the rest of files
2022-03-28 10:05:55 -03:00
await Promise.all(
pages.map(async ({ pathname }) => {
const origin = new URL(`./static/${pathname}index.html`, output);
const finalDir = new URL(`./server/pages/${pathname}`, output);
await fs.mkdir(finalDir, { recursive: true });
await fs.copyFile(origin, new URL(`./index.html`, finalDir));
await fs.rm(origin);
})
);
// Routes Manifest
// https://vercel.com/docs/file-system-api#configuration/routes
await writeJson(new URL(`./routes-manifest.json`, output), {
version: 3,
basePath: '/',
pages404: false,
});
2022-03-28 15:13:14 -03:00
const endpoints = await globby([ENDPOINT_GLOB, '!_*'], { onlyFiles: true, cwd: _config.pages });
if (endpoints.length === 0) return;
await esbuild.build({
entryPoints: endpoints.map((endpoint) => new URL(endpoint, _config.pages)).map(fileURLToPath),
outdir: fileURLToPath(new URL('./server/pages/api/', output)),
outbase: fileURLToPath(new URL('./api/', _config.pages)),
bundle: true,
target: 'node14',
platform: 'node',
format: 'cjs',
});
2022-03-28 10:05:55 -03:00
},
},
};
}
export default vercelFunctions;