@sveltejs/kit 1.0.0-next.42 → 1.0.0-next.422

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 (126) hide show
  1. package/README.md +12 -9
  2. package/package.json +95 -63
  3. package/src/cli.js +112 -0
  4. package/src/core/adapt/builder.js +207 -0
  5. package/src/core/adapt/index.js +19 -0
  6. package/src/core/config/index.js +86 -0
  7. package/src/core/config/options.js +482 -0
  8. package/src/core/config/types.d.ts +1 -0
  9. package/src/core/constants.js +5 -0
  10. package/src/core/env.js +91 -0
  11. package/src/core/generate_manifest/index.js +99 -0
  12. package/src/core/prerender/crawl.js +194 -0
  13. package/src/core/prerender/prerender.js +378 -0
  14. package/src/core/prerender/queue.js +80 -0
  15. package/src/core/sync/create_manifest_data/index.js +506 -0
  16. package/src/core/sync/create_manifest_data/types.d.ts +40 -0
  17. package/src/core/sync/sync.js +59 -0
  18. package/src/core/sync/utils.js +44 -0
  19. package/src/core/sync/write_ambient.js +27 -0
  20. package/src/core/sync/write_client_manifest.js +82 -0
  21. package/src/core/sync/write_matchers.js +25 -0
  22. package/src/core/sync/write_root.js +88 -0
  23. package/src/core/sync/write_tsconfig.js +189 -0
  24. package/src/core/sync/write_types.js +769 -0
  25. package/src/core/utils.js +58 -0
  26. package/src/hooks.js +26 -0
  27. package/src/index/index.js +45 -0
  28. package/src/index/private.js +33 -0
  29. package/src/node/index.js +145 -0
  30. package/src/node/polyfills.js +40 -0
  31. package/src/runtime/app/env.js +11 -0
  32. package/src/runtime/app/navigation.js +22 -0
  33. package/src/runtime/app/paths.js +1 -0
  34. package/src/runtime/app/stores.js +91 -0
  35. package/src/runtime/client/ambient.d.ts +17 -0
  36. package/src/runtime/client/client.js +1258 -0
  37. package/src/runtime/client/fetcher.js +60 -0
  38. package/src/runtime/client/parse.js +36 -0
  39. package/src/runtime/client/singletons.js +11 -0
  40. package/src/runtime/client/start.js +46 -0
  41. package/src/runtime/client/types.d.ts +105 -0
  42. package/src/runtime/client/utils.js +113 -0
  43. package/src/runtime/components/error.svelte +16 -0
  44. package/{assets → src/runtime}/components/layout.svelte +0 -0
  45. package/src/runtime/env/dynamic/private.js +1 -0
  46. package/src/runtime/env/dynamic/public.js +1 -0
  47. package/src/runtime/env-private.js +7 -0
  48. package/src/runtime/env-public.js +7 -0
  49. package/src/runtime/env.js +6 -0
  50. package/src/runtime/hash.js +16 -0
  51. package/src/runtime/paths.js +11 -0
  52. package/src/runtime/server/endpoint.js +58 -0
  53. package/src/runtime/server/index.js +448 -0
  54. package/src/runtime/server/page/cookie.js +25 -0
  55. package/src/runtime/server/page/crypto.js +239 -0
  56. package/src/runtime/server/page/csp.js +249 -0
  57. package/src/runtime/server/page/fetch.js +266 -0
  58. package/src/runtime/server/page/index.js +416 -0
  59. package/src/runtime/server/page/load_data.js +127 -0
  60. package/src/runtime/server/page/render.js +359 -0
  61. package/src/runtime/server/page/respond_with_error.js +94 -0
  62. package/src/runtime/server/page/types.d.ts +44 -0
  63. package/src/runtime/server/utils.js +116 -0
  64. package/src/utils/error.js +22 -0
  65. package/src/utils/escape.js +104 -0
  66. package/src/utils/filesystem.js +108 -0
  67. package/src/utils/http.js +55 -0
  68. package/src/utils/misc.js +1 -0
  69. package/src/utils/routing.js +107 -0
  70. package/src/utils/url.js +97 -0
  71. package/src/vite/build/build_server.js +337 -0
  72. package/src/vite/build/build_service_worker.js +90 -0
  73. package/src/vite/build/utils.js +157 -0
  74. package/src/vite/dev/index.js +568 -0
  75. package/src/vite/index.js +566 -0
  76. package/src/vite/preview/index.js +186 -0
  77. package/src/vite/types.d.ts +3 -0
  78. package/src/vite/utils.js +334 -0
  79. package/svelte-kit.js +1 -1
  80. package/types/ambient.d.ts +355 -0
  81. package/types/index.d.ts +342 -0
  82. package/types/internal.d.ts +308 -0
  83. package/types/private.d.ts +209 -0
  84. package/CHANGELOG.md +0 -425
  85. package/assets/components/error.svelte +0 -13
  86. package/assets/runtime/app/env.js +0 -5
  87. package/assets/runtime/app/navigation.js +0 -41
  88. package/assets/runtime/app/paths.js +0 -1
  89. package/assets/runtime/app/stores.js +0 -93
  90. package/assets/runtime/chunks/utils.js +0 -19
  91. package/assets/runtime/internal/singletons.js +0 -23
  92. package/assets/runtime/internal/start.js +0 -770
  93. package/assets/runtime/paths.js +0 -12
  94. package/dist/api.js +0 -28
  95. package/dist/api.js.map +0 -1
  96. package/dist/chunks/index.js +0 -3521
  97. package/dist/chunks/index2.js +0 -587
  98. package/dist/chunks/index3.js +0 -246
  99. package/dist/chunks/index4.js +0 -530
  100. package/dist/chunks/index5.js +0 -761
  101. package/dist/chunks/index6.js +0 -322
  102. package/dist/chunks/standard.js +0 -99
  103. package/dist/chunks/utils.js +0 -83
  104. package/dist/cli.js +0 -546
  105. package/dist/cli.js.map +0 -1
  106. package/dist/create_app.js +0 -592
  107. package/dist/create_app.js.map +0 -1
  108. package/dist/index.js +0 -392
  109. package/dist/index.js.map +0 -1
  110. package/dist/index2.js +0 -3519
  111. package/dist/index2.js.map +0 -1
  112. package/dist/index3.js +0 -320
  113. package/dist/index3.js.map +0 -1
  114. package/dist/index4.js +0 -323
  115. package/dist/index4.js.map +0 -1
  116. package/dist/index5.js +0 -247
  117. package/dist/index5.js.map +0 -1
  118. package/dist/index6.js +0 -761
  119. package/dist/index6.js.map +0 -1
  120. package/dist/renderer.js +0 -2499
  121. package/dist/renderer.js.map +0 -1
  122. package/dist/ssr.js +0 -2581
  123. package/dist/standard.js +0 -100
  124. package/dist/standard.js.map +0 -1
  125. package/dist/utils.js +0 -84
  126. package/dist/utils.js.map +0 -1
