@sveltejs/adapter-netlify 7.0.0-next.9 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/files/edge.js CHANGED
@@ -1,44 +1,47 @@
1
- import { Server } from '0SERVER';
2
- import { manifest } from 'MANIFEST';
3
-
4
- const server = new Server(manifest);
1
+ /** @import { EdgeFunction } from '@netlify/edge-functions' */
2
+ /** @import { Server } from '@sveltejs/kit' */
5
3
 
6
4
  /**
7
- * We don't know the origin until we receive a request, but
8
- * that's guaranteed to happen before we call `read`
9
- * @type {string}
5
+ * @param {Server} server
6
+ * @returns {EdgeFunction}
10
7
  */
11
- let origin;
12
-
13
- const initialized = server.init({
14
- env: Deno.env.toObject(),
15
- read: async (file) => {
16
- const url = `${origin}/${file}`;
17
- const response = await fetch(url);
18
-
19
- if (!response.ok) {
20
- throw new Error(
21
- `read(...) failed: could not fetch ${url} (${response.status} ${response.statusText})`
22
- );
8
+ export function init(server) {
9
+ /**
10
+ * We don't know the origin until we receive a request, but
11
+ * that's guaranteed to happen before we call `read`
12
+ * @type {string}
13
+ */
14
+ let origin;
15
+
16
+ const initialized = server.init({
17
+ env: Deno.env.toObject(),
18
+ read: async (file) => {
19
+ const url = `${origin}/${file}`;
20
+ const response = await fetch(url);
21
+
22
+ if (!response.ok) {
23
+ throw new Error(
24
+ `read(...) failed: could not fetch ${url} (${response.status} ${response.statusText})`
25
+ );
26
+ }
27
+
28
+ return response.body;
23
29
  }
30
+ });
24
31
 
25
- return response.body;
26
- }
27
- });
28
-
29
- /** @type {import('@netlify/edge-functions').EdgeFunction} */
30
- export default async function handler(request, context) {
31
- if (!origin) {
32
- origin = new URL(request.url).origin;
33
- }
32
+ return async function handler(request, context) {
33
+ if (!origin) {
34
+ origin = new URL(request.url).origin;
35
+ }
34
36
 
35
- // always await initialization to prevent race condition with concurrent requests
36
- await initialized;
37
+ // always await initialization to prevent race condition with concurrent requests
38
+ await initialized;
37
39
 
38
- return server.respond(request, {
39
- platform: { context },
40
- getClientAddress() {
41
- return context.ip;
42
- }
43
- });
40
+ return server.respond(request, {
41
+ platform: { context },
42
+ getClientAddress() {
43
+ return context.ip;
44
+ }
45
+ });
46
+ };
44
47
  }
@@ -1,14 +1,11 @@
1
- import { Server } from '0SERVER';
2
1
  import { createReadableStream } from '@sveltejs/kit/node';
3
2
  import process from 'node:process';
4
3
 
5
4
  /**
6
- * @param {import('@sveltejs/kit').SSRManifest} manifest
5
+ * @param {import('@sveltejs/kit').Server} server
7
6
  * @returns {(request: Request, context: import('@netlify/types').Context) => Promise<Response>}
8
7
  */
9
- export function init(manifest) {
10
- const server = new Server(manifest);
11
-
8
+ export function init(server) {
12
9
  /** @type {Promise<void> | null} */
13
10
  let init_promise = server.init({
14
11
  env: process.env,
package/index.d.ts CHANGED
@@ -9,11 +9,15 @@ export interface AdapterOptions {
9
9
  edge?: boolean;
10
10
  /**
11
11
  * If `true`, your app will be split into multiple functions instead of a single one for the entire app.
12
- *
13
- * If `edge` is `true`, this option cannot be used.
14
12
  * @default false
15
13
  */
16
14
  split?: boolean;
15
+ /**
16
+ * The directory to write prerendered pages and static assets (the contents of `static`, plus client-side JS and CSS generated by SvelteKit) to.
17
+ * @default 'build'
18
+ * @since 7.0.0
19
+ */
20
+ publish?: string;
17
21
  }
18
22
 
19
23
  export default function plugin(opts?: AdapterOptions): Adapter;
package/index.js CHANGED
@@ -1,18 +1,13 @@
1
+ /** @import { IntegrationsConfig } from '@netlify/edge-functions' */
2
+ /** @import { Builder, RouteDefinition } from '@sveltejs/kit' */
3
+ import crypto from 'node:crypto';
1
4
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
- import { join, posix } from 'node:path';
3
- import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
4
7
  import { builtinModules } from 'node:module';
5
8
  import process from 'node:process';
6
- import toml from '@iarna/toml';
7
9
  import { build } from 'rolldown';
8
- import { matches, get_publish_directory, s } from './utils.js';
9
-
10
- /**
11
- * @typedef {{
12
- * build?: { publish?: string }
13
- * functions?: { node_bundler?: 'zisi' | 'esbuild' }
14
- * } & toml.JsonMap} NetlifyConfig
15
- */
10
+ import { matches, s } from './utils.js';
16
11
 
17
12
  const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf-8'));
18
13
  const adapter_version = pkg.version;
@@ -30,8 +25,10 @@ const netlify_framework_edge_path = '.netlify/v1/edge-functions';
30
25
 
31
26
  const FUNCTION_PREFIX = 'sveltekit-';
32
27
 
28
+ // "build" is the default publish directory when Netlify detects SvelteKit
29
+
33
30
  /** @type {typeof import('./index.js').default} */
34
- export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
31
+ export default function ({ split = false, edge = edge_set_in_env_var, publish = 'build' } = {}) {
35
32
  return {
36
33
  name,
37
34
  async adapt(builder) {
@@ -54,11 +51,6 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
54
51
  );
55
52
  }
56
53
 
57
- const netlify_config = get_netlify_config();
58
-
59
- // "build" is the default publish directory when Netlify detects SvelteKit
60
- const publish = get_publish_directory(netlify_config, builder) || 'build';
61
-
62
54
  // empty out existing build directories
63
55
  rmSync(publish, { force: true, recursive: true });
64
56
  rmSync('.netlify/v1', { force: true, recursive: true });
@@ -77,29 +69,30 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
77
69
  }
78
70
  }
79
71
 
80
- builder.log.minor(`Publishing to "${publish}"`);
81
-
82
72
  builder.log.minor('Copying assets...');
83
73
  const publish_dir = `${publish}${builder.config.paths.base}`;
84
74
  builder.writeClient(publish_dir);
85
75
  builder.writePrerendered(publish_dir);
86
76
 
87
- // Copy user's custom _headers file if it exists
77
+ // Copy user's _headers file if it exists
88
78
  if (existsSync('_headers')) {
79
+ builder.log.minor('Copying user custom headers...');
89
80
  builder.copy('_headers', join(publish, '_headers'));
90
81
  }
91
82
 
83
+ // Copy user's _redirects file if it exists
84
+ if (existsSync('_redirects')) {
85
+ builder.log.minor('Copying user redirects...');
86
+ builder.copy('_redirects', join(publish, '_redirects'));
87
+ }
88
+
92
89
  builder.log.minor('Writing Netlify config...');
93
90
  write_frameworks_config({ builder });
94
91
 
95
92
  if (edge) {
96
- if (split) {
97
- throw new Error('Cannot use `split: true` alongside `edge: true`');
98
- }
99
-
100
- await generate_edge_functions({ builder });
93
+ await generate_edge_functions({ builder, split });
101
94
  } else {
102
- generate_serverless_functions({ builder, split, publish });
95
+ generate_serverless_functions(builder, split);
103
96
  }
104
97
  },
105
98
 
@@ -111,117 +104,33 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
111
104
  }
112
105
 
113
106
  /**
114
- * @param { object } params
115
- * @param {import('@sveltejs/kit').Builder} params.builder
116
- * @param { string } params.publish
117
- * @param { boolean } params.split
107
+ * @param {Builder} builder
108
+ * @param {boolean} split
118
109
  */
119
- function generate_serverless_functions({ builder, publish, split }) {
110
+ function generate_serverless_functions(builder, split) {
120
111
  // https://docs.netlify.com/build/frameworks/frameworks-api/#netlifyv1functions
121
112
  mkdirSync(netlify_framework_serverless_path, { recursive: true });
122
113
 
123
114
  builder.writeServer('.netlify/v1/server');
124
115
 
125
- const replace = {
126
- '0SERVER': './server/index.js' // digit prefix prevents CJS build from using this as a variable name, which would also get replaced
127
- };
128
-
129
- builder.copy(files, '.netlify/v1', { replace, filter: (file) => !file.endsWith('edge.js') });
116
+ builder.copy(`${files}/serverless.js`, '.netlify/v1/serverless.js');
130
117
 
131
118
  builder.log.minor('Generating serverless functions...');
132
119
 
133
120
  if (split) {
134
- const seen = new Set();
135
-
136
- for (let i = 0; i < builder.routes.length; i++) {
137
- const route = builder.routes[i];
138
- if (route.prerender === true) continue;
139
-
140
- const routes = [route];
141
-
142
- /** @type {string[]} */
143
- const parts = [];
144
-
145
- // The parts should conform to URLPattern syntax
146
- // https://docs.netlify.com/build/functions/get-started/?fn-language=ts&data-tab=TypeScript#route-requests
147
- for (const segment of route.segments) {
148
- if (segment.rest) {
149
- parts.push('*');
150
- } else if (segment.dynamic) {
151
- // URLPattern requires params to start with letters
152
- parts.push(`:param${parts.length}`);
153
- } else {
154
- parts.push(segment.content);
155
- }
156
- }
157
-
158
- // Netlify handles trailing slashes for us, so we don't need to include them in the pattern
159
- const pattern = `/${parts.join('/')}`;
160
- const name =
161
- FUNCTION_PREFIX + (parts.join('-').replace(/[:.]/g, '_').replace('*', '__rest') || 'index');
162
-
163
- // skip routes with identical patterns, they were already folded into another function
164
- if (seen.has(pattern)) continue;
165
-
166
- const patterns = [pattern, `${pattern === '/' ? '' : pattern}/__data.json`];
167
- patterns.forEach((p) => seen.add(p));
168
-
169
- // figure out which lower priority routes should be considered fallbacks
170
- for (let j = i + 1; j < builder.routes.length; j += 1) {
171
- const other = builder.routes[j];
172
- if (other.prerender === true) continue;
173
-
174
- if (matches(route.segments, other.segments)) {
175
- routes.push(other);
176
- }
177
- }
178
-
179
- generate_serverless_function({
180
- builder,
181
- routes,
182
- patterns,
183
- name
184
- });
121
+ const uuid = crypto.randomUUID();
122
+ for (const fn of get_split_functions(builder)) {
123
+ generate_serverless_function(builder, fn, uuid);
185
124
  }
186
-
187
- generate_serverless_function({
188
- builder,
189
- routes: [],
190
- patterns: ['/*'],
191
- name: `${FUNCTION_PREFIX}catch-all`,
192
- exclude: Array.from(seen)
193
- });
194
125
  } else {
195
- generate_serverless_function({
196
- builder,
126
+ generate_serverless_function(builder, {
127
+ type: 'singular',
197
128
  routes: undefined,
198
129
  patterns: ['/*'],
199
- name: `${FUNCTION_PREFIX}render`
130
+ name: `${FUNCTION_PREFIX}render`,
131
+ display_name: 'SvelteKit server'
200
132
  });
201
133
  }
202
-
203
- // Copy user's custom _redirects file if it exists
204
- if (existsSync('_redirects')) {
205
- builder.log.minor('Copying user redirects...');
206
- const redirects_file = join(publish, '_redirects');
207
- builder.copy('_redirects', redirects_file);
208
- }
209
- }
210
-
211
- /**
212
- * @returns {NetlifyConfig | null}
213
- */
214
- function get_netlify_config() {
215
- if (!existsSync('netlify.toml')) return null;
216
-
217
- try {
218
- return toml.parse(readFileSync('netlify.toml', 'utf-8'));
219
- } catch (err) {
220
- if (err instanceof Error) {
221
- throw new Error(`Failed to parse netlify.toml: ${err.message}`, { cause: err });
222
- }
223
- throw err;
224
- }
225
134
  }
226
135
 
227
136
  /**
@@ -247,90 +156,250 @@ function write_frameworks_config({ builder }) {
247
156
  writeFileSync(netlify_framework_config_path, s(config));
248
157
  }
249
158
 
159
+ /** @typedef {'singular' | 'split' | 'catch-all'} EntrypointType */
160
+
161
+ /**
162
+ * @typedef {object} EntrypointMetadata
163
+ * @property {EntrypointType} type
164
+ * @property {RouteDefinition[] | undefined} routes
165
+ * @property {string[]} patterns
166
+ * @property {string} name
167
+ * @property {string} display_name
168
+ * @property {string[]} [exclude]
169
+ */
170
+
250
171
  /**
251
- *
252
- * @param {{
253
- * builder: import('@sveltejs/kit').Builder,
254
- * routes: import('@sveltejs/kit').RouteDefinition[] | undefined,
255
- * patterns: string[],
256
- * name: string,
257
- * exclude?: string[]
258
- * }} opts
172
+ * @param {Builder} builder
173
+ * @returns {EntrypointMetadata[]}
259
174
  */
260
- function generate_serverless_function({ builder, routes, patterns, name, exclude }) {
261
- const manifest = builder.generateManifest({
262
- relativePath: '../server',
263
- routes
175
+ function get_split_functions(builder) {
176
+ const seen = new Set();
177
+ let index = 0;
178
+
179
+ /** @type {EntrypointMetadata[]} */
180
+ const functions = [];
181
+
182
+ for (let i = 0; i < builder.routes.length; i++) {
183
+ const route = builder.routes[i];
184
+ if (route.prerender === true) continue;
185
+
186
+ const routes = [route];
187
+ /** @type {string[]} */
188
+ const parts = [];
189
+
190
+ // The parts should conform to URLPattern syntax
191
+ // https://docs.netlify.com/build/functions/get-started/?fn-language=ts&data-tab=TypeScript#route-requests
192
+ for (const [i, segment] of route.segments.entries()) {
193
+ if (segment.rest) {
194
+ parts.push('*');
195
+ } else if (segment.dynamic) {
196
+ // URLPattern requires params to start with letters
197
+ const optional = /^\[\[.+\]\]$/.test(segment.content) ? '?' : '';
198
+ parts.push(`:param${i}${optional}`);
199
+ } else {
200
+ parts.push(segment.content);
201
+ }
202
+ }
203
+
204
+ // Netlify handles trailing slashes for us, so we don't need to include them in the pattern
205
+ const pattern = `/${parts.join('/')}`;
206
+
207
+ // skip routes with identical patterns, they were already folded into another function
208
+ if (seen.has(pattern)) continue;
209
+
210
+ const patterns = [pattern, `${pattern === '/' ? '' : pattern}/__data.json`];
211
+ patterns.forEach((pattern) => seen.add(pattern));
212
+
213
+ // figure out which lower priority routes should be considered fallbacks
214
+ for (let j = i + 1; j < builder.routes.length; j += 1) {
215
+ const other = builder.routes[j];
216
+ if (other.prerender === true) continue;
217
+
218
+ if (matches(route.segments, other.segments)) {
219
+ routes.push(other);
220
+ }
221
+ }
222
+
223
+ functions.push({
224
+ type: 'split',
225
+ routes,
226
+ patterns,
227
+ name: `${FUNCTION_PREFIX}${index++}`,
228
+ display_name: `SvelteKit ${route.id}`
229
+ });
230
+ }
231
+
232
+ functions.push({
233
+ type: 'catch-all',
234
+ routes: [],
235
+ patterns: ['/*'],
236
+ name: `${FUNCTION_PREFIX}catch-all`,
237
+ display_name: 'SvelteKit catch-all',
238
+ exclude: Array.from(seen)
264
239
  });
265
240
 
266
- const fn = generate_serverless_function_module(manifest);
267
- const config = generate_config_export(name, patterns, exclude);
241
+ return functions;
242
+ }
243
+
244
+ /**
245
+ * @param {Builder} builder
246
+ * @param {EntrypointMetadata} fn
247
+ * @param {string} [uuid]
248
+ */
249
+ function generate_serverless_function(builder, fn, uuid) {
250
+ builder.generateServerInstance(`.netlify/v1/server-${fn.name}.js`, {
251
+ routes: fn.routes,
252
+ serverDirectory: '.netlify/v1/server'
253
+ });
254
+
255
+ const filename = `${netlify_framework_serverless_path}/${fn.name}.mjs`;
256
+ const code = generate_function_module(
257
+ fn.type,
258
+ '../serverless.js',
259
+ `../server-${fn.name}.js`,
260
+ uuid
261
+ );
262
+ const config = create_function_config('serverless', fn);
268
263
 
269
264
  if (builder.hasServerInstrumentationFile()) {
270
- writeFileSync(`${netlify_framework_serverless_path}/${name}.mjs`, fn);
265
+ writeFileSync(filename, code);
266
+ const initializer = builder.createInstrumentationInitializer({
267
+ outputDirectory: netlify_framework_serverless_path,
268
+ serverDirectory: '.netlify/v1/server'
269
+ });
271
270
  builder.instrument({
272
- entrypoint: `${netlify_framework_serverless_path}/${name}.mjs`,
271
+ entrypoint: filename,
273
272
  instrumentation: '.netlify/v1/server/instrumentation.server.js',
274
- start: `.netlify/v1/server/${name}.start.mjs`,
273
+ start: `.netlify/v1/server/${fn.name}.start.mjs`,
274
+ initializer,
275
275
  module: {
276
276
  generateText: generate_traced_module(config)
277
277
  }
278
278
  });
279
279
  } else {
280
- writeFileSync(`${netlify_framework_serverless_path}/${name}.mjs`, `${fn}\n${config}`);
280
+ writeFileSync(filename, `${code}\n${config}`);
281
281
  }
282
282
  }
283
283
 
284
284
  /**
285
- * @param {string} manifest
285
+ * @param {EntrypointType} type
286
+ * @param {string} init
287
+ * @param {string} server
288
+ * @param {string} [uuid]
286
289
  * @returns {string}
287
290
  */
288
- function generate_serverless_function_module(manifest) {
291
+ function generate_function_module(type, init, server, uuid) {
292
+ const runtime_imports = [
293
+ `import { init } from '${init}';`,
294
+ `import { server } from '${server}';`
295
+ ].join('\n');
296
+ const original_pathname_header = `const original_pathname_header = \`x-sveltekit-original-pathname-${uuid}\``;
297
+
298
+ if (type === 'catch-all' && uuid) {
299
+ // Netlify encodes the response body but `fetch` automatically decodes it.
300
+ // So, we need to remove the `content-encoding` header to allow Netlify
301
+ // to correctly re-encode it on the way out.
302
+ return `\
303
+ import { applyReroute } from '@sveltejs/kit/adapter';
304
+ ${runtime_imports}
305
+
306
+ ${original_pathname_header}
307
+
308
+ const respond = init(server);
309
+
310
+ export default async (request, context) => {
311
+ const catch_all_response = await respond(request, context);
312
+
313
+ return await applyReroute(catch_all_response, async (url) => {
314
+ const rerouted_request = new Request(url, request);
315
+ rerouted_request.headers.set(original_pathname_header, new URL(request.url).pathname);
316
+
317
+ const rerouted_response = await fetch(rerouted_request);
318
+
319
+ const response = new Response(rerouted_response.body, rerouted_response);
320
+ if (response.headers.has('content-encoding')) {
321
+ response.headers.delete('content-encoding');
322
+ response.headers.delete('content-length');
323
+ }
324
+
325
+ return response;
326
+ });
327
+ };
328
+ `;
329
+ }
330
+
331
+ if (type === 'split' && uuid) {
332
+ return `\
333
+ ${runtime_imports}
334
+
335
+ ${original_pathname_header}
336
+
337
+ const respond = init(server);
338
+
339
+ export default async (request, context) => {
340
+ if (request.headers.has(original_pathname_header)) {
341
+ const url = new URL(request.url);
342
+ url.pathname = request.headers.get(original_pathname_header);
343
+ request = new Request(url, request);
344
+ request.headers.delete(original_pathname_header);
345
+ }
346
+
347
+ return await respond(request, context);
348
+ };
349
+ `;
350
+ }
351
+
289
352
  return `\
290
- import { init } from '../serverless.js';
353
+ ${runtime_imports}
291
354
 
292
- export default init(${manifest});
355
+ export default init(server);
293
356
  `;
294
357
  }
295
358
 
296
359
  const generator_string = `@sveltejs/adapter-netlify@${adapter_version}`;
297
360
 
298
361
  /**
299
- * @param {string} name The name that shows up in the logs & metrics functions list
300
- * @param {string[]} patterns
301
- * @param {string[]} [exclude]
362
+ * @param {'serverless' | 'edge'} runtime
363
+ * @param {EntrypointMetadata} fn
302
364
  * @returns {string}
303
365
  */
304
- function generate_config_export(name, patterns, exclude = []) {
305
- // TODO: add a human friendly name for the function https://docs.netlify.com/build/frameworks/frameworks-api/#configuration-options-2
366
+ function create_function_config(runtime, fn) {
367
+ /** @type {IntegrationsConfig & { preferStatic?: boolean }} */
368
+ const config = {
369
+ name: fn.display_name,
370
+ generator: generator_string,
371
+ path: /** @type {`/${string}`[]} */ (fn.patterns),
372
+ excludedPath: /** @type {`/${string}`[]} */ (['/.netlify/*', ...(fn.exclude ?? [])])
373
+ };
306
374
 
307
- // https://docs.netlify.com/build/frameworks/frameworks-api/#configuration-options-2
308
- return `\
309
- export const config = {
310
- name: ${JSON.stringify(name)},
311
- generator: '${generator_string}',
312
- path: [${patterns.map(s).join(', ')}],
313
- excludedPath: [${['/.netlify/*', ...exclude].map(s).join(', ')}],
314
- preferStatic: true
315
- };
316
- `;
375
+ if (runtime === 'serverless') {
376
+ config.preferStatic = true;
377
+ }
378
+
379
+ return `export const config = ${s(config)};\n`;
317
380
  }
318
381
 
319
382
  /**
320
383
  * @param {string} config
321
- * @returns {(opts: { instrumentation: string; start: string }) => string}
384
+ * @returns {(opts: { instrumentation: string; start: string; initializer: string }) => string}
322
385
  */
323
386
  function generate_traced_module(config) {
324
- return ({ instrumentation, start }) => {
387
+ return ({ instrumentation, start, initializer }) => {
325
388
  return `\
326
- import '../server/${instrumentation}';
327
- const { default: _0 } = await import('../server/${start}');
389
+ import ${JSON.stringify(to_import_specifier(initializer))};
390
+ import ${JSON.stringify(to_import_specifier(instrumentation))};
391
+ const { default: _0 } = await import(${JSON.stringify(to_import_specifier(start))});
328
392
  export { _0 as default };
329
393
 
330
394
  ${config}`;
331
395
  };
332
396
  }
333
397
 
398
+ /** @param {string} path */
399
+ function to_import_specifier(path) {
400
+ return path.startsWith('.') ? path : `./${path}`;
401
+ }
402
+
334
403
  /** @satisfies {import('rolldown').BuildOptions} */
335
404
  const rolldown_config = {
336
405
  platform: 'browser',
@@ -350,37 +419,21 @@ const rolldown_config = {
350
419
  };
351
420
 
352
421
  /**
353
- * @param { object } params
354
- * @param {import('@sveltejs/kit').Builder} params.builder
422
+ * @param {object} params
423
+ * @param {Builder} params.builder
424
+ * @param {boolean} params.split
355
425
  */
356
- async function generate_edge_functions({ builder }) {
426
+ async function generate_edge_functions({ builder, split }) {
357
427
  const tmp = builder.getBuildDirectory('netlify-tmp');
358
428
  rmSync(tmp, { force: true, recursive: true });
359
429
  mkdirSync(tmp, { recursive: true });
360
430
 
361
431
  // https://docs.netlify.com/build/frameworks/frameworks-api/#edge-functions
362
- mkdirSync('.netlify/v1/edge-functions', { recursive: true });
363
-
364
- builder.log.minor('Generating Edge Function...');
365
- const relativePath = posix.relative(tmp, builder.getServerDirectory());
432
+ mkdirSync(netlify_framework_edge_path, { recursive: true });
366
433
 
367
- builder.copy(`${files}/edge.js`, `${tmp}/entry.js`, {
368
- replace: {
369
- '0SERVER': `${relativePath}/index.js`,
370
- MANIFEST: './manifest.js'
371
- }
372
- });
434
+ builder.log.minor('Generating edge functions...');
435
+ builder.copy(`${files}/edge.js`, `${tmp}/edge.js`);
373
436
 
374
- const manifest = builder.generateManifest({
375
- relativePath
376
- });
377
-
378
- writeFileSync(`${tmp}/manifest.js`, `export const manifest = ${manifest};\n`);
379
-
380
- /** @type {{ assets: Set<string> }} */
381
- const { assets } = (await import(pathToFileURL(`${tmp}/manifest.js`).href)).manifest;
382
-
383
- const path = '/*';
384
437
  // We only need to specify paths without the trailing slash because
385
438
  // Netlify will handle the optional trailing slash for us
386
439
  const excluded_paths = [
@@ -389,66 +442,144 @@ async function generate_edge_functions({ builder }) {
389
442
  `/${builder.getAppPath()}/version.json`,
390
443
  // the base root and `trailingSlash: 'always'` pages are recorded with a trailing slash
391
444
  ...builder.prerendered.paths.map((path) => (path === '/' ? path : path.replace(/\/$/, ''))),
392
- ...Array.from(assets).flatMap((asset) => {
445
+ ...Array.from(builder.manifest.assets).flatMap(({ path: asset }) => {
393
446
  if (asset.endsWith('/index.html')) {
394
447
  const dir = asset.replace(/\/index\.html$/, '');
395
448
  return [`${builder.config.paths.base}/${asset}`, `${builder.config.paths.base}/${dir}`];
396
449
  }
397
450
  return `${builder.config.paths.base}/${asset}`;
398
- }),
399
- // Should not be served by SvelteKit at all
400
- '/.netlify/*'
451
+ })
401
452
  ];
402
453
 
403
- await Promise.all([
404
- build({
405
- ...rolldown_config,
406
- input: `${tmp}/entry.js`,
407
- output: {
408
- ...rolldown_config.output,
409
- file: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}render.js`
410
- }
411
- }),
412
- builder.hasServerInstrumentationFile() &&
413
- build({
414
- ...rolldown_config,
415
- input: `${builder.getServerDirectory()}/instrumentation.server.js`,
416
- output: {
417
- ...rolldown_config.output,
418
- file: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}instrumentation.server.js`
454
+ /** @type {EntrypointMetadata[]} */
455
+ const functions = split
456
+ ? get_split_functions(builder)
457
+ : [
458
+ {
459
+ type: 'singular',
460
+ routes: undefined,
461
+ patterns: ['/*'],
462
+ name: `${FUNCTION_PREFIX}render`,
463
+ display_name: 'SvelteKit server'
419
464
  }
420
- })
421
- ]);
465
+ ];
466
+ const reroute_id = split ? crypto.randomUUID() : undefined;
422
467
 
468
+ for (const fn of functions) {
469
+ await generate_edge_function(
470
+ builder,
471
+ tmp,
472
+ {
473
+ ...fn,
474
+ exclude: excluded_paths.concat(fn.exclude ?? [])
475
+ },
476
+ reroute_id
477
+ );
478
+ }
479
+ }
480
+
481
+ /**
482
+ * @param {Builder} builder
483
+ * @param {string} tmp
484
+ * @param {EntrypointMetadata} fn
485
+ * @param {string | undefined} reroute_id
486
+ */
487
+ async function generate_edge_function(builder, tmp, fn, reroute_id) {
488
+ builder.generateServerInstance(`${tmp}/server-${fn.name}.js`, { routes: fn.routes });
489
+
490
+ const entry = `${tmp}/entry-${fn.name}.js`;
491
+ const code = generate_edge_function_module(
492
+ fn.type,
493
+ './edge.js',
494
+ `./server-${fn.name}.js`,
495
+ reroute_id
496
+ );
497
+ const config = create_function_config('edge', fn);
498
+ writeFileSync(entry, `${code}\n${config}`);
499
+
500
+ let input = entry;
423
501
  if (builder.hasServerInstrumentationFile()) {
502
+ const initializer = builder.createInstrumentationInitializer({
503
+ outputDirectory: tmp,
504
+ environment: 'export default Deno.env.toObject();\n'
505
+ });
506
+ input = `${tmp}/instrumented-entry-${fn.name}.js`;
507
+ writeFileSync(input, `export { default, config } from './entry-${fn.name}.js';\n`);
424
508
  builder.instrument({
425
- entrypoint: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}render.js`,
426
- instrumentation: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}instrumentation.server.js`,
427
- start: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}start.js`
509
+ entrypoint: input,
510
+ instrumentation: `${builder.getServerDirectory()}/instrumentation.server.js`,
511
+ initializer,
512
+ module: {
513
+ generateText: generate_traced_module(config)
514
+ }
428
515
  });
429
516
  }
430
517
 
431
- add_edge_function_config({ builder, path, excluded_paths });
518
+ await build({
519
+ ...rolldown_config,
520
+ input,
521
+ output: {
522
+ ...rolldown_config.output,
523
+ file: `${netlify_framework_edge_path}/${fn.name}.js`
524
+ }
525
+ });
432
526
  }
433
527
 
434
528
  /**
435
- * Adds edge function configuration to the Frameworks API config file `config.json`
436
- * https://docs.netlify.com/build/frameworks/frameworks-api/#netlifyv1edge-functions
437
- * @param {{ builder: import('@sveltejs/kit').Builder, path: string, excluded_paths: string[] }} params
529
+ * @param {EntrypointType} type
530
+ * @param {string} init
531
+ * @param {string} server
532
+ * @param {string | undefined} reroute_id
533
+ * @returns {string}
438
534
  */
439
- function add_edge_function_config({ path, excluded_paths }) {
440
- const config = JSON.parse(readFileSync(netlify_framework_config_path, 'utf-8'));
441
-
442
- // https://docs.netlify.com/build/frameworks/frameworks-api/#configuration-options-1
443
- config.edge_functions = [
444
- {
445
- function: `${FUNCTION_PREFIX}render`,
446
- name: 'SvelteKit server',
447
- generator: generator_string,
448
- path,
449
- excludedPath: excluded_paths
450
- }
451
- ];
535
+ function generate_edge_function_module(type, init, server, reroute_id) {
536
+ if (type === 'singular') {
537
+ return generate_function_module(type, init, server);
538
+ }
452
539
 
453
- writeFileSync(netlify_framework_config_path, s(config));
540
+ const runtime_imports = [
541
+ `import { init } from '${init}';`,
542
+ `import { server } from '${server}';`
543
+ ].join('\n');
544
+ const reroute_parameter = `__sveltekit_original_pathname_${reroute_id}`;
545
+
546
+ if (type === 'catch-all') {
547
+ return `\
548
+ import { applyReroute } from '@sveltejs/kit/adapter';
549
+ ${runtime_imports}
550
+
551
+ const respond = init(server);
552
+
553
+ export default async (request, context) => {
554
+ const response = await respond(request, context);
555
+
556
+ let rerouted_url;
557
+ applyReroute(response, (url) => {
558
+ url.searchParams.set('${reroute_parameter}', new URL(request.url).pathname);
559
+ rerouted_url = url;
560
+ });
561
+
562
+ return rerouted_url ?? response;
563
+ };
564
+ `;
565
+ }
566
+
567
+ return `\
568
+ ${runtime_imports}
569
+
570
+ const respond = init(server);
571
+
572
+ export default async (request, context) => {
573
+ const url = new URL(request.url);
574
+ const pathname = url.searchParams.get('${reroute_parameter}');
575
+
576
+ if (pathname) {
577
+ url.pathname = pathname;
578
+ url.searchParams.delete('${reroute_parameter}');
579
+ request = new Request(url, request);
580
+ }
581
+
582
+ return await respond(request, context);
583
+ };
584
+ `;
454
585
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltejs/adapter-netlify",
3
- "version": "7.0.0-next.9",
3
+ "version": "7.0.0",
4
4
  "description": "A SvelteKit adapter that creates a Netlify app",
5
5
  "keywords": [
6
6
  "adapter",
@@ -34,27 +34,27 @@
34
34
  "ambient.d.ts"
35
35
  ],
36
36
  "dependencies": {
37
- "@iarna/toml": "^2.2.5",
38
37
  "@netlify/types": "^2.8.0",
39
38
  "rolldown": "^1.2.3"
40
39
  },
41
40
  "devDependencies": {
42
41
  "@netlify/edge-functions": "^3.0.8",
42
+ "@sveltejs/kit": "^3.0.0",
43
43
  "@types/deno": "^2.7.0",
44
44
  "@types/node": "^22.19.19",
45
- "typescript": "^7.0.2",
46
- "vitest": "^4.1.10",
47
- "@sveltejs/kit": "^3.0.0-next.24"
45
+ "@typescript/native": "npm:typescript@^7.0.2",
46
+ "vitest": "^5.0.1"
48
47
  },
49
48
  "peerDependencies": {
50
- "@sveltejs/kit": "^2.31.0"
49
+ "@sveltejs/kit": "^3.0.0-next.0"
51
50
  },
52
51
  "scripts": {
53
- "check": "tsc && tsc --project files/tsconfig.json",
52
+ "check": "pnpm tsc-native && pnpm tsc-native --project files/tsconfig.json",
54
53
  "lint": "oxfmt --check .",
55
54
  "format": "oxfmt --write .",
56
55
  "test:unit": "vitest run",
57
- "test:build": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" build",
58
- "test": "pnpm test:unit && pnpm test:build"
56
+ "test:build": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:build",
57
+ "test": "pnpm test:unit && pnpm test:build",
58
+ "tsc-native": "node node_modules/@typescript/native/bin/tsc"
59
59
  }
60
60
  }
package/utils.js CHANGED
@@ -1,17 +1,7 @@
1
- import { resolve } from 'node:path';
2
- import process from 'node:process';
3
-
4
1
  /**
5
2
  * @typedef {{ rest: boolean, dynamic: boolean, content: string }} RouteSegment
6
3
  */
7
4
 
8
- /**
9
- * @typedef {{
10
- * build?: { publish?: string }
11
- * functions?: { node_bundler?: 'zisi' | 'esbuild' }
12
- * }} NetlifyConfig
13
- */
14
-
15
5
  /**
16
6
  * @param {RouteSegment[]} a
17
7
  * @param {RouteSegment[]} b
@@ -44,31 +34,6 @@ export function matches(a, b) {
44
34
  }
45
35
  }
46
36
 
47
- /**
48
- * @param {NetlifyConfig | null} netlify_config
49
- * @param {import('@sveltejs/kit').Builder} builder
50
- * @returns {string | undefined}
51
- */
52
- export function get_publish_directory(netlify_config, builder) {
53
- if (netlify_config) {
54
- if (!netlify_config.build?.publish) {
55
- builder.log.minor('No publish directory specified in netlify.toml, using default');
56
- return;
57
- }
58
-
59
- if (resolve(netlify_config.build.publish) === process.cwd()) {
60
- throw new Error(
61
- 'The publish directory cannot be set to the site root. Please change it to another value such as "build" in netlify.toml.'
62
- );
63
- }
64
- return netlify_config.build.publish;
65
- }
66
-
67
- builder.log.warn(
68
- 'No netlify.toml found. Using default publish directory. Consult https://svelte.dev/docs/kit/adapter-netlify#usage for more details'
69
- );
70
- }
71
-
72
37
  /**
73
38
  * @param {*} value
74
39
  * @returns {string}