@sveltejs/adapter-netlify 7.0.0-next.1 → 7.0.0-next.10

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/ambient.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  declare global {
2
2
  namespace App {
3
3
  export interface Platform {
4
- context: import('@netlify/functions').Context;
4
+ context: import('@netlify/types').Context;
5
5
  }
6
6
  }
7
7
  }
package/files/edge.js CHANGED
@@ -1,28 +1,40 @@
1
- import { Server } from "0SERVER";
2
- import { manifest } from "MANIFEST";
3
- //#region src/edge.js
1
+ import { Server } from '0SERVER';
2
+ import { manifest } from 'MANIFEST';
3
+
4
4
  const server = new Server(manifest);
5
+
5
6
  /**
6
- * We don't know the origin until we receive a request, but
7
- * that's guaranteed to happen before we call `read`
8
- * @type {string}
9
- */
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}
10
+ */
10
11
  let origin;
12
+
11
13
  const initialized = server.init({
12
14
  env: Deno.env.toObject(),
13
15
  read: async (file) => {
14
16
  const url = `${origin}/${file}`;
15
17
  const response = await fetch(url);
16
- if (!response.ok) throw new Error(`read(...) failed: could not fetch ${url} (${response.status} ${response.statusText})`);
18
+
19
+ if (!response.ok) {
20
+ throw new Error(
21
+ `read(...) failed: could not fetch ${url} (${response.status} ${response.statusText})`
22
+ );
23
+ }
24
+
17
25
  return response.body;
18
26
  }
19
27
  });
28
+
20
29
  /** @type {import('@netlify/edge-functions').EdgeFunction} */
