@sveltejs/kit 3.0.0-next.0 → 3.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.
Files changed (127) hide show
  1. package/package.json +33 -21
  2. package/src/core/adapt/builder.js +29 -43
  3. package/src/core/adapt/index.js +1 -4
  4. package/src/core/config/index.js +132 -71
  5. package/src/core/config/options.js +294 -244
  6. package/src/core/config/types.d.ts +1 -1
  7. package/src/core/env.js +121 -5
  8. package/src/core/generate_manifest/index.js +12 -15
  9. package/src/core/postbuild/analyse.js +7 -19
  10. package/src/core/postbuild/crawl.js +22 -6
  11. package/src/core/postbuild/prerender.js +42 -23
  12. package/src/core/sync/create_manifest_data/index.js +53 -50
  13. package/src/core/sync/sync.js +0 -2
  14. package/src/core/sync/write_client_manifest.js +8 -15
  15. package/src/core/sync/write_env.js +2 -1
  16. package/src/core/sync/write_non_ambient.js +12 -9
  17. package/src/core/sync/write_server.js +13 -14
  18. package/src/core/sync/write_tsconfig.js +16 -8
  19. package/src/core/sync/write_tsconfig_test/package.json +7 -0
  20. package/src/core/sync/write_types/index.js +28 -24
  21. package/src/core/utils.js +2 -2
  22. package/src/exports/env/index.js +12 -0
  23. package/src/exports/hooks/index.js +3 -9
  24. package/src/exports/hooks/sequence.js +3 -2
  25. package/src/exports/index.js +35 -13
  26. package/src/exports/internal/client.js +5 -0
  27. package/src/exports/internal/env.js +2 -2
  28. package/src/exports/internal/index.js +1 -90
  29. package/src/exports/internal/{event.js → server/event.js} +1 -2
  30. package/src/exports/internal/server/index.js +33 -0
  31. package/src/exports/internal/shared.js +89 -0
  32. package/src/exports/node/index.js +62 -15
  33. package/src/exports/params.js +63 -0
  34. package/src/exports/public.d.ts +323 -170
  35. package/src/exports/url.js +86 -0
  36. package/src/exports/vite/build/build_server.js +53 -59
  37. package/src/exports/vite/build/remote.js +18 -11
  38. package/src/exports/vite/build/utils.js +0 -8
  39. package/src/exports/vite/dev/index.js +42 -44
  40. package/src/exports/vite/index.js +810 -593
  41. package/src/exports/vite/preview/index.js +29 -22
  42. package/src/exports/vite/static_analysis/index.js +2 -4
  43. package/src/exports/vite/static_analysis/types.d.ts +14 -0
  44. package/src/exports/vite/utils.js +21 -36
  45. package/src/runtime/app/env/internal.js +4 -4
  46. package/src/runtime/app/env/types.d.ts +1 -1
  47. package/src/runtime/app/environment/index.js +6 -0
  48. package/src/runtime/app/forms.js +24 -7
  49. package/src/runtime/app/paths/client.js +4 -10
  50. package/src/runtime/app/paths/internal/client.js +4 -2
  51. package/src/runtime/app/paths/internal/server.js +2 -23
  52. package/src/runtime/app/paths/public.d.ts +0 -28
  53. package/src/runtime/app/paths/server.js +9 -5
  54. package/src/runtime/app/server/remote/command.js +0 -3
  55. package/src/runtime/app/server/remote/form.js +27 -15
  56. package/src/runtime/app/server/remote/prerender.js +29 -36
  57. package/src/runtime/app/server/remote/query.js +101 -99
  58. package/src/runtime/app/server/remote/requested.js +22 -14
  59. package/src/runtime/app/server/remote/shared.js +30 -26
  60. package/src/runtime/app/state/client.js +1 -2
  61. package/src/runtime/app/stores.js +13 -76
  62. package/src/runtime/client/bundle.js +1 -1
  63. package/src/runtime/client/client-entry.js +3 -0
  64. package/src/runtime/client/client.js +411 -318
  65. package/src/runtime/client/entry.js +24 -3
  66. package/src/runtime/client/fetcher.js +3 -2
  67. package/src/runtime/client/ndjson.js +6 -33
  68. package/src/runtime/client/payload.js +17 -0
  69. package/src/runtime/client/remote-functions/cache.svelte.js +3 -1
  70. package/src/runtime/client/remote-functions/command.svelte.js +7 -32
  71. package/src/runtime/client/remote-functions/form.svelte.js +183 -112
  72. package/src/runtime/client/remote-functions/prerender.svelte.js +29 -8
  73. package/src/runtime/client/remote-functions/query/index.js +7 -14
  74. package/src/runtime/client/remote-functions/query/instance.svelte.js +63 -18
  75. package/src/runtime/client/remote-functions/query/proxy.js +3 -3
  76. package/src/runtime/client/remote-functions/query-batch.svelte.js +60 -68
  77. package/src/runtime/client/remote-functions/query-live/instance.svelte.js +60 -18
  78. package/src/runtime/client/remote-functions/query-live/iterator.js +36 -55
  79. package/src/runtime/client/remote-functions/shared.svelte.js +88 -62
  80. package/src/runtime/client/sse.js +32 -0
  81. package/src/runtime/client/state.svelte.js +65 -49
  82. package/src/runtime/client/stream.js +38 -0
  83. package/src/runtime/client/types.d.ts +11 -7
  84. package/src/runtime/client/utils.js +0 -96
  85. package/src/runtime/components/root.svelte +66 -0
  86. package/src/runtime/env/dynamic/private.js +7 -0
  87. package/src/runtime/env/dynamic/public.js +7 -0
  88. package/src/runtime/env/static/private.js +6 -0
  89. package/src/runtime/env/static/public.js +6 -0
  90. package/src/runtime/form-utils.js +100 -22
  91. package/src/runtime/server/cookie.js +69 -52
  92. package/src/runtime/server/csrf.js +65 -0
  93. package/src/runtime/server/data/index.js +14 -18
  94. package/src/runtime/server/env_module.js +0 -5
  95. package/src/runtime/server/index.js +2 -2
  96. package/src/runtime/server/page/actions.js +41 -26
  97. package/src/runtime/server/page/index.js +9 -15
  98. package/src/runtime/server/page/load_data.js +1 -1
  99. package/src/runtime/server/page/render.js +112 -187
  100. package/src/runtime/server/page/respond_with_error.js +7 -8
  101. package/src/runtime/server/page/server_routing.js +27 -18
  102. package/src/runtime/server/remote.js +355 -216
  103. package/src/runtime/server/respond.js +97 -61
  104. package/src/runtime/server/utils.js +32 -9
  105. package/src/runtime/shared.js +83 -13
  106. package/src/runtime/telemetry/otel.js +1 -1
  107. package/src/runtime/types.d.ts +8 -0
  108. package/src/types/ambient.d.ts +10 -5
  109. package/src/types/global-private.d.ts +15 -22
  110. package/src/types/internal.d.ts +89 -74
  111. package/src/types/private.d.ts +33 -1
  112. package/src/utils/error.js +24 -4
  113. package/src/utils/import.js +6 -1
  114. package/src/utils/imports.js +83 -0
  115. package/src/utils/mime.js +9 -0
  116. package/src/utils/params.js +66 -0
  117. package/src/utils/routing.js +90 -44
  118. package/src/utils/shared-iterator.js +5 -0
  119. package/src/utils/streaming.js +14 -4
  120. package/src/utils/url.js +20 -2
  121. package/src/version.js +1 -1
  122. package/types/index.d.ts +467 -537
  123. package/types/index.d.ts.map +22 -39
  124. package/src/core/sync/write_root.js +0 -148
  125. package/src/exports/internal/server.js +0 -22
  126. package/src/types/synthetic/$lib.md +0 -5
  127. /package/src/exports/internal/{remote-functions.js → server/remote-functions.js} +0 -0
