@sveltejs/kit 1.0.0-next.36 → 1.0.0-next.362

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 (64) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +28 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1793 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/paths.js +13 -0
  11. package/assets/server/index.js +3460 -0
  12. package/dist/chunks/_commonjsHelpers.js +3 -0
  13. package/dist/chunks/error.js +661 -0
  14. package/dist/chunks/index.js +15744 -0
  15. package/dist/chunks/index2.js +210 -0
  16. package/dist/chunks/multipart-parser.js +445 -0
  17. package/dist/chunks/sync.js +980 -0
  18. package/dist/chunks/write_tsconfig.js +274 -0
  19. package/dist/cli.js +64 -117
  20. package/dist/hooks.js +28 -0
  21. package/dist/node/polyfills.js +12237 -0
  22. package/dist/node.js +5855 -0
  23. package/dist/vite.js +3141 -0
  24. package/package.json +100 -55
  25. package/types/ambient.d.ts +345 -0
  26. package/types/index.d.ts +293 -0
  27. package/types/internal.d.ts +318 -0
  28. package/types/private.d.ts +235 -0
  29. package/CHANGELOG.md +0 -377
  30. package/assets/runtime/app/navigation.js +0 -23
  31. package/assets/runtime/app/navigation.js.map +0 -1
  32. package/assets/runtime/app/paths.js +0 -2
  33. package/assets/runtime/app/paths.js.map +0 -1
  34. package/assets/runtime/app/stores.js +0 -78
  35. package/assets/runtime/app/stores.js.map +0 -1
  36. package/assets/runtime/internal/singletons.js +0 -15
  37. package/assets/runtime/internal/singletons.js.map +0 -1
  38. package/assets/runtime/internal/start.js +0 -614
  39. package/assets/runtime/internal/start.js.map +0 -1
  40. package/assets/runtime/utils-85ebcc60.js +0 -18
  41. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  42. package/dist/api.js +0 -28
  43. package/dist/api.js.map +0 -1
  44. package/dist/cli.js.map +0 -1
  45. package/dist/create_app.js +0 -502
  46. package/dist/create_app.js.map +0 -1
  47. package/dist/index.js +0 -327
  48. package/dist/index.js.map +0 -1
  49. package/dist/index2.js +0 -3497
  50. package/dist/index2.js.map +0 -1
  51. package/dist/index3.js +0 -296
  52. package/dist/index3.js.map +0 -1
  53. package/dist/index4.js +0 -311
  54. package/dist/index4.js.map +0 -1
  55. package/dist/index5.js +0 -221
  56. package/dist/index5.js.map +0 -1
  57. package/dist/index6.js +0 -730
  58. package/dist/index6.js.map +0 -1
  59. package/dist/renderer.js +0 -2429
  60. package/dist/renderer.js.map +0 -1
  61. package/dist/standard.js +0 -100
  62. package/dist/standard.js.map +0 -1
  63. package/dist/utils.js +0 -61
  64. package/dist/utils.js.map +0 -1