21
- async function handler(request, context) {
30
+ export default async function handler(request, context) {
22
31
  if (!origin) {
23
32
  origin = new URL(request.url).origin;
24
- await initialized;
25
33
  }
34
+
35
+ // always await initialization to prevent race condition with concurrent requests
36
+ await initialized;
37
+
26
38
  return server.respond(request, {
27
39
  platform: { context },
28
40
  getClientAddress() {
@@ -30,5 +42,3 @@ async function handler(request, context) {
30
42
  }
31
43
  });
32
44
  }
33
- //#endregion
34
- export { handler as default };
@@ -1,35 +1,26 @@
1
- import { Server } from "0SERVER";
2
- import { createReadStream } from "node:fs";
3
- import { Readable } from "node:stream";
4
- import process from "node:process";
5
- //#region ../kit/src/exports/node/index.js
1
+ import { Server } from '0SERVER';
2
+ import { createReadableStream } from '@sveltejs/kit/node';
3
+ import process from 'node:process';
4
+
6
5
  /**
7
- * Converts a file on disk to a readable stream
8
- * @param {string} file
9
- * @returns {ReadableStream}
10
- * @since 2.4.0
11
- */
12
- function createReadableStream(file) {
13
- return Readable.toWeb(createReadStream(file));
14
- }
15
- //#endregion
16
- //#region src/serverless.js
17
- /**
18
- * @param {import('@sveltejs/kit').SSRManifest} manifest
19
- * @returns {(request: Request, context: import('@netlify/functions').Context) => Promise<Response>}
20
- */
21
- function init(manifest) {
6
+ * @param {import('@sveltejs/kit').SSRManifest} manifest
7
+ * @returns {(request: Request, context: import('@netlify/types').Context) => Promise<Response>}
8
+ */
9
+ export function init(manifest) {
22
10
  const server = new Server(manifest);
11
+
23
12
  /** @type {Promise<void> | null} */
24
13
  let init_promise = server.init({
25
14
  env: process.env,
26
15
  read: (file) => createReadableStream(`.netlify/server/${file}`)
27
16
  });
17
+
28
18
  return async (request, context) => {
29
19
  if (init_promise !== null) {
30
20
  await init_promise;
31
21
  init_promise = null;
32
22
  }
23
+
33
24
  return server.respond(request, {
34
25
  platform: { context },
35
26
  getClientAddress() {
@@ -38,5 +29,3 @@ function init(manifest) {
38
29
  });
39
30
  };
40
31
  }
41
- //#endregion
42
- export { init };
package/index.d.ts CHANGED
@@ -1,4 +1,19 @@
1
1
  import { Adapter } from '@sveltejs/kit';
2
2
  import './ambient.d.ts';
3
3
 
4
- export default function plugin(opts?: { split?: boolean; edge?: boolean }): Adapter;
4
+ export interface AdapterOptions {
5
+ /**
6
+ * If `true`, your app will be deployed as a [Netlify Edge Function](https://docs.netlify.com/build/edge-functions/overview/) rather than the standard Node-based function.
7
+ * @default false
8
+ */
9
+ edge?: boolean;
10
+ /**
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
+ * @default false
15
+ */
16
+ split?: boolean;
17
+ }
18
+
19
+ export default function plugin(opts?: AdapterOptions): Adapter;
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { join, posix } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
4
  import { builtinModules } from 'node:module';
5
5
  import process from 'node:process';
6
6
  import toml from '@iarna/toml';
@@ -30,7 +30,7 @@ const netlify_framework_edge_path = '.netlify/v1/edge-functions';
30
30
 
31
31
  const FUNCTION_PREFIX = 'sveltekit-';
32
32
 
33
- /** @type {import('./index.js').default} */
33
+ /** @type {typeof import('./index.js').default} */
34
34
  export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
35
35
  return {
36
36
  name,
@@ -42,15 +42,15 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
42
42
  );
43
43
  }
44
44
 
45
- if (existsSync(`${builder.config.kit.files.assets}/_headers`)) {
45
+ if (existsSync(`${builder.config.files.assets}/_headers`)) {
46
46
  throw new Error(
47
- `The _headers file should be placed in the project root rather than the ${builder.config.kit.files.assets} directory`
47
+ `The _headers file should be placed in the project root rather than the ${builder.config.files.assets} directory`
48
48
  );
49
49
  }
50
50
 
51
- if (existsSync(`${builder.config.kit.files.assets}/_redirects`)) {
51
+ if (existsSync(`${builder.config.files.assets}/_redirects`)) {
52
52
  throw new Error(
53
- `The _redirects file should be placed in the project root rather than the ${builder.config.kit.files.assets} directory`
53
+ `The _redirects file should be placed in the project root rather than the ${builder.config.files.assets} directory`
54
54
  );
55
55
  }
56
56
 
@@ -60,19 +60,19 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
60
60
  const publish = get_publish_directory(netlify_config, builder) || 'build';
61
61
 
62
62
  // empty out existing build directories
63
- builder.rimraf(publish);
64
- builder.rimraf('.netlify/v1');
63
+ rmSync(publish, { force: true, recursive: true });
64
+ rmSync('.netlify/v1', { force: true, recursive: true });
65
65
 
66
66
  // clean up legacy directories from older adapter versions to avoid
67
67
  // gnarly edge cases when an existing project is upgraded to this version
68
- builder.rimraf('.netlify/edge-functions');
69
- builder.rimraf('.netlify/server');
70
- builder.rimraf('.netlify/package.json');
71
- builder.rimraf('.netlify/serverless.js');
68
+ rmSync('.netlify/edge-functions', { force: true, recursive: true });
69
+ rmSync('.netlify/server', { force: true, recursive: true });
70
+ rmSync('.netlify/package.json', { force: true, recursive: true });
71
+ rmSync('.netlify/serverless.js', { force: true, recursive: true });
72
72
  if (existsSync('.netlify/functions-internal')) {
73
73
  for (const file of readdirSync('.netlify/functions-internal')) {
74
74
  if (file.startsWith(FUNCTION_PREFIX)) {
75
- builder.rimraf(join('.netlify/functions-internal', file));
75
+ rmSync(join('.netlify/functions-internal', file), { force: true, recursive: true });
76
76
  }
77
77
  }
78
78
  }
@@ -80,7 +80,7 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
80
80
  builder.log.minor(`Publishing to "${publish}"`);
81
81
 
82
82
  builder.log.minor('Copying assets...');
83
- const publish_dir = `${publish}${builder.config.kit.paths.base}`;
83
+ const publish_dir = `${publish}${builder.config.paths.base}`;
84
84
  builder.writeClient(publish_dir);
85
85
  builder.writePrerendered(publish_dir);
86
86
 
@@ -118,7 +118,7 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
118
118
  */
119
119
  function generate_serverless_functions({ builder, publish, split }) {
120
120
  // https://docs.netlify.com/build/frameworks/frameworks-api/#netlifyv1functions
121
- builder.mkdirp(netlify_framework_serverless_path);
121
+ mkdirSync(netlify_framework_serverless_path, { recursive: true });
122
122
 
123
123
  builder.writeServer('.netlify/v1/server');
124
124
 
@@ -180,7 +180,8 @@ function generate_serverless_functions({ builder, publish, split }) {
180
180
  builder,
181
181
  routes,
182
182
  patterns,
183
- name
183
+ name,
184
+ type: 'split'
184
185
  });
185
186
  }
186
187
 
@@ -189,6 +190,7 @@ function generate_serverless_functions({ builder, publish, split }) {
189
190
  routes: [],
190
191
  patterns: ['/*'],
191
192
  name: `${FUNCTION_PREFIX}catch-all`,
193
+ type: 'catch-all',
192
194
  exclude: Array.from(seen)
193
195
  });
194
196
  } else {
@@ -196,7 +198,8 @@ function generate_serverless_functions({ builder, publish, split }) {
196
198
  builder,
197
199
  routes: undefined,
198
200
  patterns: ['/*'],
199
- name: `${FUNCTION_PREFIX}render`
201
+ name: `${FUNCTION_PREFIX}render`,
202
+ type: 'singular'
200
203
  });
201
204
  }
202
205
 
@@ -243,10 +246,12 @@ function write_frameworks_config({ builder }) {
243
246
  ]
244
247
  };
245
248
 
246
- builder.mkdirp('.netlify/v1');
249
+ mkdirSync('.netlify/v1', { recursive: true });
247
250
  writeFileSync(netlify_framework_config_path, s(config));
248
251
  }
