summaryrefslogtreecommitdiff
path: root/packages/integrations/netlify/src/integration-functions.ts
blob: 8812a8e89d84f89dccc8973125e07be969339cde (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import { writeFile } from 'node:fs/promises';
import { extname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { AstroAdapter, AstroConfig, AstroIntegration, RouteData } from 'astro';
import { generateEdgeMiddleware } from './middleware.js';
import type { Args } from './netlify-functions.js';
import { createRedirects } from './shared.js';

export const NETLIFY_EDGE_MIDDLEWARE_FILE = 'netlify-edge-middleware';
export const ASTRO_LOCALS_HEADER = 'x-astro-locals';

export function getAdapter({ functionPerRoute, edgeMiddleware, ...args }: Args): AstroAdapter {
	return {
		name: '@astrojs/netlify/functions',
		serverEntrypoint: '@astrojs/netlify/netlify-functions.js',
		exports: ['handler'],
		args,
		adapterFeatures: {
			functionPerRoute,
			edgeMiddleware,
		},
		supportedAstroFeatures: {
			hybridOutput: 'stable',
			staticOutput: 'stable',
			serverOutput: 'stable',
			assets: {
				supportKind: 'stable',
				isSharpCompatible: true,
				isSquooshCompatible: true,
			},
		},
	};
}

interface NetlifyFunctionsOptions {
	dist?: URL;
	builders?: boolean;
	binaryMediaTypes?: string[];
	edgeMiddleware?: boolean;
	functionPerRoute?: boolean;
}

function netlifyFunctions({
	dist,
	builders,
	binaryMediaTypes,
	functionPerRoute = false,
	edgeMiddleware = false,
}: NetlifyFunctionsOptions = {}): AstroIntegration {
	let _config: AstroConfig;
	let _entryPoints: Map<RouteData, URL>;
	let ssrEntryFile: string;
	let _middlewareEntryPoint: URL;
	return {
		name: '@astrojs/netlify',
		hooks: {
			'astro:config:setup': ({ config, updateConfig }) => {
				const outDir = dist ?? new URL('./dist/', config.root);
				updateConfig({
					outDir,
					build: {
						redirects: false,
						client: outDir,
						server: new URL('./.netlify/functions-internal/', config.root),
					},
				});
			},
			'astro:build:ssr': async ({ entryPoints, middlewareEntryPoint }) => {
				if (middlewareEntryPoint) {
					_middlewareEntryPoint = middlewareEntryPoint;
				}
				_entryPoints = entryPoints;
			},
			'astro:config:done': ({ config, setAdapter }) => {
				setAdapter(
					getAdapter({
						binaryMediaTypes,
						builders,
						functionPerRoute,
						edgeMiddleware,
					})
				);
				_config = config;
				ssrEntryFile = config.build.serverEntry.replace(/\.m?js/, '');

				if (config.output === 'static') {
					// eslint-disable-next-line no-console
					console.warn(
						`[@astrojs/netlify] \`output: "server"\` or \`output: "hybrid"\` is required to use this adapter.`
					);
					// eslint-disable-next-line no-console
					console.warn(
						`[@astrojs/netlify] Otherwise, this adapter is not required to deploy a static site to Netlify.`
					);
				}
			},
			'astro:build:done': async ({ routes, dir }) => {
				const functionsConfig = {
					version: 1,
					config: {
						nodeModuleFormat: 'esm',
					},
				};
				const functionsConfigPath = join(fileURLToPath(_config.build.server), 'entry.json');
				await writeFile(functionsConfigPath, JSON.stringify(functionsConfig));

				const type = builders ? 'builders' : 'functions';
				const kind = type ?? 'functions';

				if (_entryPoints.size) {
					const routeToDynamicTargetMap = new Map();
					for (const [route, entryFile] of _entryPoints) {
						const wholeFileUrl = fileURLToPath(entryFile);

						const extension = extname(wholeFileUrl);
						const relative = wholeFileUrl
							.replace(fileURLToPath(_config.build.server), '')
							.replace(extension, '')
							.replaceAll('\\', '/');
						const dynamicTarget = `/.netlify/${kind}/${relative}`;

						routeToDynamicTargetMap.set(route, dynamicTarget);
					}
					await createRedirects(_config, routeToDynamicTargetMap, dir);
				} else {
					const dynamicTarget = `/.netlify/${kind}/${ssrEntryFile}`;
					const map: [RouteData, string][] = routes.map((route) => {
						return [route, dynamicTarget];
					});
					const routeToDynamicTargetMap = new Map(Array.from(map));

					await createRedirects(_config, routeToDynamicTargetMap, dir);
				}
				if (_middlewareEntryPoint) {
					const outPath = fileURLToPath(new URL('./.netlify/edge-functions/', _config.root));
					const netlifyEdgeMiddlewareHandlerPath = new URL(
						NETLIFY_EDGE_MIDDLEWARE_FILE,
						_config.srcDir
					);
					await generateEdgeMiddleware(
						_middlewareEntryPoint,
						outPath,
						netlifyEdgeMiddlewareHandlerPath
					);
				}
			},
		},
	};
}

export { netlifyFunctions as default, netlifyFunctions };