@@ -0,0 +1,86 @@
1
+ import { DEV } from 'esm-env';
2
+ // we use the export subpath to conditionally import the client/server `get_origin`
3
+ // so that `node:async_hooks` isn't pulled into the client build
4
+ import { get_origin } from '#internal';
5
+ import { matches_external_allowlist_entry } from '../utils/url.js';
6
+
7
+ // See https://datatracker.ietf.org/doc/html/rfc2606 - no domains under the .invalid TLD can be registered
8
+ const REDIRECT_BASE = 'https://sveltekit-redirect.invalid';
9
+
10
+ /**
11
+ * Whether a redirect location is absolute, i.e. not a root-relative or path-relative URL,
12
+ * and not pointing to the same origin as we're currently on (if determineable).
13
+ * @param {string} location
14
+ */
15
+ export function is_external_location(location) {
16
+ const origin = get_origin();
17
+
18
+ try {
19
+ return !matches_external_allowlist_entry(location, origin ?? REDIRECT_BASE);
20
+ } catch {
21
+ return true;
22
+ }
23
+ }
24
+
25
+ const javascript_protocols = new Set(['javascript:', 'data:']);
26
+
27
+ /**
28
+ * @param {string} location
29
+ */
30
+ function is_javascript_location(location) {
31
+ try {
32
+ return javascript_protocols.has(new URL(location, REDIRECT_BASE).protocol);
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * @param {string} location
40
+ * @param {{ external?: boolean | string[] }} [options]
41
+ */
42
+ export function validate_redirect_location(location, options) {
43
+ if (!is_external_location(location)) return;
44
+
45
+ const external = options?.external;
46
+
47
+ if (!external) {
48
+ throw new Error(
49
+ DEV
50
+ ? `Cannot redirect to external URL ${JSON.stringify(location)}. ` +
51
+ 'To redirect to an external URL, pass `{ external: true }` or an allowlist of permitted origins as the third argument to `redirect`'
52
+ : 'Cannot redirect to external URL unless explicitly allowed'
53
+ );
54
+ }
55
+
56
+ if (external === true) {
57
+ if (is_javascript_location(location)) {
58
+ throw new Error(
59
+ DEV
60
+ ? `Cannot redirect to ${JSON.stringify(location)} with \`{ external: true }\`. ` +
61
+ 'The `javascript:` and `data:` protocols must be explicitly listed in the `external` allowlist'
62
+ : 'Cannot redirect to external URL unless explicitly allowed'
63
+ );
64
+ }
65
+
66
+ return;
67
+ }
68
+
69
+ if (Array.isArray(external)) {
70
+ if (!external.some((allowed) => matches_external_allowlist_entry(location, allowed))) {
71
+ throw new Error(
72
+ DEV
73
+ ? `Cannot redirect to ${JSON.stringify(location)}: URL origin is not included in the \`external\` allowlist`
74
+ : 'Cannot redirect to external URL unless explicitly allowed'
75
+ );
76
+ }
77
+
78
+ return;
79
+ }
80
+
81
+ throw new Error(
82
+ DEV
83
+ ? '`redirect` options.external must be `true` or an array of allowed origins'
84
+ : 'Invalid redirect options.external value'
85
+ );
86
+ }
@@ -16,39 +16,16 @@ import { fix_css_urls } from '../../../utils/css.js';
16
16
  import { escape_for_interpolation } from '../../../utils/escape.js';
17
17
 
18
18
  /**
19
- * @overload Build without the client manifest so we can analyse the nodes.
20
19
  * @param {string} out
21
20
  * @param {ValidatedKitConfig} kit
22
21
  * @param {ManifestData} manifest_data
23
22
  * @param {Manifest} server_manifest
24
- * @param {null} client_manifest
25
- * @param {null} assets_path
26
- * @param {null} client_chunks
27
- * @param {string} root
28
- * @returns {void}
29
- */
30
- /**
31
- * @overload Or build with the client manifest
32
- * @param {string} out
33
- * @param {ValidatedKitConfig} kit
34
- * @param {ManifestData} manifest_data
35
- * @param {Manifest} server_manifest
36
- * @param {Manifest} client_manifest
23
+ * @param {Manifest | null} client_manifest
37
24
  * @param {string} assets_path
38
- * @param {Rolldown.RolldownOutput['output']} client_chunks
25
+ * @param {(Rolldown.OutputAsset | Rolldown.OutputChunk)[]} chunks
39
26
  * @param {string} root
40
27
  * @returns {void}
41
28
  */
42
- /**
43
- * @param {string} out
44
- * @param {ValidatedKitConfig} kit
45
- * @param {ManifestData} manifest_data
46
- * @param {Manifest} server_manifest
47
- * @param {Manifest | null} client_manifest
48
- * @param {string | null} assets_path
49
- * @param {Rolldown.RolldownOutput['output'] | null} client_chunks
50
- * @param {string} root
51
- */
52
29
  export function build_server_nodes(
53
30
  out,
54
31
  kit,
@@ -56,7 +33,7 @@ export function build_server_nodes(
56
33
  server_manifest,
57
34
  client_manifest,
58
35
  assets_path,
59
- client_chunks,
36
+ chunks,
60
37
  root
61
38
  ) {
62
39
  mkdirp(`${out}/server/nodes`);
@@ -75,8 +52,8 @@ export function build_server_nodes(
75
52
  */
76
53
  let prepare_css_for_inlining = (css) => s(css);
77
54
 
78
- if (client_chunks && kit.inlineStyleThreshold > 0 && kit.output.bundleStrategy === 'split') {
79
- for (const chunk of client_chunks) {
55
+ if (chunks && kit.inlineStyleThreshold > 0 && kit.output.bundleStrategy === 'split') {
56
+ for (const chunk of chunks) {
80
57
  if (chunk.type !== 'asset' || !chunk.fileName.endsWith('.css')) {
81
58
  continue;
82
59
  }
@@ -132,6 +109,9 @@ export function build_server_nodes(
132
109
  }
133
110
  }
134
111
 
112
+ /** path to the `.svelte-kit` directory */
113
+ const out_dir = normalizePath(kit.outDir);
114
+
135
115
  for (let i = 0; i < manifest_data.nodes.length; i++) {
136
116
  const node = manifest_data.nodes[i];
137
117
 
@@ -155,7 +135,11 @@ export function build_server_nodes(
155
135
  /** @type {Set<string>} */
156
136
  const eager_assets = new Set();
157
137
 
158
- if (node.component && client_manifest) {
138
+ const uses_server_component = node.child_pages
139
+ ? node.child_pages.some((child) => child.page_options?.ssr !== false)
140
+ : node.page_options?.ssr !== false;
141
+
142
+ if (node.component && uses_server_component) {
159
143
  exports.push(
160
144
  'let component_cache;',
161
145
  `export const component = async () => component_cache ??= (await import('../${
@@ -165,7 +149,12 @@ export function build_server_nodes(
165
149
  }
166
150
 
167
151
  if (node.universal) {
168
- if (!!node.page_options && node.page_options.ssr === false) {
152
+ if (
153
+ (kit.router.type === 'hash' &&
154
+ node.page_options !== null &&
155
+ node.page_options?.ssr === undefined) ||
156
+ (node.page_options && node.page_options.ssr === false)
157
+ ) {
169
158
  exports.push(`export const universal = ${s(node.page_options, null, 2)};`);
170
159
  } else {
171
160
  imports.push(
@@ -185,18 +174,7 @@ export function build_server_nodes(
185
174
  exports.push(`export const server_id = ${s(node.server)};`);
186
175
  }
187
176
 
188
- if (
189
- client_manifest &&
190
- (node.universal || node.component) &&
191
- kit.output.bundleStrategy === 'split'
192
- ) {
193
- const entry_path = `${normalizePath(kit.outDir)}/generated/client-optimized/nodes/${i}.js`;
194
- const entry = find_deps(client_manifest, entry_path, true, root);
195
-
196
- // Eagerly load client stylesheets and fonts imported by the SSR-ed page to avoid FOUC.
197
- // However, if it is not used during SSR (not present in the server manifest),
198
- // then it can be lazily loaded in the browser.
199
-
177
+ if ((node.universal || node.component) && kit.output.bundleStrategy === 'split') {
200
178
  /** @type {AssetDependencies | undefined} */
201
179
  let component;
202
180
  if (node.component) {
@@ -209,25 +187,41 @@ export function build_server_nodes(
209
187
  universal = find_deps(server_manifest, node.universal, true, root);
210
188
  }
211
189
 
212
- /** @type {Set<string>} */
213
- const eager_css = new Set();
190
+ if (client_manifest) {
191
+ const entry_path = `${out_dir}/generated/client-optimized/nodes/${i}.js`;
192
+ const entry = find_deps(client_manifest, entry_path, true, root);
214
193
 
215
- entry.stylesheet_map.forEach((value, filepath) => {
216
- // pages and layouts are renamed to node indexes when optimised for the client
217
- // so we use the original filename instead to check against the server manifest
218
- if (filepath === entry_path) {
219
- filepath = node.component ?? filepath;
220
- }
194
+ // Eagerly load client stylesheets and fonts imported by the SSR-ed page to avoid FOUC.
195
+ // However, if it is not used during SSR (not present in the server manifest),
196
+ // then it can be lazily loaded in the browser.
221
197
 
222
- if (component?.stylesheet_map.has(filepath) || universal?.stylesheet_map.has(filepath)) {
223
- value.css.forEach((file) => eager_css.add(file));
224
- value.assets.forEach((file) => eager_assets.add(file));
225
- }
226
- });
198
+ /** @type {Set<string>} */
199
+ const eager_css = new Set();
200
+
201
+ entry.stylesheet_map.forEach((value, filepath) => {
202
+ // pages and layouts are renamed to node indexes when optimised for the client
203
+ // so we use the original filename instead to check against the server manifest
204
+ if (filepath === entry_path) {
205
+ filepath = node.component ?? filepath;
206
+ }
207
+
208
+ if (component?.stylesheet_map.has(filepath) || universal?.stylesheet_map.has(filepath)) {
209
+ value.css.forEach((file) => eager_css.add(file));
210
+ value.assets.forEach((file) => eager_assets.add(file));
211
+ }
212
+ });
227
213
 
228
- imported = entry.imports;
229
- stylesheets = Array.from(eager_css);
230
- fonts = filter_fonts(Array.from(eager_assets));
214
+ imported = entry.imports;
215
+ stylesheets = Array.from(eager_css);
216
+ fonts = filter_fonts(Array.from(eager_assets));
217
+ } else {
218
+ for (const entry of [component, universal]) {
219
+ if (!entry) continue;
220
+ imported.push(...entry.imports);
221
+ stylesheets.push(...entry.stylesheets);
222
+ fonts.push(...entry.fonts);
223
+ }
224
+ }
231
225
  }
232
226
 
233
227
  exports.push(
@@ -244,7 +238,7 @@ export function build_server_nodes(
244
238
 
245
239
  // Keep track of Vite asset filenames so that we avoid touching unrelated ones
246
240
  // when adjusting the inlined CSS
247
- if (stylesheets_to_inline.size && assets_path && eager_assets.size) {
241
+ if (stylesheets_to_inline.size && eager_assets.size) {
248
242
  vite_assets = new Set(
249
243
  Array.from(eager_assets).map((asset) => {
250
244
  return decodeURIComponent(asset.replace(`${assets_path}/`, ''));
@@ -13,7 +13,7 @@ import { posixify } from '../../../utils/os.js';
13
13
  * @param {Array<{ hash: string, file: string }>} remotes
14
14
  * @param {ServerMetadata} metadata
15
15
  * @param {string} cwd
16
- * @param {Rolldown.RolldownOutput} server_bundle
16
+ * @param {(Rolldown.OutputAsset | Rolldown.OutputChunk)[]} server_chunks
17
17
  * @param {NonNullable<import('vitest/config').ViteUserConfig['build']>['sourcemap']} sourcemap
18
18
  */
19
19
  export async function treeshake_prerendered_remotes(
@@ -22,11 +22,14 @@ export async function treeshake_prerendered_remotes(
22
22
  remotes,
23
23
  metadata,
24
24
  cwd,
25
- server_bundle,
25
+ server_chunks,
26
26
  sourcemap
27
27
  ) {
28
28
  if (remotes.length === 0) return;
29
29
 
30
+ /** @type {string[]} */
31
+ const chunk_paths = [];
32
+
30
33
  for (const remote of remotes) {
31
34
  const exports_map = metadata.remotes.get(remote.hash);
32
35
  if (!exports_map) continue;
@@ -45,7 +48,7 @@ export async function treeshake_prerendered_remotes(
45
48
  // remove file extension
46
49
  const remote_filename = path.basename(remote.file).split('.').slice(0, -1).join('.');
47
50
 
48
- const remote_chunk = Object.values(server_bundle).find((chunk) => {
51
+ const remote_chunk = server_chunks.find((chunk) => {
49
52
  return chunk.name === remote_filename;
50
53
  });
51
54
 
@@ -88,8 +91,13 @@ export async function treeshake_prerendered_remotes(
88
91
 
89
92
  const stubbed = modified_code.toString();
90
93
  fs.writeFileSync(chunk_path, stubbed);
94
+ chunk_paths.push(chunk_path);
95
+ }
96
+
97
+ if (!chunk_paths.length) return;
91
98
 
92
- const bundle = /** @type {import('vite').Rolldown.RolldownOutput} */ (
99
+ for (const chunk_path of chunk_paths) {
100
+ const bundle = /** @type {Rolldown.RolldownOutput} */ (
93
101
  await vite.build({
94
102
  configFile: false,
95
103
  build: {
@@ -97,7 +105,7 @@ export async function treeshake_prerendered_remotes(
97
105
  ssr: true,
98
106
  target: 'esnext',
99
107
  sourcemap,
100
- rollupOptions: {
108
+ rolldownOptions: {
101
109
  // avoid resolving imports
102
110
  external: (id) => !id.endsWith(chunk_path),
103
111
  input: {
@@ -108,14 +116,13 @@ export async function treeshake_prerendered_remotes(
108
116
  })
109
117
  );
110
118
 
111
- const chunk = bundle.output.find(
112
- (output) => output.type === 'chunk' && output.name === 'treeshaken'
113
- );
114
- if (chunk && chunk.type === 'chunk') {
115
- fs.writeFileSync(chunk_path, chunk.code);
119
+ for (const output of bundle.output) {
120
+ if (output.type !== 'chunk' || output.name !== 'treeshaken') return;
121
+
122
+ fs.writeFileSync(chunk_path, output.code);
116
123
 
117
124
  const chunk_sourcemap = bundle.output.find(
118
- (output) => output.type === 'asset' && output.fileName === chunk.fileName + '.map'
125
+ (o) => o.type === 'asset' && o.fileName === output.fileName + '.map'
119
126
  );
120
127
  if (chunk_sourcemap && chunk_sourcemap.type === 'asset') {
121
128
  fs.writeFileSync(chunk_path + '.map', chunk_sourcemap.source);
@@ -124,14 +124,6 @@ export function filter_fonts(assets) {
124
124
  return assets.filter((asset) => /\.(woff2?|ttf|otf)$/.test(asset));
125
125
  }
126
126
 
127
- /**
128
- * @param {import('types').ValidatedKitConfig} config
129
- * @returns {string}
130
- */
131
- export function assets_base(config) {
132
- return (config.paths.assets || config.paths.base || '.') + '/';
133
- }
134
-
135
127
  /**
136
128
  * Writes a function with arguments used by a template literal.
137
129
  * This helps us store strings in a module and inject values at runtime.
@@ -10,12 +10,14 @@ import { isCSSRequest, loadEnv, buildErrorMessage } from 'vite';
10
10
  import { createReadableStream, getRequest, setResponse } from '../../../exports/node/index.js';
11
11
  import { coalesce_to_error } from '../../../utils/error.js';
12
12
  import { resolve_entry } from '../../../utils/filesystem.js';
13
+ import { load_and_validate_params } from '../../../utils/params.js';
13
14
  import { from_fs, to_fs } from '../../../utils/vite.js';
14
15
  import { posixify } from '../../../utils/os.js';
15
16
  import { load_error_page } from '../../../core/config/index.js';
16
17
  import { SVELTE_KIT_ASSETS } from '../../../constants.js';
17
18
  import * as sync from '../../../core/sync/sync.js';
18
19
  import { get_mime_lookup, get_runtime_base } from '../../../core/utils.js';
20
+ import '../../../utils/mime.js'; // extend mrmime with additional types (affects sirv too)
19
21
  import { compact } from '../../../utils/array.js';
20
22
  import { is_chrome_devtools_request, not_found } from '../utils.js';
21
23
  import { SCHEME } from '../../../utils/url.js';
@@ -31,10 +33,9 @@ const vite_css_query_regex = /(?:\?|&)(?:raw|url|inline)(?:&|$)/;
31
33
  * @param {import('types').ValidatedConfig} svelte_config
32
34
  * @param {() => Array<{ hash: string, file: string }>} get_remotes
33
35
  * @param {string} root The project root directory
34
- * @param {import('@sveltejs/kit').Adapter | undefined} adapter
35
36
  * @return {Promise<Promise<() => void>>}
36
37
  */
37
- export async function dev(vite, vite_config, svelte_config, get_remotes, root, adapter) {
38
+ export async function dev(vite, vite_config, svelte_config, get_remotes, root) {
38
39
  /** @type {AsyncLocalStorage<{ event: RequestEvent, config: any, prerender: PrerenderOption }>} */
39
40
  const async_local_storage = new AsyncLocalStorage();
40
41
 
@@ -42,7 +43,12 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
42
43
  const context = async_local_storage.getStore();
43
44
  if (!context || context.prerender === true) return;
44
45
 
45
- check_feature(/** @type {string} */ (context.event.route.id), context.config, label, adapter);
46
+ check_feature(
47
+ /** @type {string} */ (context.event.route.id),
48
+ context.config,
49
+ label,
50
+ svelte_config.kit.adapter
51
+ );
46
52
  };
47
53
 
48
54
  const fetch = globalThis.fetch;
@@ -79,6 +85,10 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
79
85
  vite.config.logger.error(msg, { error: err });
80
86
  }
81
87
 
88
+ // TODO this is inadequate — it doesn't reliably show the overlay on every page load,
89
+ // and when it does appear it may immediately vanish. `vite.ws.send` broadcasts
90
+ // to all connected clients, even ones that are unaffected by the error.
91
+ // we need a more considered approach
82
92
  vite.ws.send({
83
93
  type: 'error',
84
94
  err: /** @type {import('vite').ErrorPayload['err']} */ ({
@@ -106,10 +116,17 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
106
116
  return { module, module_node, url };
107
117
  }
108
118
 
109
- function update_manifest() {
119
+ async function update_manifest() {
110
120
  try {
111
121
  ({ manifest_data } = sync.create(svelte_config, root));
112
122
 
123
+ await load_and_validate_params({
124
+ routes: manifest_data.routes,
125
+ params_path: manifest_data.params,
126
+ root,
127
+ load: (file) => loud_ssr_load_module(file)
128
+ });
129
+
113
130
  if (manifest_error) {
114
131
  manifest_error = null;
115
132
  vite.ws.send({ type: 'full-reload' });
@@ -288,22 +305,18 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
288
305
  })
289
306
  ),
290
307
  matchers: async () => {
291
- /** @type {Record<string, import('@sveltejs/kit').ParamMatcher>} */
292
- const matchers = {};
293
-
294
- for (const key in manifest_data.matchers) {
295
- const file = manifest_data.matchers[key];
296
- const url = path.resolve(root, file);
297
- const module = await vite.ssrLoadModule(url, { fixStacktrace: true });
298
-
299
- if (module.match) {
300
- matchers[key] = module.match;
301
- } else {
302
- throw new Error(`${file} does not export a \`match\` function`);
303
- }
308
+ if (!manifest_data.params) return {};
309
+
310
+ const url = path.resolve(root, manifest_data.params);
311
+ const module = await vite.ssrLoadModule(url, { fixStacktrace: true });
312
+
313
+ if (!module.params) {
314
+ throw new Error(
315
+ `${manifest_data.params} does not export \`params\` from \`defineParams\``
316
+ );
304
317
  }
305
318
 
306
- return matchers;
319
+ return module.params;
307
320
  }
308
321
  }
309
322
  };
@@ -320,7 +333,9 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
320
333
  return error.stack?.replaceAll('\0', ''); // remove null bytes from e.g. virtual module IDs, or the response will fail
321
334
  }
322
335
 
323
- update_manifest();
336
+ await update_manifest();
337
+
338
+ const params_file = resolve_entry(svelte_config.kit.files.params);
324
339
 
325
340
  /**
326
341
  * @param {string} event
@@ -330,7 +345,7 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
330
345
  vite.watcher.on(event, (file) => {
331
346
  if (
332
347
  file.startsWith(svelte_config.kit.files.routes + path.sep) ||
333
- file.startsWith(svelte_config.kit.files.params + path.sep) ||
348
+ (params_file && file === params_file) ||
334
349
  svelte_config.kit.moduleExtensions.some((ext) => file.endsWith(`.remote${ext}`)) ||
335
350
  // in contrast to server hooks, client hooks are written to the client manifest
336
351
  // and therefore need rebuilding when they are added/removed
@@ -351,9 +366,6 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
351
366
  }, 100);
352
367
  };
353
368
 
354
- // flag to skip watchers if server is already restarting
355
- let restarting = false;
356
-
357
369
  // Debounce add/unlink events because in case of folder deletion or moves
358
370
  // they fire in rapid succession, causing needless invocations.
359
371
  // These watchers only run for routes, param matchers, and client hooks.
@@ -362,7 +374,7 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
362
374
  watch('change', (file) => {
363
375
  // Don't run for a single file if the whole manifest is about to get updated
364
376
  // Unless it's a file where the trailing slash page option might have changed
365
- if (timeout || restarting || !/\+(page|layout|server).*$/.test(file)) return;
377
+ if (timeout || !/\+(page|layout|server).*$/.test(file)) return;
366
378
  sync.update(svelte_config, manifest_data, file, root);
367
379
  });
368
380
 
@@ -373,7 +385,7 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
373
385
  // send the vite client a full-reload event without path being set
374
386
  if (appTemplate !== 'index.html') {
375
387
  vite.watcher.on('change', (file) => {
376
- if (file === appTemplate && !restarting) {
388
+ if (file === appTemplate) {
377
389
  vite.ws.send({ type: 'full-reload' });
378
390
  }
379
391
  });
@@ -390,26 +402,12 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
390
402
  }
391
403
  });
392
404
 
393
- vite.watcher.on('change', async (file) => {
394
- // changing the svelte config requires restarting the dev server
395
- // the config is only read on start and passed on to vite-plugin-svelte
396
- // which needs up-to-date values to operate correctly
397
- if (file.match(/[/\\]svelte\.config\.[jt]s$/)) {
398
- console.log(`svelte config changed, restarting vite dev-server. changed file: ${file}`);
399
- restarting = true;
400
- await vite.restart();
401
- }
402
- });
403
-
404
405
  const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base;
405
406
  const asset_server = sirv(svelte_config.kit.files.assets, {
406
407
  dev: true,
407
408
  etag: true,
408
409
  maxAge: 0,
409
- extensions: [],
410
- setHeaders: (res) => {
411
- res.setHeader('access-control-allow-origin', '*');
412
- }
410
+ extensions: []
413
411
  });
414
412
 
415
413
  vite.middlewares.use((req, res, next) => {
@@ -436,7 +434,7 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
436
434
  });
437
435
 
438
436
  const env = loadEnv(vite_config.mode, svelte_config.kit.env.dir, '');
439
- const emulator = await adapter?.emulate?.();
437
+ const emulator = await svelte_config.kit.adapter?.emulate?.();
440
438
 
441
439
  return () => {
442
440
  const serve_static_middleware = vite.middlewares.stack.find(
@@ -527,7 +525,7 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
527
525
  read: (file) => createReadableStream(from_fs(file))
528
526
  });
529
527
 
530
- const request = await getRequest({
528
+ const request = getRequest({
531
529
  base,
532
530
  request: req
533
531
  });
@@ -578,10 +576,10 @@ export async function dev(vite, vite_config, svelte_config, get_remotes, root, a
578
576
  if (rendered.status === 404) {
579
577
  // @ts-expect-error
580
578
  serve_static_middleware.handle(req, res, () => {
581
- void setResponse(res, rendered);
579
+ setResponse(res, rendered);
582
580
  });
583
581
  } else {
584
- void setResponse(res, rendered);
582
+ setResponse(res, rendered);
585
583
  }
586
584
  } catch (e) {
587
585
  const error = coalesce_to_error(e);