249
252
 
253
+ /** @typedef {'singular' | 'split' | 'catch-all'} ServerlessFunctionType */
254
+
250
255
  /**
251
256
  *
252
257
  * @param {{
@@ -254,17 +259,18 @@ function write_frameworks_config({ builder }) {
254
259
  * routes: import('@sveltejs/kit').RouteDefinition[] | undefined,
255
260
  * patterns: string[],
256
261
  * name: string,
262
+ * type: ServerlessFunctionType,
257
263
  * exclude?: string[]
258
264
  * }} opts
259
265
  */
260
- function generate_serverless_function({ builder, routes, patterns, name, exclude }) {
266
+ function generate_serverless_function({ builder, routes, patterns, name, type, exclude }) {
261
267
  const manifest = builder.generateManifest({
262
268
  relativePath: '../server',
263
269
  routes
264
270
  });
265
271
 
266
- const fn = generate_serverless_function_module(manifest);
267
- const config = generate_config_export(patterns, exclude);
272
+ const fn = generate_serverless_function_module(manifest, type);
273
+ const config = generate_config_export(name, patterns, exclude);
268
274
 
269
275
  if (builder.hasServerInstrumentationFile()) {
270
276
  writeFileSync(`${netlify_framework_serverless_path}/${name}.mjs`, fn);
@@ -283,9 +289,63 @@ function generate_serverless_function({ builder, routes, patterns, name, exclude
283
289
 
284
290
  /**
285
291
  * @param {string} manifest
292
+ * @param {ServerlessFunctionType} type
286
293
  * @returns {string}
287
294
  */
288
- function generate_serverless_function_module(manifest) {
295
+ function generate_serverless_function_module(manifest, type) {
296
+ if (type === 'catch-all') {
297
+ // Netlify encodes the response body but `fetch` automatically decodes it.
298
+ // So, we need to remove the `content-encoding` header to allow Netlify
299
+ // to correctly re-encode it on the way out.
300
+ return `\
301
+ import { applyReroute } from '@sveltejs/kit/adapter';
302
+ import { init } from '../serverless.js';
303
+
304
+ const original_url_header = \`x-sveltekit-original-url-\${process.env.NETLIFY_FUNCTIONS_TOKEN}\`
305
+
306
+ const respond = init(${manifest});
307
+
308
+ export default async (request, context) => {
309
+ const catch_all_response = await respond(request, context);
310
+
311
+ return await applyReroute(catch_all_response, async (url) => {
312
+ const rerouted_request = new Request(url, request);
313
+ rerouted_request.headers.set(original_url_header, request.url);
314
+
315
+ const rerouted_response = await fetch(rerouted_request);
316
+
317
+ const response = new Response(rerouted_response.body, rerouted_response);
318
+ if (response.headers.has('content-encoding')) {
319
+ response.headers.delete('content-encoding');
320
+ response.headers.delete('content-length');
321
+ }
322
+
323
+ return response;
324
+ });
325
+ };
326
+ `;
327
+ }
328
+
329
+ if (type === 'split') {
330
+ return `\
331
+ import { init } from '../serverless.js';
332
+
333
+ const original_url_header = \`x-sveltekit-original-url-\${process.env.NETLIFY_FUNCTIONS_TOKEN}\`
334
+
335
+ const respond = init(${manifest});
336
+
337
+ export default async (request, context) => {
338
+ if (request.headers.has(original_url_header)) {
339
+ const original_url = request.headers.get(original_url_header);
340
+ request = new Request(original_url, request);
341
+ request.headers.delete(original_url_header);
342
+ }
343
+
344
+ return await respond(request, context);
345
+ };
346
+ `;
347
+ }
348
+
289
349
  return `\
290
350
  import { init } from '../serverless.js';
291
351
 
@@ -296,17 +356,18 @@ export default init(${manifest});
296
356
  const generator_string = `@sveltejs/adapter-netlify@${adapter_version}`;
297
357
 
298
358
  /**
359
+ * @param {string} name The name that shows up in the logs & metrics functions list
299
360
  * @param {string[]} patterns
300
361
  * @param {string[]} [exclude]
301
362
  * @returns {string}
302
363
  */
303
- function generate_config_export(patterns, exclude = []) {
364
+ function generate_config_export(name, patterns, exclude = []) {
304
365
  // TODO: add a human friendly name for the function https://docs.netlify.com/build/frameworks/frameworks-api/#configuration-options-2
305
366
 
306
367
  // https://docs.netlify.com/build/frameworks/frameworks-api/#configuration-options-2
307
368
  return `\
308
369
  export const config = {
309
- name: 'SvelteKit server',
370
+ name: ${JSON.stringify(name)},
310
371
  generator: '${generator_string}',
311
372
  path: [${patterns.map(s).join(', ')}],
312
373
  excludedPath: [${['/.netlify/*', ...exclude].map(s).join(', ')}],
@@ -354,11 +415,11 @@ const rolldown_config = {
354
415
  */
355
416
  async function generate_edge_functions({ builder }) {
356
417
  const tmp = builder.getBuildDirectory('netlify-tmp');
357
- builder.rimraf(tmp);
358
- builder.mkdirp(tmp);
418
+ rmSync(tmp, { force: true, recursive: true });
419
+ mkdirSync(tmp, { recursive: true });
359
420
 
360
421
  // https://docs.netlify.com/build/frameworks/frameworks-api/#edge-functions
361
- builder.mkdirp('.netlify/v1/edge-functions');
422
+ mkdirSync('.netlify/v1/edge-functions', { recursive: true });
362
423
 
363
424
  builder.log.minor('Generating Edge Function...');
364
425
  const relativePath = posix.relative(tmp, builder.getServerDirectory());
@@ -377,8 +438,7 @@ async function generate_edge_functions({ builder }) {
377
438
  writeFileSync(`${tmp}/manifest.js`, `export const manifest = ${manifest};\n`);
378
439
 
379
440
  /** @type {{ assets: Set<string> }} */
380
- // we have to prepend the file:// protocol because Windows doesn't support absolute path imports
381
- const { assets } = (await import(`file://${tmp}/manifest.js`)).manifest;
441
+ const { assets } = (await import(pathToFileURL(`${tmp}/manifest.js`).href)).manifest;
382
442
 
383
443
  const path = '/*';
384
444
  // We only need to specify paths without the trailing slash because
@@ -387,16 +447,14 @@ async function generate_edge_functions({ builder }) {
387
447
  // Contains static files
388
448
  `/${builder.getAppPath()}/immutable/*`,
389
449
  `/${builder.getAppPath()}/version.json`,
390
- ...builder.prerendered.paths,
450
+ // the base root and `trailingSlash: 'always'` pages are recorded with a trailing slash
451
+ ...builder.prerendered.paths.map((path) => (path === '/' ? path : path.replace(/\/$/, ''))),
391
452
  ...Array.from(assets).flatMap((asset) => {
392
453
  if (asset.endsWith('/index.html')) {
393
454
  const dir = asset.replace(/\/index\.html$/, '');
394
- return [
395
- `${builder.config.kit.paths.base}/${asset}`,
396
- `${builder.config.kit.paths.base}/${dir}`
397
- ];
455
+ return [`${builder.config.paths.base}/${asset}`, `${builder.config.paths.base}/${dir}`];
398
456
  }
399
- return `${builder.config.kit.paths.base}/${asset}`;
457
+ return `${builder.config.paths.base}/${asset}`;
400
458
  }),
401
459
  // Should not be served by SvelteKit at all
402
460
  '/.netlify/*'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltejs/adapter-netlify",
3
- "version": "7.0.0-next.1",
3
+ "version": "7.0.0-next.10",
4
4
  "description": "A SvelteKit adapter that creates a Netlify app",
5
5
  "keywords": [
6
6
  "adapter",
@@ -27,37 +27,34 @@
27
27
  },
28
28
  "types": "index.d.ts",
29
29
  "files": [
30
- "files",
30
+ "files/*.js",
31
31
  "index.js",
32
+ "utils.js",
32
33
  "index.d.ts",
33
34
  "ambient.d.ts"
34
35
  ],
35
36
  "dependencies": {
36
37
  "@iarna/toml": "^2.2.5",
37
- "rolldown": "^1.1.2"
38
+ "@netlify/types": "^2.8.0",
39
+ "rolldown": "^1.2.3"
38
40
  },
39
41
  "devDependencies": {
40
- "@netlify/dev": "^4.11.2",
41
- "@netlify/edge-functions": "^3.0.3",
42
- "@netlify/functions": "^5.1.2",
43
- "@netlify/node-cookies": "^0.1.0",
44
- "@netlify/types": "^2.3.0",
42
+ "@netlify/edge-functions": "^3.0.8",
43
+ "@types/deno": "^2.7.0",
45
44
  "@types/node": "^22.19.19",
46
- "typescript": "^6.0.3",
47
- "vitest": "^4.1.9",
48
- "@sveltejs/kit": "^3.0.0-next.6"
45
+ "typescript": "^7.0.2",
46
+ "vitest": "^4.1.10",
47
+ "@sveltejs/kit": "^3.0.0-next.25"
49
48
  },
50
49
  "peerDependencies": {
51
50
  "@sveltejs/kit": "^2.31.0"
52
51
  },
53
52
  "scripts": {
54
- "dev": "rolldown -cw",
55
- "build": "rolldown -c",
56
- "check": "tsc",
57
- "lint": "prettier --check .",
58
- "format": "pnpm lint --write",
59
- "test": "pnpm test:unit && pnpm test:integration",
53
+ "check": "tsc && tsc --project files/tsconfig.json",
54
+ "lint": "oxfmt --check .",
55
+ "format": "oxfmt --write .",
60
56
  "test:unit": "vitest run",
61
- "test:integration": "pnpm build && pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test"
57
+ "test:build": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" build",
58
+ "test": "pnpm test:unit && pnpm test:build"
62
59
  }
63
60
  }
package/utils.js ADDED
@@ -0,0 +1,78 @@
1
+ import { resolve } from 'node:path';
2
+ import process from 'node:process';
3
+
4
+ /**
5
+ * @typedef {{ rest: boolean, dynamic: boolean, content: string }} RouteSegment
6
+ */
7
+
8
+ /**
9
+ * @typedef {{
10
+ * build?: { publish?: string }
11
+ * functions?: { node_bundler?: 'zisi' | 'esbuild' }
12
+ * }} NetlifyConfig
13
+ */
14
+
15
+ /**
16
+ * @param {RouteSegment[]} a
17
+ * @param {RouteSegment[]} b
18
+ * @returns {boolean}
19
+ */
20
+ export function matches(a, b) {
21
+ if (a[0] && b[0]) {
22
+ if (b[0].rest) {
23
+ if (b.length === 1) return true;
24
+
25
+ const next_b = b.slice(1);
26
+
27
+ for (let i = 0; i < a.length; i += 1) {
28
+ if (matches(a.slice(i), next_b)) return true;
29
+ }
30
+
31
+ return false;
32
+ }
33
+
34
+ if (!b[0].dynamic) {
35
+ if (!a[0].dynamic && a[0].content !== b[0].content) return false;
36
+ }
37
+
38
+ if (a.length === 1 && b.length === 1) return true;
39
+ return matches(a.slice(1), b.slice(1));
40
+ } else if (a[0]) {
41
+ return a.length === 1 && a[0].rest;
42
+ } else {
43
+ return b.length === 1 && b[0].rest;
44
+ }
45
+ }
46
+
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
+ /**
73
+ * @param {*} value
74
+ * @returns {string}
75
+ */
76
+ export function s(value) {
77
+ return JSON.stringify(value, null, '\t');
78
+ }