|
| 1 | +import type { AstroAdapter, AstroIntegration, AstroConfig } from 'astro'; |
| 2 | +import fs from 'fs'; |
| 3 | + |
| 4 | +export function getAdapter(site: string | undefined): AstroAdapter { |
| 5 | + return { |
| 6 | + name: '@astrojs/netlify', |
| 7 | + serverEntrypoint: '@astrojs/netlify/netlify-functions.js', |
| 8 | + exports: ['handler'], |
| 9 | + args: { site } |
| 10 | + }; |
| 11 | +} |
| 12 | + |
| 13 | +interface NetlifyFunctionsOptions { |
| 14 | + dist?: URL; |
| 15 | +} |
| 16 | + |
| 17 | +function netlifyFunctions({ dist }: NetlifyFunctionsOptions = {}): AstroIntegration { |
| 18 | + let _config: AstroConfig; |
| 19 | + let entryFile: string; |
| 20 | + return { |
| 21 | + name: '@astrojs/netlify', |
| 22 | + hooks: { |
| 23 | + 'astro:config:setup': ({ config }) => { |
| 24 | + if(dist) { |
| 25 | + config.dist = dist; |
| 26 | + } else { |
| 27 | + config.dist = new URL('./netlify/', config.projectRoot); |
| 28 | + } |
| 29 | + }, |
| 30 | + 'astro:config:done': ({ config, setAdapter }) => { |
| 31 | + setAdapter(getAdapter(config.buildOptions.site)); |
| 32 | + _config = config; |
| 33 | + }, |
| 34 | + 'astro:build:start': async({ buildConfig }) => { |
| 35 | + entryFile = buildConfig.serverEntry.replace(/\.m?js/, ''); |
| 36 | + buildConfig.client = _config.dist; |
| 37 | + buildConfig.server = new URL('./functions/', _config.dist); |
| 38 | + }, |
| 39 | + 'astro:build:done': async ({ routes, dir }) => { |
| 40 | + const _redirectsURL = new URL('./_redirects', dir); |
| 41 | + |
| 42 | + // Create the redirects file that is used for routing. |
| 43 | + let _redirects = ''; |
| 44 | + for(const route of routes) { |
| 45 | + if(route.pathname) { |
| 46 | + _redirects += ` |
| 47 | +${route.pathname} /.netlify/functions/${entryFile} 200` |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + if(fs.existsSync(_redirects)) { |
| 52 | + await fs.promises.appendFile(_redirectsURL, _redirects, 'utf-8'); |
| 53 | + } else { |
| 54 | + await fs.promises.writeFile(_redirectsURL, _redirects, 'utf-8'); |
| 55 | + } |
| 56 | + } |
| 57 | + }, |
| 58 | + }; |
| 59 | +} |
| 60 | + |
| 61 | +export { |
| 62 | + netlifyFunctions, |
| 63 | + netlifyFunctions as default |
| 64 | +}; |
0 commit comments