@@ -0,0 +1,1793 @@
1
+ import { onMount, tick } from 'svelte';
2
+ import { writable } from 'svelte/store';
3
+ import { assets, set_paths } from '../paths.js';
4
+ import Root from '__GENERATED__/root.svelte';
5
+ import { components, dictionary, matchers } from '__GENERATED__/client-manifest.js';
6
+ import { init } from './singletons.js';
7
+
8
+ /**
9
+ * @param {unknown} err
10
+ * @return {Error}
11
+ */
12
+ function coalesce_to_error(err) {
13
+ return err instanceof Error ||
14
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
15
+ ? /** @type {Error} */ (err)
16
+ : new Error(JSON.stringify(err));
17
+ }
18
+
19
+ /**
20
+ * @param {import('types').LoadOutput} loaded
21
+ * @returns {import('types').NormalizedLoadOutput}
22
+ */
23
+ function normalize(loaded) {
24
+ // TODO remove for 1.0
25
+ // @ts-expect-error
26
+ if (loaded.fallthrough) {
27
+ throw new Error(
28
+ 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
29
+ );
30
+ }
31
+
32
+ // TODO remove for 1.0
33
+ if ('maxage' in loaded) {
34
+ throw new Error('maxage should be replaced with cache: { maxage }');
35
+ }
36
+
37
+ const has_error_status =
38
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
39
+ if (loaded.error || has_error_status) {
40
+ const status = loaded.status;
41
+
42
+ if (!loaded.error && has_error_status) {
43
+ return { status: status || 500, error: new Error() };
44
+ }
45
+
46
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
47
+
48
+ if (!(error instanceof Error)) {
49
+ return {
50
+ status: 500,
51
+ error: new Error(
52
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
53
+ )
54
+ };
55
+ }
56
+
57
+ if (!status || status < 400 || status > 599) {
58
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
59
+ return { status: 500, error };
60
+ }
61
+
62
+ return { status, error };
63
+ }
64
+
65
+ if (loaded.redirect) {
66
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
67
+ throw new Error(
68
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
69
+ );
70
+ }
71
+
72
+ if (typeof loaded.redirect !== 'string') {
73
+ throw new Error('"redirect" property returned from load() must be a string');
74
+ }
75
+ }
76
+
77
+ if (loaded.dependencies) {
78
+ if (
79
+ !Array.isArray(loaded.dependencies) ||
80
+ loaded.dependencies.some((dep) => typeof dep !== 'string')
81
+ ) {
82
+ throw new Error('"dependencies" property returned from load() must be of type string[]');
83
+ }
84
+ }
85
+
86
+ // TODO remove before 1.0
87
+ if (/** @type {any} */ (loaded).context) {
88
+ throw new Error(
89
+ 'You are returning "context" from a load function. ' +
90
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
91
+ );
92
+ }
93
+
94
+ return /** @type {import('types').NormalizedLoadOutput} */ (loaded);
95
+ }
96
+
97
+ /**
98
+ * @param {string} path
99
+ * @param {import('types').TrailingSlash} trailing_slash
100
+ */
101
+ function normalize_path(path, trailing_slash) {
102
+ if (path === '/' || trailing_slash === 'ignore') return path;
103
+
104
+ if (trailing_slash === 'never') {
105
+ return path.endsWith('/') ? path.slice(0, -1) : path;
106
+ } else if (trailing_slash === 'always' && !path.endsWith('/')) {
107
+ return path + '/';
108
+ }
109
+
110
+ return path;
111
+ }
112
+
113
+ class LoadURL extends URL {
114
+ /** @returns {string} */
115
+ get hash() {
116
+ throw new Error(
117
+ 'url.hash is inaccessible from load. Consider accessing hash from the page store within the script tag of your component.'
118
+ );
119
+ }
120
+ }
121
+
122
+ /** @param {HTMLDocument} doc */
123
+ function get_base_uri(doc) {
124
+ let baseURI = doc.baseURI;
125
+
126
+ if (!baseURI) {
127
+ const baseTags = doc.getElementsByTagName('base');
128
+ baseURI = baseTags.length ? baseTags[0].href : doc.URL;
129
+ }
130
+
131
+ return baseURI;
132
+ }
133
+
134
+ function scroll_state() {
135
+ return {
136
+ x: pageXOffset,
137
+ y: pageYOffset
138
+ };
139
+ }
140
+
141
+ /** @param {Event} event */
142
+ function find_anchor(event) {
143
+ const node = event
144
+ .composedPath()
145
+ .find((e) => e instanceof Node && e.nodeName.toUpperCase() === 'A'); // SVG <a> elements have a lowercase name
146
+ return /** @type {HTMLAnchorElement | SVGAElement | undefined} */ (node);
147
+ }
148
+
149
+ /** @param {HTMLAnchorElement | SVGAElement} node */
150
+ function get_href(node) {
151
+ return node instanceof SVGAElement
152
+ ? new URL(node.href.baseVal, document.baseURI)
153
+ : new URL(node.href);
154
+ }
155
+
156
+ /** @param {any} value */
157
+ function notifiable_store(value) {
158
+ const store = writable(value);
159
+ let ready = true;
160
+
161
+ function notify() {
162
+ ready = true;
163
+ store.update((val) => val);
164
+ }
165
+
166
+ /** @param {any} new_value */
167
+ function set(new_value) {
168
+ ready = false;
169
+ store.set(new_value);
170
+ }
171
+
172
+ /** @param {(value: any) => void} run */
173
+ function subscribe(run) {
174
+ /** @type {any} */
175
+ let old_value;
176
+ return store.subscribe((new_value) => {
177
+ if (old_value === undefined || (ready && new_value !== old_value)) {
178
+ run((old_value = new_value));
179
+ }
180
+ });
181
+ }
182
+
183
+ return { notify, set, subscribe };
184
+ }
185
+
186
+ function create_updated_store() {
187
+ const { set, subscribe } = writable(false);
188
+
189
+ const interval = +(
190
+ /** @type {string} */ (import.meta.env.VITE_SVELTEKIT_APP_VERSION_POLL_INTERVAL)
191
+ );
192
+ const initial = import.meta.env.VITE_SVELTEKIT_APP_VERSION;
193
+
194
+ /** @type {NodeJS.Timeout} */
195
+ let timeout;
196
+
197
+ async function check() {
198
+ if (import.meta.env.DEV || import.meta.env.SSR) return false;
199
+
200
+ clearTimeout(timeout);
201
+
202
+ if (interval) timeout = setTimeout(check, interval);
203
+
204
+ const file = import.meta.env.VITE_SVELTEKIT_APP_VERSION_FILE;
205
+
206
+ const res = await fetch(`${assets}/${file}`, {
207
+ headers: {
208
+ pragma: 'no-cache',
209
+ 'cache-control': 'no-cache'
210
+ }
211
+ });
212
+
213
+ if (res.ok) {
214
+ const { version } = await res.json();
215
+ const updated = version !== initial;
216
+
217
+ if (updated) {
218
+ set(true);
219
+ clearTimeout(timeout);
220
+ }
221
+
222
+ return updated;
223
+ } else {
224
+ throw new Error(`Version check failed: ${res.status}`);
225
+ }
226
+ }
227
+
228
+ if (interval) timeout = setTimeout(check, interval);
229
+
230
+ return {
231
+ subscribe,
232
+ check
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Hash using djb2
238
+ * @param {import('types').StrictBody} value
239
+ */
240
+ function hash(value) {
241
+ let hash = 5381;
242
+ let i = value.length;
243
+
244
+ if (typeof value === 'string') {
245
+ while (i) hash = (hash * 33) ^ value.charCodeAt(--i);
246
+ } else {
247
+ while (i) hash = (hash * 33) ^ value[--i];
248
+ }
249
+
250
+ return (hash >>> 0).toString(36);
251
+ }
252
+
253
+ let loading = 0;
254
+
255
+ const native_fetch = window.fetch;
256
+
257
+ function lock_fetch() {
258
+ loading += 1;
259
+ }
260
+
261
+ function unlock_fetch() {
262
+ loading -= 1;
263
+ }
264
+
265
+ if (import.meta.env.DEV) {
266
+ let can_inspect_stack_trace = false;
267
+
268
+ const check_stack_trace = async () => {
269
+ const stack = /** @type {string} */ (new Error().stack);
270
+ can_inspect_stack_trace = stack.includes('check_stack_trace');
271
+ };
272
+
273
+ check_stack_trace();
274
+
275
+ window.fetch = (input, init) => {
276
+ const url = input instanceof Request ? input.url : input.toString();
277
+ const stack = /** @type {string} */ (new Error().stack);
278
+
279
+ const heuristic = can_inspect_stack_trace ? stack.includes('load_node') : loading;
280
+ if (heuristic) {
281
+ console.warn(
282
+ `Loading ${url} using \`window.fetch\`. For best results, use the \`fetch\` that is passed to your \`load\` function: https://kit.svelte.dev/docs/loading#input-fetch`
283
+ );
284
+ }
285
+
286
+ return native_fetch(input, init);
287
+ };
288
+ }
289
+
290
+ /**
291
+ * @param {RequestInfo} resource
292
+ * @param {RequestInit} [opts]
293
+ */
294
+ function initial_fetch(resource, opts) {
295
+ const url = JSON.stringify(typeof resource === 'string' ? resource : resource.url);
296
+
297
+ let selector = `script[sveltekit\\:data-type="data"][sveltekit\\:data-url=${url}]`;
298
+
299
+ if (opts && typeof opts.body === 'string') {
300
+ selector += `[sveltekit\\:data-body="${hash(opts.body)}"]`;
301
+ }
302
+
303
+ const script = document.querySelector(selector);
304
+ if (script && script.textContent) {
305
+ const { body, ...init } = JSON.parse(script.textContent);
306
+ return Promise.resolve(new Response(body, init));
307
+ }
308
+
309
+ return native_fetch(resource, opts);
310
+ }
311
+
312
+ const param_pattern = /^(\.\.\.)?(\w+)(?:=(\w+))?$/;
313
+
314
+ /** @param {string} id */
315
+ function parse_route_id(id) {
316
+ /** @type {string[]} */
317
+ const names = [];
318
+
319
+ /** @type {string[]} */
320
+ const types = [];
321
+
322
+ // `/foo` should get an optional trailing slash, `/foo.json` should not
323
+ // const add_trailing_slash = !/\.[a-z]+$/.test(key);
324
+ let add_trailing_slash = true;
325
+
326
+ const pattern =
327
+ id === ''
328
+ ? /^\/$/
329
+ : new RegExp(
330
+ `^${decodeURIComponent(id)
331
+ .split(/(?:@[a-zA-Z0-9_-]+)?(?:\/|$)/)
332
+ .map((segment, i, segments) => {
333
+ // special case — /[...rest]/ could contain zero segments
334
+ const match = /^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(segment);
335
+ if (match) {
336
+ names.push(match[1]);
337
+ types.push(match[2]);
338
+ return '(?:/(.*))?';
339
+ }
340
+
341
+ const is_last = i === segments.length - 1;
342
+
343
+ return (
344
+ segment &&
345
+ '/' +
346
+ segment
347
+ .split(/\[(.+?)\]/)
348
+ .map((content, i) => {
349
+ if (i % 2) {
350
+ const [, rest, name, type] = /** @type {RegExpMatchArray} */ (
351
+ param_pattern.exec(content)
352
+ );
353
+ names.push(name);
354
+ types.push(type);
355
+ return rest ? '(.*?)' : '([^/]+?)';
356
+ }
357
+
358
+ if (is_last && content.includes('.')) add_trailing_slash = false;
359
+
360
+ return (
361
+ content // allow users to specify characters on the file system in an encoded manner
362
+ .normalize()
363
+ // We use [ and ] to denote parameters, so users must encode these on the file
364
+ // system to match against them. We don't decode all characters since others
365
+ // can already be epressed and so that '%' can be easily used directly in filenames
366
+ .replace(/%5[Bb]/g, '[')
367
+ .replace(/%5[Dd]/g, ']')
368
+ // '#', '/', and '?' can only appear in URL path segments in an encoded manner.
369
+ // They will not be touched by decodeURI so need to be encoded here, so
370
+ // that we can match against them.
371
+ // We skip '/' since you can't create a file with it on any OS
372
+ .replace(/#/g, '%23')
373
+ .replace(/\?/g, '%3F')
374
+ // escape characters that have special meaning in regex
375
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
376
+ ); // TODO handle encoding
377
+ })
378
+ .join('')
379
+ );
380
+ })
381
+ .join('')}${add_trailing_slash ? '/?' : ''}$`
382
+ );
383
+
384
+ return { pattern, names, types };
385
+ }
386
+
387
+ /**
388
+ * @param {RegExpMatchArray} match
389
+ * @param {string[]} names
390
+ * @param {string[]} types
391
+ * @param {Record<string, import('types').ParamMatcher>} matchers
392
+ */
393
+ function exec(match, names, types, matchers) {
394
+ /** @type {Record<string, string>} */
395
+ const params = {};
396
+
397
+ for (let i = 0; i < names.length; i += 1) {
398
+ const name = names[i];
399
+ const type = types[i];
400
+ const value = match[i + 1] || '';
401
+
402
+ if (type) {
403
+ const matcher = matchers[type];
404
+ if (!matcher) throw new Error(`Missing "${type}" param matcher`); // TODO do this ahead of time?
405
+
406
+ if (!matcher(value)) return;
407
+ }
408
+
409
+ params[name] = value;
410
+ }
411
+
412
+ return params;
413
+ }
414
+
415
+ /**
416
+ * @param {import('types').CSRComponentLoader[]} components
417
+ * @param {Record<string, [number[], number[], 1?]>} dictionary
418
+ * @param {Record<string, (param: string) => boolean>} matchers
419
+ * @returns {import('types').CSRRoute[]}
420
+ */
421
+ function parse(components, dictionary, matchers) {
422
+ const routes = Object.entries(dictionary).map(([id, [a, b, has_shadow]]) => {
423
+ const { pattern, names, types } = parse_route_id(id);
424
+
425
+ return {
426
+ id,
427
+ /** @param {string} path */
428
+ exec: (path) => {
429
+ const match = pattern.exec(path);
430
+ if (match) return exec(match, names, types, matchers);
431
+ },
432
+ a: a.map((n) => components[n]),
433
+ b: b.map((n) => components[n]),
434
+ has_shadow: !!has_shadow
435
+ };
436
+ });
437
+
438
+ return routes;
439
+ }
440
+
441
+ const SCROLL_KEY = 'sveltekit:scroll';
442
+ const INDEX_KEY = 'sveltekit:index';
443
+
444
+ const routes = parse(components, dictionary, matchers);
445
+
446
+ // we import the root layout/error components eagerly, so that
447
+ // connectivity errors after initialisation don't nuke the app
448
+ const default_layout = components[0]();
449
+ const default_error = components[1]();
450
+
451
+ const root_stuff = {};
452
+
453
+ // We track the scroll position associated with each history entry in sessionStorage,
454
+ // rather than on history.state itself, because when navigation is driven by
455
+ // popstate it's too late to update the scroll position associated with the
456
+ // state we're navigating from
457
+
458
+ /** @typedef {{ x: number, y: number }} ScrollPosition */
459
+ /** @type {Record<number, ScrollPosition>} */
460
+ let scroll_positions = {};
461
+ try {
462
+ scroll_positions = JSON.parse(sessionStorage[SCROLL_KEY]);
463
+ } catch {
464
+ // do nothing
465
+ }
466
+
467
+ /** @param {number} index */
468
+ function update_scroll_positions(index) {
469
+ scroll_positions[index] = scroll_state();
470
+ }
471
+
472
+ /**
473
+ * @param {{
474
+ * target: Element;
475
+ * session: App.Session;
476
+ * base: string;
477
+ * trailing_slash: import('types').TrailingSlash;
478
+ * }} opts
479
+ * @returns {import('./types').Client}
480
+ */
481
+ function create_client({ target, session, base, trailing_slash }) {
482
+ /** @type {Map<string, import('./types').NavigationResult>} */
483
+ const cache = new Map();
484
+
485
+ /** @type {Array<((href: string) => boolean)>} */
486
+ const invalidated = [];
487
+
488
+ const stores = {
489
+ url: notifiable_store({}),
490
+ page: notifiable_store({}),
491
+ navigating: writable(/** @type {import('types').Navigation | null} */ (null)),
492
+ session: writable(session),
493
+ updated: create_updated_store()
494
+ };
495
+
496
+ /** @type {{id: string | null, promise: Promise<import('./types').NavigationResult | undefined> | null}} */
497
+ const load_cache = {
498
+ id: null,
499
+ promise: null
500
+ };
501
+
502
+ const callbacks = {
503
+ /** @type {Array<(opts: { from: URL, to: URL | null, cancel: () => void }) => void>} */
504
+ before_navigate: [],
505
+
506
+ /** @type {Array<(opts: { from: URL | null, to: URL }) => void>} */
507
+ after_navigate: []
508
+ };
509
+
510
+ /** @type {import('./types').NavigationState} */
511
+ let current = {
512
+ branch: [],
513
+ error: null,
514
+ session_id: 0,
515
+ stuff: root_stuff,
516
+ // @ts-ignore - we need the initial value to be null
517
+ url: null
518
+ };
519
+
520
+ let started = false;
521
+ let autoscroll = true;
522
+ let updating = false;
523
+ let session_id = 1;
524
+
525
+ /** @type {Promise<void> | null} */
526
+ let invalidating = null;
527
+
528
+ /** @type {import('svelte').SvelteComponent} */
529
+ let root;
530
+
531
+ /** @type {App.Session} */
532
+ let $session;
533
+
534
+ let ready = false;
535
+ stores.session.subscribe(async (value) => {
536
+ $session = value;
537
+
538
+ if (!ready) return;
539
+ session_id += 1;
540
+
541
+ update(new URL(location.href), [], true);
542
+ });
543
+ ready = true;
544
+
545
+ let router_enabled = true;
546
+
547
+ // keeping track of the history index in order to prevent popstate navigation events if needed
548
+ let current_history_index = history.state?.[INDEX_KEY];
549
+
550
+ if (!current_history_index) {
551
+ // we use Date.now() as an offset so that cross-document navigations
552
+ // within the app don't result in data loss
553
+ current_history_index = Date.now();
554
+
555
+ // create initial history entry, so we can return here
556
+ history.replaceState(
557
+ { ...history.state, [INDEX_KEY]: current_history_index },
558
+ '',
559
+ location.href
560
+ );
561
+ }
562
+
563
+ // if we reload the page, or Cmd-Shift-T back to it,
564
+ // recover scroll position
565
+ const scroll = scroll_positions[current_history_index];
566
+ if (scroll) {
567
+ history.scrollRestoration = 'manual';
568
+ scrollTo(scroll.x, scroll.y);
569
+ }
570
+
571
+ let hash_navigating = false;
572
+
573
+ /** @type {import('types').Page} */
574
+ let page;
575
+
576
+ /** @type {{}} */
577
+ let token;
578
+
579
+ /**
580
+ * @param {string | URL} url
581
+ * @param {{ noscroll?: boolean; replaceState?: boolean; keepfocus?: boolean; state?: any }} opts
582
+ * @param {string[]} redirect_chain
583
+ */
584
+ async function goto(
585
+ url,
586
+ { noscroll = false, replaceState = false, keepfocus = false, state = {} },
587
+ redirect_chain
588
+ ) {
589
+ if (typeof url === 'string') {
590
+ url = new URL(url, get_base_uri(document));
591
+ }
592
+
593
+ if (router_enabled) {
594
+ return navigate({
595
+ url,
596
+ scroll: noscroll ? scroll_state() : null,
597
+ keepfocus,
598
+ redirect_chain,
599
+ details: {
600
+ state,
601
+ replaceState
602
+ },
603
+ accepted: () => {},
604
+ blocked: () => {}
605
+ });
606
+ }
607
+
608
+ await native_navigation(url);
609
+ }
610
+
611
+ /** @param {URL} url */
612
+ async function prefetch(url) {
613
+ const intent = get_navigation_intent(url);
614
+
615
+ if (!intent) {
616
+ throw new Error('Attempted to prefetch a URL that does not belong to this app');
617
+ }
618
+
619
+ load_cache.promise = load_route(intent, false);
620
+ load_cache.id = intent.id;
621
+
622
+ return load_cache.promise;
623
+ }
624
+
625
+ /**
626
+ * Returns `true` if update completes, `false` if it is aborted
627
+ * @param {URL} url
628
+ * @param {string[]} redirect_chain
629
+ * @param {boolean} no_cache
630
+ * @param {{hash?: string, scroll: { x: number, y: number } | null, keepfocus: boolean, details: { replaceState: boolean, state: any } | null}} [opts]
631
+ * @param {() => void} [callback]
632
+ */
633
+ async function update(url, redirect_chain, no_cache, opts, callback) {
634
+ const intent = get_navigation_intent(url);
635
+
636
+ const current_token = (token = {});
637
+ let navigation_result = intent && (await load_route(intent, no_cache));
638
+
639
+ if (
640
+ !navigation_result &&
641
+ url.origin === location.origin &&
642
+ url.pathname === location.pathname
643
+ ) {
644
+ // this could happen in SPA fallback mode if the user navigated to
645
+ // `/non-existent-page`. if we fall back to reloading the page, it
646
+ // will create an infinite loop. so whereas we normally handle
647
+ // unknown routes by going to the server, in this special case
648
+ // we render a client-side error page instead
649
+ navigation_result = await load_root_error_page({
650
+ status: 404,
651
+ error: new Error(`Not found: ${url.pathname}`),
652
+ url,
653
+ routeId: null
654
+ });
655
+ }
656
+
657
+ if (!navigation_result) {
658
+ await native_navigation(url);
659
+ return false; // unnecessary, but TypeScript prefers it this way
660
+ }
661
+
662
+ // abort if user navigated during update
663
+ if (token !== current_token) return false;
664
+
665
+ invalidated.length = 0;
666
+
667
+ if (navigation_result.redirect) {
668
+ if (redirect_chain.length > 10 || redirect_chain.includes(url.pathname)) {
669
+ navigation_result = await load_root_error_page({
670
+ status: 500,
671
+ error: new Error('Redirect loop'),
672
+ url,
673
+ routeId: null
674
+ });
675
+ } else {
676
+ if (router_enabled) {
677
+ goto(new URL(navigation_result.redirect, url).href, {}, [
678
+ ...redirect_chain,
679
+ url.pathname
680
+ ]);
681
+ } else {
682
+ await native_navigation(new URL(navigation_result.redirect, location.href));
683
+ }
684
+
685
+ return false;
686
+ }
687
+ } else if (navigation_result.props?.page?.status >= 400) {
688
+ const updated = await stores.updated.check();
689
+ if (updated) {
690
+ await native_navigation(url);
691
+ }
692
+ }
693
+
694
+ updating = true;
695
+
696
+ if (opts && opts.details) {
697
+ const { details } = opts;
698
+ const change = details.replaceState ? 0 : 1;
699
+ details.state[INDEX_KEY] = current_history_index += change;
700
+ history[details.replaceState ? 'replaceState' : 'pushState'](details.state, '', url);
701
+ }
702
+
703
+ if (started) {
704
+ current = navigation_result.state;
705
+
706
+ if (navigation_result.props.page) {
707
+ navigation_result.props.page.url = url;
708
+ }
709
+
710
+ root.$set(navigation_result.props);
711
+ } else {
712
+ initialize(navigation_result);
713
+ }
714
+
715
+ // opts must be passed if we're navigating
716
+ if (opts) {
717
+ const { scroll, keepfocus } = opts;
718
+
719
+ if (!keepfocus) {
720
+ // Reset page selection and focus
721
+ // We try to mimic browsers' behaviour as closely as possible by targeting the
722
+ // first scrollable region, but unfortunately it's not a perfect match — e.g.
723
+ // shift-tabbing won't immediately cycle up from the end of the page on Chromium
724
+ // See https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area
725
+ const root = document.body;
726
+ const tabindex = root.getAttribute('tabindex');
727
+
728
+ getSelection()?.removeAllRanges();
729
+ root.tabIndex = -1;
730
+ root.focus({ preventScroll: true });
731
+
732
+ // restore `tabindex` as to prevent `root` from stealing input from elements
733
+ if (tabindex !== null) {
734
+ root.setAttribute('tabindex', tabindex);
735
+ } else {
736
+ root.removeAttribute('tabindex');
737
+ }
738
+ }
739
+
740
+ // need to render the DOM before we can scroll to the rendered elements
741
+ await tick();
742
+
743
+ if (autoscroll) {
744
+ const deep_linked = url.hash && document.getElementById(url.hash.slice(1));
745
+ if (scroll) {
746
+ scrollTo(scroll.x, scroll.y);
747
+ } else if (deep_linked) {
748
+ // Here we use `scrollIntoView` on the element instead of `scrollTo`
749
+ // because it natively supports the `scroll-margin` and `scroll-behavior`
750
+ // CSS properties.
751
+ deep_linked.scrollIntoView();
752
+ } else {
753
+ scrollTo(0, 0);
754
+ }
755
+ }
756
+ } else {
757
+ // in this case we're simply invalidating
758
+ await tick();
759
+ }
760
+
761
+ load_cache.promise = null;
762
+ load_cache.id = null;
763
+ autoscroll = true;
764
+
765
+ if (navigation_result.props.page) {
766
+ page = navigation_result.props.page;
767
+ }
768
+
769
+ const leaf_node = navigation_result.state.branch[navigation_result.state.branch.length - 1];
770
+ router_enabled = leaf_node?.module.router !== false;
771
+
772
+ if (callback) callback();
773
+
774
+ updating = false;
775
+ }
776
+
777
+ /** @param {import('./types').NavigationResult} result */
778
+ function initialize(result) {
779
+ current = result.state;
780
+
781
+ const style = document.querySelector('style[data-sveltekit]');
782
+ if (style) style.remove();
783
+
784
+ page = result.props.page;
785
+
786
+ root = new Root({
787
+ target,
788
+ props: { ...result.props, stores },
789
+ hydrate: true
790
+ });
791
+
792
+ if (router_enabled) {
793
+ const navigation = { from: null, to: new URL(location.href) };
794
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
795
+ }
796
+
797
+ started = true;
798
+ }
799
+
800
+ /**
801
+ *
802
+ * @param {{
803
+ * url: URL;
804
+ * params: Record<string, string>;
805
+ * stuff: Record<string, any>;
806
+ * branch: Array<import('./types').BranchNode | undefined>;
807
+ * status: number;
808
+ * error: Error | null;
809
+ * routeId: string | null;
810
+ * }} opts
811
+ */
812
+ async function get_navigation_result_from_branch({
813
+ url,
814
+ params,
815
+ stuff,
816
+ branch,
817
+ status,
818
+ error,
819
+ routeId
820
+ }) {
821
+ const filtered = /** @type {import('./types').BranchNode[] } */ (branch.filter(Boolean));
822
+ const redirect = filtered.find((f) => f.loaded?.redirect);
823
+
824
+ /** @type {import('./types').NavigationResult} */
825
+ const result = {
826
+ redirect: redirect?.loaded?.redirect,
827
+ state: {
828
+ url,
829
+ params,
830
+ branch,
831
+ error,
832
+ stuff,
833
+ session_id
834
+ },
835
+ props: {
836
+ components: filtered.map((node) => node.module.default)
837
+ }
838
+ };
839
+
840
+ for (let i = 0; i < filtered.length; i += 1) {
841
+ const loaded = filtered[i].loaded;
842
+ result.props[`props_${i}`] = loaded ? await loaded.props : null;
843
+ }
844
+
845
+ const page_changed =
846
+ !current.url ||
847
+ url.href !== current.url.href ||
848
+ current.error !== error ||
849
+ current.stuff !== stuff;
850
+
851
+ if (page_changed) {
852
+ result.props.page = { error, params, routeId, status, stuff, url };
853
+
854
+ // TODO remove this for 1.0
855
+ /**
856
+ * @param {string} property
857
+ * @param {string} replacement
858
+ */
859
+ const print_error = (property, replacement) => {
860
+ Object.defineProperty(result.props.page, property, {
861
+ get: () => {
862
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
863
+ }
864
+ });
865
+ };
866
+
867
+ print_error('origin', 'origin');
868
+ print_error('path', 'pathname');
869
+ print_error('query', 'searchParams');
870
+ }
871
+
872
+ const leaf = filtered[filtered.length - 1];
873
+ const load_cache = leaf?.loaded?.cache;
874
+
875
+ if (load_cache) {
876
+ const key = url.pathname + url.search; // omit hash
877
+ let ready = false;
878
+
879
+ const clear = () => {
880
+ if (cache.get(key) === result) {
881
+ cache.delete(key);
882
+ }
883
+
884
+ unsubscribe();
885
+ clearTimeout(timeout);
886
+ };
887
+
888
+ const timeout = setTimeout(clear, load_cache.maxage * 1000);
889
+
890
+ const unsubscribe = stores.session.subscribe(() => {
891
+ if (ready) clear();
892
+ });
893
+
894
+ ready = true;
895
+
896
+ cache.set(key, result);
897
+ }
898
+
899
+ return result;
900
+ }
901
+
902
+ /**
903
+ * @param {{
904
+ * status?: number;
905
+ * error?: Error;
906
+ * module: import('types').CSRComponent;
907
+ * url: URL;
908
+ * params: Record<string, string>;
909
+ * stuff: Record<string, any>;
910
+ * props?: Record<string, any>;
911
+ * routeId: string | null;
912
+ * }} options
913
+ */
914
+ async function load_node({ status, error, module, url, params, stuff, props, routeId }) {
915
+ /** @type {import('./types').BranchNode} */
916
+ const node = {
917
+ module,
918
+ uses: {
919
+ params: new Set(),
920
+ url: false,
921
+ session: false,
922
+ stuff: false,
923
+ dependencies: new Set()
924
+ },
925
+ loaded: null,
926
+ stuff
927
+ };
928
+
929
+ /** @param dep {string} */
930
+ function add_dependency(dep) {
931
+ const { href } = new URL(dep, url);
932
+ node.uses.dependencies.add(href);
933
+ }
934
+
935
+ if (props) {
936
+ // shadow endpoint props means we need to mark this URL as a dependency of itself
937
+ node.uses.dependencies.add(url.href);
938
+ }
939
+
940
+ /** @type {Record<string, string>} */
941
+ const uses_params = {};
942
+ for (const key in params) {
943
+ Object.defineProperty(uses_params, key, {
944
+ get() {
945
+ node.uses.params.add(key);
946
+ return params[key];
947
+ },
948
+ enumerable: true
949
+ });
950
+ }
951
+
952
+ const session = $session;
953
+ const load_url = new LoadURL(url);
954
+
955
+ if (module.load) {
956
+ /** @type {import('types').LoadEvent} */
957
+ const load_input = {
958
+ routeId,
959
+ params: uses_params,
960
+ props: props || {},
961
+ get url() {
962
+ node.uses.url = true;
963
+ return load_url;
964
+ },
965
+ get session() {
966
+ node.uses.session = true;
967
+ return session;
968
+ },
969
+ get stuff() {
970
+ node.uses.stuff = true;
971
+ return { ...stuff };
972
+ },
973
+ async fetch(resource, init) {
974
+ let requested;
975
+
976
+ if (typeof resource === 'string') {
977
+ requested = resource;
978
+ } else {
979
+ requested = resource.url;
980
+
981
+ // we're not allowed to modify the received `Request` object, so in order
982
+ // to fixup relative urls we create a new equivalent `init` object instead
983
+ init = {
984
+ // the request body must be consumed in memory until browsers
985
+ // implement streaming request bodies and/or the body getter
986
+ body:
987
+ resource.method === 'GET' || resource.method === 'HEAD'
988
+ ? undefined
989
+ : await resource.blob(),
990
+ cache: resource.cache,
991
+ credentials: resource.credentials,
992
+ headers: resource.headers,
993
+ integrity: resource.integrity,
994
+ keepalive: resource.keepalive,
995
+ method: resource.method,
996
+ mode: resource.mode,
997
+ redirect: resource.redirect,
998
+ referrer: resource.referrer,
999
+ referrerPolicy: resource.referrerPolicy,
1000
+ signal: resource.signal,
1001
+ ...init
1002
+ };
1003
+ }
1004
+
1005
+ // we must fixup relative urls so they are resolved from the target page
1006
+ const normalized = new URL(requested, url).href;
1007
+ add_dependency(normalized);
1008
+
1009
+ // prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be normalized
1010
+ return started ? native_fetch(normalized, init) : initial_fetch(requested, init);
1011
+ },
1012
+ status: status ?? null,
1013
+ error: error ?? null
1014
+ };
1015
+
1016
+ if (import.meta.env.DEV) {
1017
+ // TODO remove this for 1.0
1018
+ Object.defineProperty(load_input, 'page', {
1019
+ get: () => {
1020
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
1021
+ }
1022
+ });
1023
+ }
1024
+
1025
+ let loaded;
1026
+
1027
+ if (import.meta.env.DEV) {
1028
+ try {
1029
+ lock_fetch();
1030
+ loaded = await module.load.call(null, load_input);
1031
+ } finally {
1032
+ unlock_fetch();
1033
+ }
1034
+ } else {
1035
+ loaded = await module.load.call(null, load_input);
1036
+ }
1037
+
1038
+ if (!loaded) {
1039
+ throw new Error('load function must return a value');
1040
+ }
1041
+
1042
+ node.loaded = normalize(loaded);
1043
+ if (node.loaded.stuff) node.stuff = node.loaded.stuff;
1044
+ if (node.loaded.dependencies) {
1045
+ node.loaded.dependencies.forEach(add_dependency);
1046
+ }
1047
+ } else if (props) {
1048
+ node.loaded = normalize({ props });
1049
+ }
1050
+
1051
+ return node;
1052
+ }
1053
+
1054
+ /**
1055
+ * @param {import('./types').NavigationIntent} intent
1056
+ * @param {boolean} no_cache
1057
+ */
1058
+ async function load_route({ id, url, params, route }, no_cache) {
1059
+ if (load_cache.id === id && load_cache.promise) {
1060
+ return load_cache.promise;
1061
+ }
1062
+
1063
+ if (!no_cache) {
1064
+ const cached = cache.get(id);
1065
+ if (cached) return cached;
1066
+ }
1067
+
1068
+ const { a, b, has_shadow } = route;
1069
+
1070
+ const changed = current.url && {
1071
+ url: id !== current.url.pathname + current.url.search,
1072
+ params: Object.keys(params).filter((key) => current.params[key] !== params[key]),
1073
+ session: session_id !== current.session_id
1074
+ };
1075
+
1076
+ /** @type {Array<import('./types').BranchNode | undefined>} */
1077
+ let branch = [];
1078
+
1079
+ /** @type {Record<string, any>} */
1080
+ let stuff = root_stuff;
1081
+ let stuff_changed = false;
1082
+
1083
+ /** @type {number | undefined} */
1084
+ let status = 200;
1085
+
1086
+ /** @type {Error | null} */
1087
+ let error = null;
1088
+
1089
+ // preload modules to avoid waterfall, but handle rejections
1090
+ // so they don't get reported to Sentry et al (we don't need
1091
+ // to act on the failures at this point)
1092
+ a.forEach((loader) => loader().catch(() => {}));
1093
+
1094
+ load: for (let i = 0; i < a.length; i += 1) {
1095
+ /** @type {import('./types').BranchNode | undefined} */
1096
+ let node;
1097
+
1098
+ try {
1099
+ if (!a[i]) continue;
1100
+
1101
+ const module = await a[i]();
1102
+ const previous = current.branch[i];
1103
+
1104
+ const changed_since_last_render =
1105
+ !previous ||
1106
+ module !== previous.module ||
1107
+ (changed.url && previous.uses.url) ||
1108
+ changed.params.some((param) => previous.uses.params.has(param)) ||
1109
+ (changed.session && previous.uses.session) ||
1110
+ Array.from(previous.uses.dependencies).some((dep) => invalidated.some((fn) => fn(dep))) ||
1111
+ (stuff_changed && previous.uses.stuff);
1112
+
1113
+ if (changed_since_last_render) {
1114
+ /** @type {Record<string, any>} */
1115
+ let props = {};
1116
+
1117
+ const is_shadow_page = has_shadow && i === a.length - 1;
1118
+
1119
+ if (is_shadow_page) {
1120
+ const res = await native_fetch(
1121
+ `${url.pathname}${url.pathname.endsWith('/') ? '' : '/'}__data.json${url.search}`,
1122
+ {
1123
+ headers: {
1124
+ 'x-sveltekit-load': 'true'
1125
+ }
1126
+ }
1127
+ );
1128
+
1129
+ if (res.ok) {
1130
+ const redirect = res.headers.get('x-sveltekit-location');
1131
+
1132
+ if (redirect) {
1133
+ return {
1134
+ redirect,
1135
+ props: {},
1136
+ state: current
1137
+ };
1138
+ }
1139
+
1140
+ props = res.status === 204 ? {} : await res.json();
1141
+ } else {
1142
+ status = res.status;
1143
+ try {
1144
+ error = await res.json();
1145
+ } catch (e) {
1146
+ error = new Error('Failed to load data');
1147
+ }
1148
+ }
1149
+ }
1150
+
1151
+ if (!error) {
1152
+ node = await load_node({
1153
+ module,
1154
+ url,
1155
+ params,
1156
+ props,
1157
+ stuff,
1158
+ routeId: route.id
1159
+ });
1160
+ }
1161
+
1162
+ if (node) {
1163
+ if (is_shadow_page) {
1164
+ node.uses.url = true;
1165
+ }
1166
+
1167
+ if (node.loaded) {
1168
+ if (node.loaded.error) {
1169
+ status = node.loaded.status;
1170
+ error = node.loaded.error;
1171
+ }
1172
+
1173
+ if (node.loaded.redirect) {
1174
+ return {
1175
+ redirect: node.loaded.redirect,
1176
+ props: {},
1177
+ state: current
1178
+ };
1179
+ }
1180
+
1181
+ if (node.loaded.stuff) {
1182
+ stuff_changed = true;
1183
+ }
1184
+ }
1185
+ }
1186
+ } else {
1187
+ node = previous;
1188
+ }
1189
+ } catch (e) {
1190
+ status = 500;
1191
+ error = coalesce_to_error(e);
1192
+ }
1193
+
1194
+ if (error) {
1195
+ while (i--) {
1196
+ if (b[i]) {
1197
+ let error_loaded;
1198
+
1199
+ /** @type {import('./types').BranchNode | undefined} */
1200
+ let node_loaded;
1201
+ let j = i;
1202
+ while (!(node_loaded = branch[j])) {
1203
+ j -= 1;
1204
+ }
1205
+
1206
+ try {
1207
+ error_loaded = await load_node({
1208
+ status,
1209
+ error,
1210
+ module: await b[i](),
1211
+ url,
1212
+ params,
1213
+ stuff: node_loaded.stuff,
1214
+ routeId: route.id
1215
+ });
1216
+
1217
+ if (error_loaded?.loaded?.error) {
1218
+ continue;
1219
+ }
1220
+
1221
+ if (error_loaded?.loaded?.stuff) {
1222
+ stuff = {
1223
+ ...stuff,
1224
+ ...error_loaded.loaded.stuff
1225
+ };
1226
+ }
1227
+
1228
+ branch = branch.slice(0, j + 1).concat(error_loaded);
1229
+ break load;
1230
+ } catch (e) {
1231
+ continue;
1232
+ }
1233
+ }
1234
+ }
1235
+
1236
+ return await load_root_error_page({
1237
+ status,
1238
+ error,
1239
+ url,
1240
+ routeId: route.id
1241
+ });
1242
+ } else {
1243
+ if (node?.loaded?.stuff) {
1244
+ stuff = {
1245
+ ...stuff,
1246
+ ...node.loaded.stuff
1247
+ };
1248
+ }
1249
+
1250
+ branch.push(node);
1251
+ }
1252
+ }
1253
+
1254
+ return await get_navigation_result_from_branch({
1255
+ url,
1256
+ params,
1257
+ stuff,
1258
+ branch,
1259
+ status,
1260
+ error,
1261
+ routeId: route.id
1262
+ });
1263
+ }
1264
+
1265
+ /**
1266
+ * @param {{
1267
+ * status: number;
1268
+ * error: Error;
1269
+ * url: URL;
1270
+ * routeId: string | null
1271
+ * }} opts
1272
+ */
1273
+ async function load_root_error_page({ status, error, url, routeId }) {
1274
+ /** @type {Record<string, string>} */
1275
+ const params = {}; // error page does not have params
1276
+
1277
+ const root_layout = await load_node({
1278
+ module: await default_layout,
1279
+ url,
1280
+ params,
1281
+ stuff: {},
1282
+ routeId
1283
+ });
1284
+
1285
+ const root_error = await load_node({
1286
+ status,
1287
+ error,
1288
+ module: await default_error,
1289
+ url,
1290
+ params,
1291
+ stuff: (root_layout && root_layout.loaded && root_layout.loaded.stuff) || {},
1292
+ routeId
1293
+ });
1294
+
1295
+ return await get_navigation_result_from_branch({
1296
+ url,
1297
+ params,
1298
+ stuff: {
1299
+ ...root_layout?.loaded?.stuff,
1300
+ ...root_error?.loaded?.stuff
1301
+ },
1302
+ branch: [root_layout, root_error],
1303
+ status,
1304
+ error,
1305
+ routeId
1306
+ });
1307
+ }
1308
+
1309
+ /** @param {URL} url */
1310
+ function get_navigation_intent(url) {
1311
+ if (url.origin !== location.origin || !url.pathname.startsWith(base)) return;
1312
+
1313
+ const path = decodeURI(url.pathname.slice(base.length) || '/');
1314
+
1315
+ for (const route of routes) {
1316
+ const params = route.exec(path);
1317
+
1318
+ if (params) {
1319
+ /** @type {import('./types').NavigationIntent} */
1320
+ const intent = {
1321
+ id: url.pathname + url.search,
1322
+ route,
1323
+ params,
1324
+ url
1325
+ };
1326
+
1327
+ return intent;
1328
+ }
1329
+ }
1330
+ }
1331
+
1332
+ /**
1333
+ * @param {{
1334
+ * url: URL;
1335
+ * scroll: { x: number, y: number } | null;
1336
+ * keepfocus: boolean;
1337
+ * redirect_chain: string[];
1338
+ * details: {
1339
+ * replaceState: boolean;
1340
+ * state: any;
1341
+ * } | null;
1342
+ * accepted: () => void;
1343
+ * blocked: () => void;
1344
+ * }} opts
1345
+ */
1346
+ async function navigate({ url, scroll, keepfocus, redirect_chain, details, accepted, blocked }) {
1347
+ const from = current.url;
1348
+ let should_block = false;
1349
+
1350
+ const navigation = {
1351
+ from,
1352
+ to: url,
1353
+ cancel: () => (should_block = true)
1354
+ };
1355
+
1356
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1357
+
1358
+ if (should_block) {
1359
+ blocked();
1360
+ return;
1361
+ }
1362
+
1363
+ const pathname = normalize_path(url.pathname, trailing_slash);
1364
+ const normalized = new URL(url.origin + pathname + url.search + url.hash);
1365
+
1366
+ update_scroll_positions(current_history_index);
1367
+
1368
+ accepted();
1369
+
1370
+ if (started) {
1371
+ stores.navigating.set({
1372
+ from: current.url,
1373
+ to: normalized
1374
+ });
1375
+ }
1376
+
1377
+ await update(
1378
+ normalized,
1379
+ redirect_chain,
1380
+ false,
1381
+ {
1382
+ scroll,
1383
+ keepfocus,
1384
+ details
1385
+ },
1386
+ () => {
1387
+ const navigation = { from, to: normalized };
1388
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
1389
+
1390
+ stores.navigating.set(null);
1391
+ }
1392
+ );
1393
+ }
1394
+
1395
+ /**
1396
+ * Loads `href` the old-fashioned way, with a full page reload.
1397
+ * Returns a `Promise` that never resolves (to prevent any
1398
+ * subsequent work, e.g. history manipulation, from happening)
1399
+ * @param {URL} url
1400
+ */
1401
+ function native_navigation(url) {
1402
+ location.href = url.href;
1403
+ return new Promise(() => {});
1404
+ }
1405
+
1406
+ if (import.meta.hot) {
1407
+ import.meta.hot.on('vite:beforeUpdate', () => {
1408
+ if (current.error) location.reload();
1409
+ });
1410
+ }
1411
+
1412
+ return {
1413
+ after_navigate: (fn) => {
1414
+ onMount(() => {
1415
+ callbacks.after_navigate.push(fn);
1416
+
1417
+ return () => {
1418
+ const i = callbacks.after_navigate.indexOf(fn);
1419
+ callbacks.after_navigate.splice(i, 1);
1420
+ };
1421
+ });
1422
+ },
1423
+
1424
+ before_navigate: (fn) => {
1425
+ onMount(() => {
1426
+ callbacks.before_navigate.push(fn);
1427
+
1428
+ return () => {
1429
+ const i = callbacks.before_navigate.indexOf(fn);
1430
+ callbacks.before_navigate.splice(i, 1);
1431
+ };
1432
+ });
1433
+ },
1434
+
1435
+ disable_scroll_handling: () => {
1436
+ if (import.meta.env.DEV && started && !updating) {
1437
+ throw new Error('Can only disable scroll handling during navigation');
1438
+ }
1439
+
1440
+ if (updating || !started) {
1441
+ autoscroll = false;
1442
+ }
1443
+ },
1444
+
1445
+ goto: (href, opts = {}) => goto(href, opts, []),
1446
+
1447
+ invalidate: (resource) => {
1448
+ if (typeof resource === 'function') {
1449
+ invalidated.push(resource);
1450
+ } else {
1451
+ const { href } = new URL(resource, location.href);
1452
+ invalidated.push((dep) => dep === href);
1453
+ }
1454
+
1455
+ if (!invalidating) {
1456
+ invalidating = Promise.resolve().then(async () => {
1457
+ await update(new URL(location.href), [], true);
1458
+
1459
+ invalidating = null;
1460
+ });
1461
+ }
1462
+
1463
+ return invalidating;
1464
+ },
1465
+
1466
+ prefetch: async (href) => {
1467
+ const url = new URL(href, get_base_uri(document));
1468
+ await prefetch(url);
1469
+ },
1470
+
1471
+ // TODO rethink this API
1472
+ prefetch_routes: async (pathnames) => {
1473
+ const matching = pathnames
1474
+ ? routes.filter((route) => pathnames.some((pathname) => route.exec(pathname)))
1475
+ : routes;
1476
+
1477
+ const promises = matching.map((r) => Promise.all(r.a.map((load) => load())));
1478
+
1479
+ await Promise.all(promises);
1480
+ },
1481
+
1482
+ _start_router: () => {
1483
+ history.scrollRestoration = 'manual';
1484
+
1485
+ // Adopted from Nuxt.js
1486
+ // Reset scrollRestoration to auto when leaving page, allowing page reload
1487
+ // and back-navigation from other pages to use the browser to restore the
1488
+ // scrolling position.
1489
+ addEventListener('beforeunload', (e) => {
1490
+ let should_block = false;
1491
+
1492
+ const navigation = {
1493
+ from: current.url,
1494
+ to: null,
1495
+ cancel: () => (should_block = true)
1496
+ };
1497
+
1498
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1499
+
1500
+ if (should_block) {
1501
+ e.preventDefault();
1502
+ e.returnValue = '';
1503
+ } else {
1504
+ history.scrollRestoration = 'auto';
1505
+ }
1506
+ });
1507
+
1508
+ addEventListener('visibilitychange', () => {
1509
+ if (document.visibilityState === 'hidden') {
1510
+ update_scroll_positions(current_history_index);
1511
+
1512
+ try {
1513
+ sessionStorage[SCROLL_KEY] = JSON.stringify(scroll_positions);
1514
+ } catch {
1515
+ // do nothing
1516
+ }
1517
+ }
1518
+ });
1519
+
1520
+ /** @param {Event} event */
1521
+ const trigger_prefetch = (event) => {
1522
+ const a = find_anchor(event);
1523
+ if (a && a.href && a.hasAttribute('sveltekit:prefetch')) {
1524
+ prefetch(get_href(a));
1525
+ }
1526
+ };
1527
+
1528
+ /** @type {NodeJS.Timeout} */
1529
+ let mousemove_timeout;
1530
+
1531
+ /** @param {MouseEvent|TouchEvent} event */
1532
+ const handle_mousemove = (event) => {
1533
+ clearTimeout(mousemove_timeout);
1534
+ mousemove_timeout = setTimeout(() => {
1535
+ // event.composedPath(), which is used in find_anchor, will be empty if the event is read in a timeout
1536
+ // add a layer of indirection to address that
1537
+ event.target?.dispatchEvent(
1538
+ new CustomEvent('sveltekit:trigger_prefetch', { bubbles: true })
1539
+ );
1540
+ }, 20);
1541
+ };
1542
+
1543
+ addEventListener('touchstart', trigger_prefetch);
1544
+ addEventListener('mousemove', handle_mousemove);
1545
+ addEventListener('sveltekit:trigger_prefetch', trigger_prefetch);
1546
+
1547
+ /** @param {MouseEvent} event */
1548
+ addEventListener('click', (event) => {
1549
+ if (!router_enabled) return;
1550
+
1551
+ // Adapted from https://github.com/visionmedia/page.js
1552
+ // MIT license https://github.com/visionmedia/page.js#license
1553
+ if (event.button || event.which !== 1) return;
1554
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
1555
+ if (event.defaultPrevented) return;
1556
+
1557
+ const a = find_anchor(event);
1558
+ if (!a) return;
1559
+
1560
+ if (!a.href) return;
1561
+
1562
+ const is_svg_a_element = a instanceof SVGAElement;
1563
+ const url = get_href(a);
1564
+
1565
+ // Ignore if url does not have origin (e.g. `mailto:`, `tel:`.)
1566
+ // MEMO: Without this condition, firefox will open mailer twice.
1567
+ // See: https://github.com/sveltejs/kit/issues/4045
1568
+ if (!is_svg_a_element && url.origin === 'null') return;
1569
+
1570
+ // Ignore if tag has
1571
+ // 1. 'download' attribute
1572
+ // 2. 'rel' attribute includes external
1573
+ const rel = (a.getAttribute('rel') || '').split(/\s+/);
1574
+
1575
+ if (
1576
+ a.hasAttribute('download') ||
1577
+ rel.includes('external') ||
1578
+ a.hasAttribute('sveltekit:reload')
1579
+ ) {
1580
+ return;
1581
+ }
1582
+
1583
+ // Ignore if <a> has a target
1584
+ if (is_svg_a_element ? a.target.baseVal : a.target) return;
1585
+
1586
+ // Check if new url only differs by hash and use the browser default behavior in that case
1587
+ // This will ensure the `hashchange` event is fired
1588
+ // Removing the hash does a full page navigation in the browser, so make sure a hash is present
1589
+ const [base, hash] = url.href.split('#');
1590
+ if (hash !== undefined && base === location.href.split('#')[0]) {
1591
+ // set this flag to distinguish between navigations triggered by
1592
+ // clicking a hash link and those triggered by popstate
1593
+ hash_navigating = true;
1594
+
1595
+ update_scroll_positions(current_history_index);
1596
+
1597
+ stores.page.set({ ...page, url });
1598
+ stores.page.notify();
1599
+
1600
+ return;
1601
+ }
1602
+
1603
+ navigate({
1604
+ url,
1605
+ scroll: a.hasAttribute('sveltekit:noscroll') ? scroll_state() : null,
1606
+ keepfocus: false,
1607
+ redirect_chain: [],
1608
+ details: {
1609
+ state: {},
1610
+ replaceState: url.href === location.href
1611
+ },
1612
+ accepted: () => event.preventDefault(),
1613
+ blocked: () => event.preventDefault()
1614
+ });
1615
+ });
1616
+
1617
+ addEventListener('popstate', (event) => {
1618
+ if (event.state && router_enabled) {
1619
+ // if a popstate-driven navigation is cancelled, we need to counteract it
1620
+ // with history.go, which means we end up back here, hence this check
1621
+ if (event.state[INDEX_KEY] === current_history_index) return;
1622
+
1623
+ navigate({
1624
+ url: new URL(location.href),
1625
+ scroll: scroll_positions[event.state[INDEX_KEY]],
1626
+ keepfocus: false,
1627
+ redirect_chain: [],
1628
+ details: null,
1629
+ accepted: () => {
1630
+ current_history_index = event.state[INDEX_KEY];
1631
+ },
1632
+ blocked: () => {
1633
+ const delta = current_history_index - event.state[INDEX_KEY];
1634
+ history.go(delta);
1635
+ }
1636
+ });
1637
+ }
1638
+ });
1639
+
1640
+ addEventListener('hashchange', () => {
1641
+ // if the hashchange happened as a result of clicking on a link,
1642
+ // we need to update history, otherwise we have to leave it alone
1643
+ if (hash_navigating) {
1644
+ hash_navigating = false;
1645
+ history.replaceState(
1646
+ { ...history.state, [INDEX_KEY]: ++current_history_index },
1647
+ '',
1648
+ location.href
1649
+ );
1650
+ }
1651
+ });
1652
+ },
1653
+
1654
+ _hydrate: async ({ status, error, nodes, params, routeId }) => {
1655
+ const url = new URL(location.href);
1656
+
1657
+ /** @type {Array<import('./types').BranchNode | undefined>} */
1658
+ const branch = [];
1659
+
1660
+ /** @type {Record<string, any>} */
1661
+ let stuff = {};
1662
+
1663
+ /** @type {import('./types').NavigationResult | undefined} */
1664
+ let result;
1665
+
1666
+ let error_args;
1667
+
1668
+ try {
1669
+ for (let i = 0; i < nodes.length; i += 1) {
1670
+ const is_leaf = i === nodes.length - 1;
1671
+
1672
+ let props;
1673
+
1674
+ if (is_leaf) {
1675
+ const serialized = document.querySelector('script[sveltekit\\:data-type="props"]');
1676
+ if (serialized) {
1677
+ props = JSON.parse(/** @type {string} */ (serialized.textContent));
1678
+ }
1679
+ }
1680
+
1681
+ const node = await load_node({
1682
+ module: await components[nodes[i]](),
1683
+ url,
1684
+ params,
1685
+ stuff,
1686
+ status: is_leaf ? status : undefined,
1687
+ error: is_leaf ? error : undefined,
1688
+ props,
1689
+ routeId
1690
+ });
1691
+
1692
+ if (props) {
1693
+ node.uses.dependencies.add(url.href);
1694
+ node.uses.url = true;
1695
+ }
1696
+
1697
+ branch.push(node);
1698
+
1699
+ if (node && node.loaded) {
1700
+ if (node.loaded.error) {
1701
+ if (error) throw node.loaded.error;
1702
+ error_args = {
1703
+ status: node.loaded.status,
1704
+ error: node.loaded.error,
1705
+ url,
1706
+ routeId
1707
+ };
1708
+ } else if (node.loaded.stuff) {
1709
+ stuff = {
1710
+ ...stuff,
1711
+ ...node.loaded.stuff
1712
+ };
1713
+ }
1714
+ }
1715
+ }
1716
+
1717
+ result = error_args
1718
+ ? await load_root_error_page(error_args)
1719
+ : await get_navigation_result_from_branch({
1720
+ url,
1721
+ params,
1722
+ stuff,
1723
+ branch,
1724
+ status,
1725
+ error,
1726
+ routeId
1727
+ });
1728
+ } catch (e) {
1729
+ if (error) throw e;
1730
+
1731
+ result = await load_root_error_page({
1732
+ status: 500,
1733
+ error: coalesce_to_error(e),
1734
+ url,
1735
+ routeId
1736
+ });
1737
+ }
1738
+
1739
+ if (result.redirect) {
1740
+ // this is a real edge case — `load` would need to return
1741
+ // a redirect but only in the browser
1742
+ await native_navigation(new URL(result.redirect, location.href));
1743
+ }
1744
+
1745
+ initialize(result);
1746
+ }
1747
+ };
1748
+ }
1749
+
1750
+ /**
1751
+ * @param {{
1752
+ * paths: {
1753
+ * assets: string;
1754
+ * base: string;
1755
+ * },
1756
+ * target: Element;
1757
+ * session: any;
1758
+ * route: boolean;
1759
+ * spa: boolean;
1760
+ * trailing_slash: import('types').TrailingSlash;
1761
+ * hydrate: {
1762
+ * status: number;
1763
+ * error: Error;
1764
+ * nodes: number[];
1765
+ * params: Record<string, string>;
1766
+ * routeId: string | null;
1767
+ * };
1768
+ * }} opts
1769
+ */
1770
+ async function start({ paths, target, session, route, spa, trailing_slash, hydrate }) {
1771
+ const client = create_client({
1772
+ target,
1773
+ session,
1774
+ base: paths.base,
1775
+ trailing_slash
1776
+ });
1777
+
1778
+ init({ client });
1779
+ set_paths(paths);
1780
+
1781
+ if (hydrate) {
1782
+ await client._hydrate(hydrate);
1783
+ }
1784
+
1785
+ if (route) {
1786
+ if (spa) client.goto(location.href, { replaceState: true });
1787
+ client._start_router();
1788
+ }
1789
+
1790
+ dispatchEvent(new CustomEvent('sveltekit:start'));
1791
+ }
1792
+
1793
+ export { start };