@sveltejs/kit 1.0.0-next.46 → 1.0.0-next.462

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