@@ -0,0 +1,1258 @@
1
+ import { onMount, tick } from 'svelte';
2
+ import { writable } from 'svelte/store';
3
+ import { normalize_error } from '../../utils/error.js';
4
+ import { LoadURL, decode_params, normalize_path } from '../../utils/url.js';
5
+ import {
6
+ create_updated_store,
7
+ find_anchor,
8
+ get_base_uri,
9
+ get_href,
10
+ notifiable_store,
11
+ scroll_state
12
+ } from './utils.js';
13
+ import { lock_fetch, unlock_fetch, initial_fetch, native_fetch } from './fetcher.js';
14
+ import { parse } from './parse.js';
15
+ import { error } from '../../index/index.js';
16
+
17
+ import Root from '__GENERATED__/root.svelte';
18
+ import { nodes, dictionary, matchers } from '__GENERATED__/client-manifest.js';
19
+ import { HttpError, Redirect } from '../../index/private.js';
20
+
21
+ const SCROLL_KEY = 'sveltekit:scroll';
22
+ const INDEX_KEY = 'sveltekit:index';
23
+
24
+ const routes = parse(nodes, dictionary, matchers);
25
+
26
+ // we import the root layout/error nodes eagerly, so that
27
+ // connectivity errors after initialisation don't nuke the app
28
+ const default_layout = nodes[0]();
29
+ const default_error = nodes[1]();
30
+
31
+ // We track the scroll position associated with each history entry in sessionStorage,
32
+ // rather than on history.state itself, because when navigation is driven by
33
+ // popstate it's too late to update the scroll position associated with the
34
+ // state we're navigating from
35
+
36
+ /** @typedef {{ x: number, y: number }} ScrollPosition */
37
+ /** @type {Record<number, ScrollPosition>} */
38
+ let scroll_positions = {};
39
+ try {
40
+ scroll_positions = JSON.parse(sessionStorage[SCROLL_KEY]);
41
+ } catch {
42
+ // do nothing
43
+ }
44
+
45
+ /** @param {number} index */
46
+ function update_scroll_positions(index) {
47
+ scroll_positions[index] = scroll_state();
48
+ }
49
+
50
+ /**
51
+ * @param {{
52
+ * target: Element;
53
+ * base: string;
54
+ * trailing_slash: import('types').TrailingSlash;
55
+ * }} opts
56
+ * @returns {import('./types').Client}
57
+ */
58
+ export function create_client({ target, base, trailing_slash }) {
59
+ /** @type {Array<((href: string) => boolean)>} */
60
+ const invalidated = [];
61
+
62
+ const stores = {
63
+ url: notifiable_store({}),
64
+ page: notifiable_store({}),
65
+ navigating: writable(/** @type {import('types').Navigation | null} */ (null)),
66
+ updated: create_updated_store()
67
+ };
68
+
69
+ /** @type {{id: string | null, promise: Promise<import('./types').NavigationResult | undefined> | null}} */
70
+ const load_cache = {
71
+ id: null,
72
+ promise: null
73
+ };
74
+
75
+ const callbacks = {
76
+ /** @type {Array<(opts: { from: URL, to: URL | null, cancel: () => void }) => void>} */
77
+ before_navigate: [],
78
+
79
+ /** @type {Array<(opts: { from: URL | null, to: URL }) => void>} */
80
+ after_navigate: []
81
+ };
82
+
83
+ /** @type {import('./types').NavigationState} */
84
+ let current = {
85
+ branch: [],
86
+ error: null,
87
+ session_id: 0,
88
+ // @ts-ignore - we need the initial value to be null
89
+ url: null
90
+ };
91
+
92
+ let started = false;
93
+ let autoscroll = true;
94
+ let updating = false;
95
+ let session_id = 1;
96
+
97
+ /** @type {Promise<void> | null} */
98
+ let invalidating = null;
99
+
100
+ /** @type {import('svelte').SvelteComponent} */
101
+ let root;
102
+
103
+ let router_enabled = true;
104
+
105
+ // keeping track of the history index in order to prevent popstate navigation events if needed
106
+ let current_history_index = history.state?.[INDEX_KEY];
107
+
108
+ if (!current_history_index) {
109
+ // we use Date.now() as an offset so that cross-document navigations
110
+ // within the app don't result in data loss
111
+ current_history_index = Date.now();
112
+
113
+ // create initial history entry, so we can return here
114
+ history.replaceState(
115
+ { ...history.state, [INDEX_KEY]: current_history_index },
116
+ '',
117
+ location.href
118
+ );
119
+ }
120
+
121
+ // if we reload the page, or Cmd-Shift-T back to it,
122
+ // recover scroll position
123
+ const scroll = scroll_positions[current_history_index];
124
+ if (scroll) {
125
+ history.scrollRestoration = 'manual';
126
+ scrollTo(scroll.x, scroll.y);
127
+ }
128
+
129
+ let hash_navigating = false;
130
+
131
+ /** @type {import('types').Page} */
132
+ let page;
133
+
134
+ /** @type {{}} */
135
+ let token;
136
+
137
+ /**
138
+ * @param {string | URL} url
139
+ * @param {{ noscroll?: boolean; replaceState?: boolean; keepfocus?: boolean; state?: any }} opts
140
+ * @param {string[]} redirect_chain
141
+ */
142
+ async function goto(
143
+ url,
144
+ { noscroll = false, replaceState = false, keepfocus = false, state = {} },
145
+ redirect_chain
146
+ ) {
147
+ if (typeof url === 'string') {
148
+ url = new URL(url, get_base_uri(document));
149
+ }
150
+
151
+ if (router_enabled) {
152
+ return navigate({
153
+ url,
154
+ scroll: noscroll ? scroll_state() : null,
155
+ keepfocus,
156
+ redirect_chain,
157
+ details: {
158
+ state,
159
+ replaceState
160
+ },
161
+ accepted: () => {},
162
+ blocked: () => {}
163
+ });
164
+ }
165
+
166
+ await native_navigation(url);
167
+ }
168
+
169
+ /** @param {URL} url */
170
+ async function prefetch(url) {
171
+ const intent = get_navigation_intent(url);
172
+
173
+ if (!intent) {
174
+ throw new Error('Attempted to prefetch a URL that does not belong to this app');
175
+ }
176
+
177
+ load_cache.promise = load_route(intent);
178
+ load_cache.id = intent.id;
179
+
180
+ return load_cache.promise;
181
+ }
182
+
183
+ /**
184
+ * Returns `true` if update completes, `false` if it is aborted
185
+ * @param {URL} url
186
+ * @param {string[]} redirect_chain
187
+ * @param {{hash?: string, scroll: { x: number, y: number } | null, keepfocus: boolean, details: { replaceState: boolean, state: any } | null}} [opts]
188
+ * @param {() => void} [callback]
189
+ */
190
+ async function update(url, redirect_chain, opts, callback) {
191
+ const intent = get_navigation_intent(url);
192
+
193
+ const current_token = (token = {});
194
+ let navigation_result = intent && (await load_route(intent));
195
+
196
+ if (
197
+ !navigation_result &&
198
+ url.origin === location.origin &&
199
+ url.pathname === location.pathname
200
+ ) {
201
+ // this could happen in SPA fallback mode if the user navigated to
202
+ // `/non-existent-page`. if we fall back to reloading the page, it
203
+ // will create an infinite loop. so whereas we normally handle
204
+ // unknown routes by going to the server, in this special case
205
+ // we render a client-side error page instead
206
+ navigation_result = await load_root_error_page({
207
+ status: 404,
208
+ error: new Error(`Not found: ${url.pathname}`),
209
+ url,
210
+ routeId: null
211
+ });
212
+ }
213
+
214
+ if (!navigation_result) {
215
+ await native_navigation(url);
216
+ return false; // unnecessary, but TypeScript prefers it this way
217
+ }
218
+
219
+ // if this is an internal navigation intent, use the normalized
220
+ // URL for the rest of the function
221
+ url = intent?.url || url;
222
+
223
+ // abort if user navigated during update
224
+ if (token !== current_token) return false;
225
+
226
+ invalidated.length = 0;
227
+
228
+ if (navigation_result.type === 'redirect') {
229
+ if (redirect_chain.length > 10 || redirect_chain.includes(url.pathname)) {
230
+ navigation_result = await load_root_error_page({
231
+ status: 500,
232
+ error: new Error('Redirect loop'),
233
+ url,
234
+ routeId: null
235
+ });
236
+ } else {
237
+ if (router_enabled) {
238
+ goto(new URL(navigation_result.location, url).href, {}, [
239
+ ...redirect_chain,
240
+ url.pathname
241
+ ]);
242
+ } else {
243
+ await native_navigation(new URL(navigation_result.location, location.href));
244
+ }
245
+
246
+ return false;
247
+ }
248
+ } else if (navigation_result.props?.page?.status >= 400) {
249
+ const updated = await stores.updated.check();
250
+ if (updated) {
251
+ await native_navigation(url);
252
+ }
253
+ }
254
+
255
+ updating = true;
256
+
257
+ if (opts && opts.details) {
258
+ const { details } = opts;
259
+ const change = details.replaceState ? 0 : 1;
260
+ details.state[INDEX_KEY] = current_history_index += change;
261
+ history[details.replaceState ? 'replaceState' : 'pushState'](details.state, '', url);
262
+ }
263
+
264
+ if (started) {
265
+ current = navigation_result.state;
266
+
267
+ if (navigation_result.props.page) {
268
+ navigation_result.props.page.url = url;
269
+ }
270
+
271
+ root.$set(navigation_result.props);
272
+ } else {
273
+ initialize(navigation_result);
274
+ }
275
+
276
+ // opts must be passed if we're navigating
277
+ if (opts) {
278
+ const { scroll, keepfocus } = opts;
279
+
280
+ if (!keepfocus) {
281
+ // Reset page selection and focus
282
+ // We try to mimic browsers' behaviour as closely as possible by targeting the
283
+ // first scrollable region, but unfortunately it's not a perfect match — e.g.
284
+ // shift-tabbing won't immediately cycle up from the end of the page on Chromium
285
+ // See https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area
286
+ const root = document.body;
287
+ const tabindex = root.getAttribute('tabindex');
288
+
289
+ root.tabIndex = -1;
290
+ root.focus({ preventScroll: true });
291
+
292
+ setTimeout(() => {
293
+ getSelection()?.removeAllRanges();
294
+ });
295
+
296
+ // restore `tabindex` as to prevent `root` from stealing input from elements
297
+ if (tabindex !== null) {
298
+ root.setAttribute('tabindex', tabindex);
299
+ } else {
300
+ root.removeAttribute('tabindex');
301
+ }
302
+ }
303
+
304
+ // need to render the DOM before we can scroll to the rendered elements
305
+ await tick();
306
+
307
+ if (autoscroll) {
308
+ const deep_linked = url.hash && document.getElementById(url.hash.slice(1));
309
+ if (scroll) {
310
+ scrollTo(scroll.x, scroll.y);
311
+ } else if (deep_linked) {
312
+ // Here we use `scrollIntoView` on the element instead of `scrollTo`
313
+ // because it natively supports the `scroll-margin` and `scroll-behavior`
314
+ // CSS properties.
315
+ deep_linked.scrollIntoView();
316
+ } else {
317
+ scrollTo(0, 0);
318
+ }
319
+ }
320
+ } else {
321
+ // in this case we're simply invalidating
322
+ await tick();
323
+ }
324
+
325
+ load_cache.promise = null;
326
+ load_cache.id = null;
327
+ autoscroll = true;
328
+
329
+ if (navigation_result.props.page) {
330
+ page = navigation_result.props.page;
331
+ }
332
+
333
+ const leaf_node = navigation_result.state.branch.at(-1);
334
+ router_enabled = leaf_node?.node.shared?.router !== false;
335
+
336
+ if (callback) callback();
337
+
338
+ updating = false;
339
+ }
340
+
341
+ /** @param {import('./types').NavigationFinished} result */
342
+ function initialize(result) {
343
+ current = result.state;
344
+
345
+ const style = document.querySelector('style[data-sveltekit]');
346
+ if (style) style.remove();
347
+
348
+ page = result.props.page;
349
+
350
+ root = new Root({
351
+ target,
352
+ props: { ...result.props, stores },
353
+ hydrate: true
354
+ });
355
+
356
+ if (router_enabled) {
357
+ const navigation = { from: null, to: new URL(location.href) };
358
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
359
+ }
360
+
361
+ started = true;
362
+ }
363
+
364
+ /**
365
+ *
366
+ * @param {{
367
+ * url: URL;
368
+ * params: Record<string, string>;
369
+ * branch: Array<import('./types').BranchNode | undefined>;
370
+ * status: number;
371
+ * error: HttpError | Error | null;
372
+ * routeId: string | null;
373
+ * validation_errors?: string | undefined;
374
+ * }} opts
375
+ */
376
+ async function get_navigation_result_from_branch({
377
+ url,
378
+ params,
379
+ branch,
380
+ status,
381
+ error,
382
+ routeId,
383
+ validation_errors
384
+ }) {
385
+ const filtered = /** @type {import('./types').BranchNode[] } */ (branch.filter(Boolean));
386
+
387
+ /** @type {import('./types').NavigationFinished} */
388
+ const result = {
389
+ type: 'loaded',
390
+ state: {
391
+ url,
392
+ params,
393
+ branch,
394
+ error,
395
+ session_id
396
+ },
397
+ props: {
398
+ components: filtered.map((branch_node) => branch_node.node.component),
399
+ errors: validation_errors
400
+ }
401
+ };
402
+
403
+ let data = {};
404
+ let data_changed = false;
405
+ for (let i = 0; i < filtered.length; i += 1) {
406
+ Object.assign(data, filtered[i].data);
407
+ // Only set props if the node actually updated. This prevents needless rerenders.
408
+ if (!current.branch.some((node) => node === filtered[i])) {
409
+ result.props[`data_${i}`] = filtered[i].data;
410
+ data_changed = true;
411
+ }
412
+ }
413
+
414
+ const page_changed =
415
+ !current.url || url.href !== current.url.href || current.error !== error || data_changed;
416
+
417
+ if (page_changed) {
418
+ result.props.page = { error, params, routeId, status, url, data };
419
+
420
+ // TODO remove this for 1.0
421
+ /**
422
+ * @param {string} property
423
+ * @param {string} replacement
424
+ */
425
+ const print_error = (property, replacement) => {
426
+ Object.defineProperty(result.props.page, property, {
427
+ get: () => {
428
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
429
+ }
430
+ });
431
+ };
432
+
433
+ print_error('origin', 'origin');
434
+ print_error('path', 'pathname');
435
+ print_error('query', 'searchParams');
436
+ }
437
+
438
+ return result;
439
+ }
440
+
441
+ /**
442
+ * Call the load function of the given node, if it exists.
443
+ * If `server_data` is passed, this is treated as the initial run and the page endpoint is not requested.
444
+ *
445
+ * @param {{
446
+ * node: import('types').CSRPageNode;
447
+ * parent: () => Promise<Record<string, any>>;
448
+ * url: URL;
449
+ * params: Record<string, string>;
450
+ * routeId: string | null;
451
+ * server_data: Record<string, any> | null;
452
+ * }} options
453
+ * @returns {Promise<import('./types').BranchNode>}
454
+ */
455
+ async function load_node({ node, parent, url, params, routeId, server_data }) {
456
+ const uses = {
457
+ params: new Set(),
458
+ url: false,
459
+ dependencies: new Set(),
460
+ parent: false
461
+ };
462
+
463
+ /** @param {string[]} deps */
464
+ function depends(...deps) {
465
+ for (const dep of deps) {
466
+ const { href } = new URL(dep, url);
467
+ uses.dependencies.add(href);
468
+ }
469
+ }
470
+
471
+ /** @type {Record<string, any> | null} */
472
+ let data = null;
473
+
474
+ if (node.server) {
475
+ // +page|layout.server.js data means we need to mark this URL as a dependency of itself,
476
+ // unless we want to get clever with usage detection on the server, which could
477
+ // be returned to the client either as payload or custom headers
478
+ uses.dependencies.add(url.href);
479
+ uses.url = true;
480
+ }
481
+
482
+ /** @type {Record<string, string>} */
483
+ const uses_params = {};
484
+ for (const key in params) {
485
+ Object.defineProperty(uses_params, key, {
486
+ get() {
487
+ uses.params.add(key);
488
+ return params[key];
489
+ },
490
+ enumerable: true
491
+ });
492
+ }
493
+
494
+ const load_url = new LoadURL(url);
495
+
496
+ if (node.shared?.load) {
497
+ /** @type {import('types').LoadEvent} */
498
+ const load_input = {
499
+ routeId,
500
+ params: uses_params,
501
+ data: server_data,
502
+ get url() {
503
+ uses.url = true;
504
+ return load_url;
505
+ },
506
+ async fetch(resource, init) {
507
+ let requested;
508
+
509
+ if (typeof resource === 'string') {
510
+ requested = resource;
511
+ } else {
512
+ requested = resource.url;
513
+
514
+ // we're not allowed to modify the received `Request` object, so in order
515
+ // to fixup relative urls we create a new equivalent `init` object instead
516
+ init = {
517
+ // the request body must be consumed in memory until browsers
518
+ // implement streaming request bodies and/or the body getter
519
+ body:
520
+ resource.method === 'GET' || resource.method === 'HEAD'
521
+ ? undefined
522
+ : await resource.blob(),
523
+ cache: resource.cache,
524
+ credentials: resource.credentials,
525
+ headers: resource.headers,
526
+ integrity: resource.integrity,
527
+ keepalive: resource.keepalive,
528
+ method: resource.method,
529
+ mode: resource.mode,
530
+ redirect: resource.redirect,
531
+ referrer: resource.referrer,
532
+ referrerPolicy: resource.referrerPolicy,
533
+ signal: resource.signal,
534
+ ...init
535
+ };
536
+ }
537
+
538
+ // we must fixup relative urls so they are resolved from the target page
539
+ const normalized = new URL(requested, url).href;
540
+ depends(normalized);
541
+
542
+ // prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be normalized
543
+ return started ? native_fetch(normalized, init) : initial_fetch(requested, init);
544
+ },
545
+ setHeaders: () => {}, // noop
546
+ depends,
547
+ get parent() {
548
+ // uses.parent assignment here, not on method inokation, else we wouldn't notice when someone
549
+ // does await parent() inside an if branch which wasn't executed yet.
550
+ uses.parent = true;
551
+ return parent;
552
+ },
553
+ // @ts-expect-error
554
+ get props() {
555
+ throw new Error(
556
+ '@migration task: Replace `props` with `data` stuff https://github.com/sveltejs/kit/discussions/5774#discussioncomment-3292693'
557
+ );
558
+ },
559
+ get session() {
560
+ // TODO remove this for 1.0
561
+ throw new Error(
562
+ 'session is no longer available. See https://github.com/sveltejs/kit/discussions/5883'
563
+ );
564
+ },
565
+ get stuff() {
566
+ throw new Error(
567
+ '@migration task: Remove stuff https://github.com/sveltejs/kit/discussions/5774#discussioncomment-3292693'
568
+ );
569
+ }
570
+ };
571
+
572
+ if (import.meta.env.DEV) {
573
+ try {
574
+ lock_fetch();
575
+ data = (await node.shared.load.call(null, load_input)) ?? null;
576
+ } finally {
577
+ unlock_fetch();
578
+ }
579
+ } else {
580
+ data = (await node.shared.load.call(null, load_input)) ?? null;
581
+ }
582
+ }
583
+
584
+ return {
585
+ node,
586
+ data: data || server_data,
587
+ uses
588
+ };
589
+ }
590
+
591
+ /**
592
+ * @param {import('./types').NavigationIntent} intent
593
+ * @returns {Promise<import('./types').NavigationResult | undefined>}
594
+ */
595
+ async function load_route({ id, url, params, route }) {
596
+ if (load_cache.id === id && load_cache.promise) {
597
+ return load_cache.promise;
598
+ }
599
+
600
+ const { errors, layouts, leaf } = route;
601
+
602
+ const changed = current.url && {
603
+ url: id !== current.url.pathname + current.url.search,
604
+ params: Object.keys(params).filter((key) => current.params[key] !== params[key])
605
+ };
606
+
607
+ // preload modules to avoid waterfall, but handle rejections
608
+ // so they don't get reported to Sentry et al (we don't need
609
+ // to act on the failures at this point)
610
+ [...errors, ...layouts, leaf].forEach((loader) => loader?.().catch(() => {}));
611
+
612
+ const nodes = [...layouts, leaf];
613
+
614
+ // To avoid waterfalls when someone awaits a parent, compute as much as possible here already
615
+ /** @type {boolean[]} */
616
+ const nodes_changed_since_last_render = [];
617
+ for (let i = 0; i < nodes.length; i++) {
618
+ if (!nodes[i]) {
619
+ nodes_changed_since_last_render.push(false);
620
+ } else {
621
+ const previous = current.branch[i];
622
+ const changed_since_last_render =
623
+ !previous ||
624
+ (changed.url && previous.uses.url) ||
625
+ changed.params.some((param) => previous.uses.params.has(param)) ||
626
+ Array.from(previous.uses.dependencies).some((dep) => invalidated.some((fn) => fn(dep))) ||
627
+ (previous.uses.parent && nodes_changed_since_last_render.includes(true));
628
+ nodes_changed_since_last_render.push(changed_since_last_render);
629
+ }
630
+ }
631
+
632
+ /** @type {import('./types').ServerDataPayload | null} */
633
+ let server_data_payload = null;
634
+
635
+ if (route.uses_server_data) {
636
+ try {
637
+ const res = await native_fetch(
638
+ `${url.pathname}${url.pathname.endsWith('/') ? '' : '/'}__data.json${url.search}`
639
+ );
640
+
641
+ server_data_payload = /** @type {import('./types').ServerDataPayload} */ (await res.json());
642
+
643
+ if (!res.ok) {
644
+ throw server_data_payload;
645
+ }
646
+ } catch (e) {
647
+ throw new Error('TODO render fallback error page');
648
+ }
649
+
650
+ if (server_data_payload.type === 'redirect') {
651
+ return server_data_payload;
652
+ }
653
+ }
654
+
655
+ const server_data_nodes = server_data_payload?.nodes;
656
+
657
+ const branch_promises = nodes.map(async (loader, i) => {
658
+ return Promise.resolve().then(async () => {
659
+ if (!loader) return;
660
+ const node = await loader();
661
+
662
+ /** @type {import('./types').BranchNode | undefined} */
663
+ const previous = current.branch[i];
664
+ const changed_since_last_render =
665
+ nodes_changed_since_last_render[i] || !previous || node !== previous.node;
666
+
667
+ if (changed_since_last_render) {
668
+ const payload = server_data_nodes?.[i];
669
+
670
+ if (payload?.status) {
671
+ throw error(payload.status, payload.message);
672
+ }
673
+
674
+ if (payload?.error) {
675
+ throw payload.error;
676
+ }
677
+
678
+ return await load_node({
679
+ node,
680
+ url,
681
+ params,
682
+ routeId: route.id,
683
+ parent: async () => {
684
+ const data = {};
685
+ for (let j = 0; j < i; j += 1) {
686
+ Object.assign(data, (await branch_promises[j])?.data);
687
+ }
688
+ return data;
689
+ },
690
+ server_data: payload?.data ?? null
691
+ });
692
+ } else {
693
+ return previous;
694
+ }
695
+ });
696
+ });
697
+
698
+ // if we don't do this, rejections will be unhandled
699
+ for (const p of branch_promises) p.catch(() => {});
700
+
701
+ /** @type {Array<import('./types').BranchNode | undefined>} */
702
+ const branch = [];
703
+
704
+ for (let i = 0; i < nodes.length; i += 1) {
705
+ if (nodes[i]) {
706
+ try {
707
+ branch.push(await branch_promises[i]);
708
+ } catch (e) {
709
+ const error = normalize_error(e);
710
+
711
+ if (error instanceof Redirect) {
712
+ return {
713
+ type: 'redirect',
714
+ location: error.location
715
+ };
716
+ }
717
+
718
+ const status = e instanceof HttpError ? e.status : 500;
719
+
720
+ while (i--) {
721
+ if (errors[i]) {
722
+ /** @type {import('./types').BranchNode | undefined} */
723
+ let error_loaded;
724
+
725
+ let j = i;
726
+ while (!branch[j]) j -= 1;
727
+
728
+ try {
729
+ error_loaded = {
730
+ node: await errors[i](),
731
+ data: {},
732
+ uses: {
733
+ params: new Set(),
734
+ url: false,
735
+ dependencies: new Set(),
736
+ parent: false
737
+ }
738
+ };
739
+
740
+ return await get_navigation_result_from_branch({
741
+ url,
742
+ params,
743
+ branch: branch.slice(0, j + 1).concat(error_loaded),
744
+ status,
745
+ error,
746
+ routeId: route.id
747
+ });
748
+ } catch (e) {
749
+ continue;
750
+ }
751
+ }
752
+ }
753
+
754
+ return await load_root_error_page({
755
+ status,
756
+ error,
757
+ url,
758
+ routeId: route.id
759
+ });
760
+ }
761
+ } else {
762
+ // push an empty slot so we can rewind past gaps to the
763
+ // layout that corresponds with an +error.svelte page
764
+ branch.push(undefined);
765
+ }
766
+ }
767
+
768
+ return await get_navigation_result_from_branch({
769
+ url,
770
+ params,
771
+ branch,
772
+ status: 200,
773
+ error: null,
774
+ routeId: route.id
775
+ });
776
+ }
777
+
778
+ /**
779
+ * @param {{
780
+ * status: number;
781
+ * error: HttpError | Error;
782
+ * url: URL;
783
+ * routeId: string | null
784
+ * }} opts
785
+ */
786
+ async function load_root_error_page({ status, error, url, routeId }) {
787
+ /** @type {Record<string, string>} */
788
+ const params = {}; // error page does not have params
789
+
790
+ const root_layout = await load_node({
791
+ node: await default_layout,
792
+ url,
793
+ params,
794
+ routeId,
795
+ parent: () => Promise.resolve({}),
796
+ server_data: null // TODO!!!!!
797
+ });
798
+
799
+ const root_error = {
800
+ node: await default_error,
801
+ data: null,
802
+ // TODO make this unnecessary
803
+ uses: {
804
+ params: new Set(),
805
+ url: false,
806
+ dependencies: new Set(),
807
+ parent: false
808
+ }
809
+ };
810
+
811
+ return await get_navigation_result_from_branch({
812
+ url,
813
+ params,
814
+ branch: [root_layout, root_error],
815
+ status,
816
+ error,
817
+ routeId
818
+ });
819
+ }
820
+
821
+ /** @param {URL} url */
822
+ function get_navigation_intent(url) {
823
+ if (url.origin !== location.origin || !url.pathname.startsWith(base)) return;
824
+
825
+ const path = decodeURI(url.pathname.slice(base.length) || '/');
826
+
827
+ for (const route of routes) {
828
+ const params = route.exec(path);
829
+
830
+ if (params) {
831
+ const normalized = new URL(
832
+ url.origin + normalize_path(url.pathname, trailing_slash) + url.search + url.hash
833
+ );
834
+ const id = normalized.pathname + normalized.search;
835
+ /** @type {import('./types').NavigationIntent} */
836
+ const intent = { id, route, params: decode_params(params), url: normalized };
837
+ return intent;
838
+ }
839
+ }
840
+ }
841
+
842
+ /**
843
+ * @param {{
844
+ * url: URL;
845
+ * scroll: { x: number, y: number } | null;
846
+ * keepfocus: boolean;
847
+ * redirect_chain: string[];
848
+ * details: {
849
+ * replaceState: boolean;
850
+ * state: any;
851
+ * } | null;
852
+ * accepted: () => void;
853
+ * blocked: () => void;
854
+ * }} opts
855
+ */
856
+ async function navigate({ url, scroll, keepfocus, redirect_chain, details, accepted, blocked }) {
857
+ const from = current.url;
858
+ let should_block = false;
859
+
860
+ const navigation = {
861
+ from,
862
+ to: url,
863
+ cancel: () => (should_block = true)
864
+ };
865
+
866
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
867
+
868
+ if (should_block) {
869
+ blocked();
870
+ return;
871
+ }
872
+
873
+ update_scroll_positions(current_history_index);
874
+
875
+ accepted();
876
+
877
+ if (started) {
878
+ stores.navigating.set({
879
+ from: current.url,
880
+ to: url
881
+ });
882
+ }
883
+
884
+ await update(
885
+ url,
886
+ redirect_chain,
887
+ {
888
+ scroll,
889
+ keepfocus,
890
+ details
891
+ },
892
+ () => {
893
+ const navigation = { from, to: url };
894
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
895
+
896
+ stores.navigating.set(null);
897
+ }
898
+ );
899
+ }
900
+
901
+ /**
902
+ * Loads `href` the old-fashioned way, with a full page reload.
903
+ * Returns a `Promise` that never resolves (to prevent any
904
+ * subsequent work, e.g. history manipulation, from happening)
905
+ * @param {URL} url
906
+ */
907
+ function native_navigation(url) {
908
+ location.href = url.href;
909
+ return new Promise(() => {});
910
+ }
911
+
912
+ if (import.meta.hot) {
913
+ import.meta.hot.on('vite:beforeUpdate', () => {
914
+ if (current.error) location.reload();
915
+ });
916
+ }
917
+
918
+ return {
919
+ after_navigate: (fn) => {
920
+ onMount(() => {
921
+ callbacks.after_navigate.push(fn);
922
+
923
+ return () => {
924
+ const i = callbacks.after_navigate.indexOf(fn);
925
+ callbacks.after_navigate.splice(i, 1);
926
+ };
927
+ });
928
+ },
929
+
930
+ before_navigate: (fn) => {
931
+ onMount(() => {
932
+ callbacks.before_navigate.push(fn);
933
+
934
+ return () => {
935
+ const i = callbacks.before_navigate.indexOf(fn);
936
+ callbacks.before_navigate.splice(i, 1);
937
+ };
938
+ });
939
+ },
940
+
941
+ disable_scroll_handling: () => {
942
+ if (import.meta.env.DEV && started && !updating) {
943
+ throw new Error('Can only disable scroll handling during navigation');
944
+ }
945
+
946
+ if (updating || !started) {
947
+ autoscroll = false;
948
+ }
949
+ },
950
+
951
+ goto: (href, opts = {}) => goto(href, opts, []),
952
+
953
+ invalidate: (resource) => {
954
+ if (resource === undefined) {
955
+ // Force rerun of all load functions, regardless of their dependencies
956
+ for (const node of current.branch) {
957
+ node?.uses.dependencies.add('');
958
+ }
959
+ invalidated.push(() => true);
960
+ } else if (typeof resource === 'function') {
961
+ invalidated.push(resource);
962
+ } else {
963
+ const { href } = new URL(resource, location.href);
964
+ invalidated.push((dep) => dep === href);
965
+ }
966
+
967
+ if (!invalidating) {
968
+ invalidating = Promise.resolve().then(async () => {
969
+ await update(new URL(location.href), []);
970
+
971
+ invalidating = null;
972
+ });
973
+ }
974
+
975
+ return invalidating;
976
+ },
977
+
978
+ prefetch: async (href) => {
979
+ const url = new URL(href, get_base_uri(document));
980
+ await prefetch(url);
981
+ },
982
+
983
+ // TODO rethink this API
984
+ prefetch_routes: async (pathnames) => {
985
+ const matching = pathnames
986
+ ? routes.filter((route) => pathnames.some((pathname) => route.exec(pathname)))
987
+ : routes;
988
+
989
+ const promises = matching.map((r) => {
990
+ return Promise.all([...r.layouts, r.leaf].map((load) => load?.()));
991
+ });
992
+
993
+ await Promise.all(promises);
994
+ },
995
+
996
+ _start_router: () => {
997
+ history.scrollRestoration = 'manual';
998
+
999
+ // Adopted from Nuxt.js
1000
+ // Reset scrollRestoration to auto when leaving page, allowing page reload
1001
+ // and back-navigation from other pages to use the browser to restore the
1002
+ // scrolling position.
1003
+ addEventListener('beforeunload', (e) => {
1004
+ let should_block = false;
1005
+
1006
+ const navigation = {
1007
+ from: current.url,
1008
+ to: null,
1009
+ cancel: () => (should_block = true)
1010
+ };
1011
+
1012
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1013
+
1014
+ if (should_block) {
1015
+ e.preventDefault();
1016
+ e.returnValue = '';
1017
+ } else {
1018
+ history.scrollRestoration = 'auto';
1019
+ }
1020
+ });
1021
+
1022
+ addEventListener('visibilitychange', () => {
1023
+ if (document.visibilityState === 'hidden') {
1024
+ update_scroll_positions(current_history_index);
1025
+
1026
+ try {
1027
+ sessionStorage[SCROLL_KEY] = JSON.stringify(scroll_positions);
1028
+ } catch {
1029
+ // do nothing
1030
+ }
1031
+ }
1032
+ });
1033
+
1034
+ /** @param {Event} event */
1035
+ const trigger_prefetch = (event) => {
1036
+ const a = find_anchor(event);
1037
+ if (a && a.href && a.hasAttribute('sveltekit:prefetch')) {
1038
+ prefetch(get_href(a));
1039
+ }
1040
+ };
1041
+
1042
+ /** @type {NodeJS.Timeout} */
1043
+ let mousemove_timeout;
1044
+
1045
+ /** @param {MouseEvent|TouchEvent} event */
1046
+ const handle_mousemove = (event) => {
1047
+ clearTimeout(mousemove_timeout);
1048
+ mousemove_timeout = setTimeout(() => {
1049
+ // event.composedPath(), which is used in find_anchor, will be empty if the event is read in a timeout
1050
+ // add a layer of indirection to address that
1051
+ event.target?.dispatchEvent(
1052
+ new CustomEvent('sveltekit:trigger_prefetch', { bubbles: true })
1053
+ );
1054
+ }, 20);
1055
+ };
1056
+
1057
+ addEventListener('touchstart', trigger_prefetch);
1058
+ addEventListener('mousemove', handle_mousemove);
1059
+ addEventListener('sveltekit:trigger_prefetch', trigger_prefetch);
1060
+
1061
+ /** @param {MouseEvent} event */
1062
+ addEventListener('click', (event) => {
1063
+ if (!router_enabled) return;
1064
+
1065
+ // Adapted from https://github.com/visionmedia/page.js
1066
+ // MIT license https://github.com/visionmedia/page.js#license
1067
+ if (event.button || event.which !== 1) return;
1068
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
1069
+ if (event.defaultPrevented) return;
1070
+
1071
+ const a = find_anchor(event);
1072
+ if (!a) return;
1073
+
1074
+ if (!a.href) return;
1075
+
1076
+ const is_svg_a_element = a instanceof SVGAElement;
1077
+ const url = get_href(a);
1078
+
1079
+ // Ignore non-HTTP URL protocols (e.g. `mailto:`, `tel:`, `myapp:`, etc.)
1080
+ // MEMO: Without this condition, firefox will open mailer twice.
1081
+ // See:
1082
+ // - https://github.com/sveltejs/kit/issues/4045
1083
+ // - https://github.com/sveltejs/kit/issues/5725
1084
+ if (!is_svg_a_element && !(url.protocol === 'https:' || url.protocol === 'http:')) return;
1085
+
1086
+ // Ignore if tag has
1087
+ // 1. 'download' attribute
1088
+ // 2. 'rel' attribute includes external
1089
+ const rel = (a.getAttribute('rel') || '').split(/\s+/);
1090
+
1091
+ if (
1092
+ a.hasAttribute('download') ||
1093
+ rel.includes('external') ||
1094
+ a.hasAttribute('sveltekit:reload')
1095
+ ) {
1096
+ return;
1097
+ }
1098
+
1099
+ // Ignore if <a> has a target
1100
+ if (is_svg_a_element ? a.target.baseVal : a.target) return;
1101
+
1102
+ // Check if new url only differs by hash and use the browser default behavior in that case
1103
+ // This will ensure the `hashchange` event is fired
1104
+ // Removing the hash does a full page navigation in the browser, so make sure a hash is present
1105
+ const [base, hash] = url.href.split('#');
1106
+ if (hash !== undefined && base === location.href.split('#')[0]) {
1107
+ // set this flag to distinguish between navigations triggered by
1108
+ // clicking a hash link and those triggered by popstate
1109
+ hash_navigating = true;
1110
+
1111
+ update_scroll_positions(current_history_index);
1112
+
1113
+ stores.page.set({ ...page, url });
1114
+ stores.page.notify();
1115
+
1116
+ return;
1117
+ }
1118
+
1119
+ navigate({
1120
+ url,
1121
+ scroll: a.hasAttribute('sveltekit:noscroll') ? scroll_state() : null,
1122
+ keepfocus: false,
1123
+ redirect_chain: [],
1124
+ details: {
1125
+ state: {},
1126
+ replaceState: url.href === location.href
1127
+ },
1128
+ accepted: () => event.preventDefault(),
1129
+ blocked: () => event.preventDefault()
1130
+ });
1131
+ });
1132
+
1133
+ addEventListener('popstate', (event) => {
1134
+ if (event.state && router_enabled) {
1135
+ // if a popstate-driven navigation is cancelled, we need to counteract it
1136
+ // with history.go, which means we end up back here, hence this check
1137
+ if (event.state[INDEX_KEY] === current_history_index) return;
1138
+
1139
+ navigate({
1140
+ url: new URL(location.href),
1141
+ scroll: scroll_positions[event.state[INDEX_KEY]],
1142
+ keepfocus: false,
1143
+ redirect_chain: [],
1144
+ details: null,
1145
+ accepted: () => {
1146
+ current_history_index = event.state[INDEX_KEY];
1147
+ },
1148
+ blocked: () => {
1149
+ const delta = current_history_index - event.state[INDEX_KEY];
1150
+ history.go(delta);
1151
+ }
1152
+ });
1153
+ }
1154
+ });
1155
+
1156
+ addEventListener('hashchange', () => {
1157
+ // if the hashchange happened as a result of clicking on a link,
1158
+ // we need to update history, otherwise we have to leave it alone
1159
+ if (hash_navigating) {
1160
+ hash_navigating = false;
1161
+ history.replaceState(
1162
+ { ...history.state, [INDEX_KEY]: ++current_history_index },
1163
+ '',
1164
+ location.href
1165
+ );
1166
+ }
1167
+ });
1168
+
1169
+ // fix link[rel=icon], because browsers will occasionally try to load relative
1170
+ // URLs after a pushState/replaceState, resulting in a 404 — see
1171
+ // https://github.com/sveltejs/kit/issues/3748#issuecomment-1125980897
1172
+ for (const link of document.querySelectorAll('link')) {
1173
+ if (link.rel === 'icon') link.href = link.href;
1174
+ }
1175
+
1176
+ addEventListener('pageshow', (event) => {
1177
+ // If the user navigates to another site and then uses the back button and
1178
+ // bfcache hits, we need to set navigating to null, the site doesn't know
1179
+ // the navigation away from it was successful.
1180
+ // Info about bfcache here: https://web.dev/bfcache
1181
+ if (event.persisted) {
1182
+ stores.navigating.set(null);
1183
+ }
1184
+ });
1185
+ },
1186
+
1187
+ _hydrate: async ({ status, error, node_ids, params, routeId }) => {
1188
+ const url = new URL(location.href);
1189
+
1190
+ /** @type {import('./types').NavigationFinished | undefined} */
1191
+ let result;
1192
+
1193
+ try {
1194
+ /**
1195
+ * @param {string} type
1196
+ * @param {any} fallback
1197
+ */
1198
+ const parse = (type, fallback) => {
1199
+ const script = document.querySelector(`script[sveltekit\\:data-type="${type}"]`);
1200
+ return script?.textContent ? JSON.parse(script.textContent) : fallback;
1201
+ };
1202
+ const server_data = parse('server_data', []);
1203
+ const validation_errors = parse('validation_errors', undefined);
1204
+
1205
+ const branch_promises = node_ids.map(async (n, i) => {
1206
+ return load_node({
1207
+ node: await nodes[n](),
1208
+ url,
1209
+ params,
1210
+ routeId,
1211
+ parent: async () => {
1212
+ const data = {};
1213
+ for (let j = 0; j < i; j += 1) {
1214
+ Object.assign(data, (await branch_promises[j]).data);
1215
+ }
1216
+ return data;
1217
+ },
1218
+ server_data: server_data[i] ?? null
1219
+ });
1220
+ });
1221
+
1222
+ result = await get_navigation_result_from_branch({
1223
+ url,
1224
+ params,
1225
+ branch: await Promise.all(branch_promises),
1226
+ status,
1227
+ error: /** @type {import('../server/page/types').SerializedHttpError} */ (error)
1228
+ ?.__is_http_error
1229
+ ? new HttpError(
1230
+ /** @type {import('../server/page/types').SerializedHttpError} */ (error).status,
1231
+ error.message
1232
+ )
1233
+ : error,
1234
+ validation_errors,
1235
+ routeId
1236
+ });
1237
+ } catch (e) {
1238
+ const error = normalize_error(e);
1239
+
1240
+ if (error instanceof Redirect) {
1241
+ // this is a real edge case — `load` would need to return
1242
+ // a redirect but only in the browser
1243
+ await native_navigation(new URL(/** @type {Redirect} */ (e).location, location.href));
1244
+ return;
1245
+ }
1246
+
1247
+ result = await load_root_error_page({
1248
+ status: error instanceof HttpError ? error.status : 500,
1249
+ error,
1250
+ url,
1251
+ routeId
1252
+ });
1253
+ }
1254
+
1255
+ initialize(result);
1256
+ }
1257
+ };
1258
+ }