diff --git a/.changeset/famous-llamas-play.md b/.changeset/famous-llamas-play.md new file mode 100644 index 000000000000..5345b7a6d859 --- /dev/null +++ b/.changeset/famous-llamas-play.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/adapter-netlify': patch +--- + +fix: preserve functions-internal folder so that auto-generated functions are not removed when ntl build is run diff --git a/packages/adapter-netlify/index.js b/packages/adapter-netlify/index.js index d2033d7a47ef..987d55ca0dee 100644 --- a/packages/adapter-netlify/index.js +++ b/packages/adapter-netlify/index.js @@ -1,8 +1,16 @@ -import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'fs'; +import { + appendFileSync, + existsSync, + readFileSync, + writeFileSync, + unlinkSync, + createReadStream +} from 'fs'; import { dirname, join, resolve, posix } from 'path'; import { fileURLToPath } from 'url'; import esbuild from 'esbuild'; import toml from '@iarna/toml'; +import { createInterface } from 'readline'; /** * @typedef {{ @@ -51,10 +59,43 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) { // "build" is the default publish directory when Netlify detects SvelteKit const publish = get_publish_directory(netlify_config, builder) || 'build'; + const redirects_file_path = join(publish, '_redirects'); + + // If redirects file exists - empty any netlify generated files in functions-internal + // Without removing other files that may have been auto generated by integrations + if (existsSync(redirects_file_path)) { + // Read each line of the file + const fileStream = createReadStream(redirects_file_path); + const rl = createInterface({ + input: fileStream, + crlfDelay: Infinity + }); + + // Create an array of lines + const lines = []; + for await (const line of rl) { + lines.push(line); + } + + const functions_internal = join('.netlify', 'functions-internal'); + + // Loop through redirects, and delete corresponding functions-internal files + lines.forEach((line) => { + if (line) { + // example line /.netlify/functions/{function_name} 200 + const path = line.split(' ')[1]; + const function_name = path.split('/').pop(); + const mjsFile = join(functions_internal, `${function_name}.mjs`); + const jsonFile = join(functions_internal, `${function_name}.json`); + if (existsSync(mjsFile)) unlinkSync(mjsFile); + if (existsSync(jsonFile)) unlinkSync(jsonFile); + } + }); + } + // empty out existing build directories builder.rimraf(publish); builder.rimraf('.netlify/edge-functions'); - builder.rimraf('.netlify/functions-internal'); builder.rimraf('.netlify/server'); builder.rimraf('.netlify/package.json'); builder.rimraf('.netlify/serverless.js');