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

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 +1789 -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 +3407 -0
  12. package/dist/chunks/_commonjsHelpers.js +3 -0
  13. package/dist/chunks/error.js +663 -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 +12238 -0
  22. package/dist/node.js +5855 -0
  23. package/dist/vite.js +3143 -0
  24. package/package.json +100 -55
  25. package/types/ambient.d.ts +345 -0
  26. package/types/index.d.ts +294 -0
  27. package/types/internal.d.ts +326 -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,1789 @@
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
+ error = new Error('Failed to load data');
1144
+ }
1145
+ }
1146
+
1147
+ if (!error) {
1148
+ node = await load_node({
1149
+ module,
1150
+ url,
1151
+ params,
1152
+ props,
1153
+ stuff,
1154
+ routeId: route.id
1155
+ });
1156
+ }
1157
+
1158
+ if (node) {
1159
+ if (is_shadow_page) {
1160
+ node.uses.url = true;
1161
+ }
1162
+
1163
+ if (node.loaded) {
1164
+ if (node.loaded.error) {
1165
+ status = node.loaded.status;
1166
+ error = node.loaded.error;
1167
+ }
1168
+
1169
+ if (node.loaded.redirect) {
1170
+ return {
1171
+ redirect: node.loaded.redirect,
1172
+ props: {},
1173
+ state: current
1174
+ };
1175
+ }
1176
+
1177
+ if (node.loaded.stuff) {
1178
+ stuff_changed = true;
1179
+ }
1180
+ }
1181
+ }
1182
+ } else {
1183
+ node = previous;
1184
+ }
1185
+ } catch (e) {
1186
+ status = 500;
1187
+ error = coalesce_to_error(e);
1188
+ }
1189
+
1190
+ if (error) {
1191
+ while (i--) {
1192
+ if (b[i]) {
1193
+ let error_loaded;
1194
+
1195
+ /** @type {import('./types').BranchNode | undefined} */
1196
+ let node_loaded;
1197
+ let j = i;
1198
+ while (!(node_loaded = branch[j])) {
1199
+ j -= 1;
1200
+ }
1201
+
1202
+ try {
1203
+ error_loaded = await load_node({
1204
+ status,
1205
+ error,
1206
+ module: await b[i](),
1207
+ url,
1208
+ params,
1209
+ stuff: node_loaded.stuff,
1210
+ routeId: route.id
1211
+ });
1212
+
1213
+ if (error_loaded?.loaded?.error) {
1214
+ continue;
1215
+ }
1216
+
1217
+ if (error_loaded?.loaded?.stuff) {
1218
+ stuff = {
1219
+ ...stuff,
1220
+ ...error_loaded.loaded.stuff
1221
+ };
1222
+ }
1223
+
1224
+ branch = branch.slice(0, j + 1).concat(error_loaded);
1225
+ break load;
1226
+ } catch (e) {
1227
+ continue;
1228
+ }
1229
+ }
1230
+ }
1231
+
1232
+ return await load_root_error_page({
1233
+ status,
1234
+ error,
1235
+ url,
1236
+ routeId: route.id
1237
+ });
1238
+ } else {
1239
+ if (node?.loaded?.stuff) {
1240
+ stuff = {
1241
+ ...stuff,
1242
+ ...node.loaded.stuff
1243
+ };
1244
+ }
1245
+
1246
+ branch.push(node);
1247
+ }
1248
+ }
1249
+
1250
+ return await get_navigation_result_from_branch({
1251
+ url,
1252
+ params,
1253
+ stuff,
1254
+ branch,
1255
+ status,
1256
+ error,
1257
+ routeId: route.id
1258
+ });
1259
+ }
1260
+
1261
+ /**
1262
+ * @param {{
1263
+ * status: number;
1264
+ * error: Error;
1265
+ * url: URL;
1266
+ * routeId: string | null
1267
+ * }} opts
1268
+ */
1269
+ async function load_root_error_page({ status, error, url, routeId }) {
1270
+ /** @type {Record<string, string>} */
1271
+ const params = {}; // error page does not have params
1272
+
1273
+ const root_layout = await load_node({
1274
+ module: await default_layout,
1275
+ url,
1276
+ params,
1277
+ stuff: {},
1278
+ routeId
1279
+ });
1280
+
1281
+ const root_error = await load_node({
1282
+ status,
1283
+ error,
1284
+ module: await default_error,
1285
+ url,
1286
+ params,
1287
+ stuff: (root_layout && root_layout.loaded && root_layout.loaded.stuff) || {},
1288
+ routeId
1289
+ });
1290
+
1291
+ return await get_navigation_result_from_branch({
1292
+ url,
1293
+ params,
1294
+ stuff: {
1295
+ ...root_layout?.loaded?.stuff,
1296
+ ...root_error?.loaded?.stuff
1297
+ },
1298
+ branch: [root_layout, root_error],
1299
+ status,
1300
+ error,
1301
+ routeId
1302
+ });
1303
+ }
1304
+
1305
+ /** @param {URL} url */
1306
+ function get_navigation_intent(url) {
1307
+ if (url.origin !== location.origin || !url.pathname.startsWith(base)) return;
1308
+
1309
+ const path = decodeURI(url.pathname.slice(base.length) || '/');
1310
+
1311
+ for (const route of routes) {
1312
+ const params = route.exec(path);
1313
+
1314
+ if (params) {
1315
+ /** @type {import('./types').NavigationIntent} */
1316
+ const intent = {
1317
+ id: url.pathname + url.search,
1318
+ route,
1319
+ params,
1320
+ url
1321
+ };
1322
+
1323
+ return intent;
1324
+ }
1325
+ }
1326
+ }
1327
+
1328
+ /**
1329
+ * @param {{
1330
+ * url: URL;
1331
+ * scroll: { x: number, y: number } | null;
1332
+ * keepfocus: boolean;
1333
+ * redirect_chain: string[];
1334
+ * details: {
1335
+ * replaceState: boolean;
1336
+ * state: any;
1337
+ * } | null;
1338
+ * accepted: () => void;
1339
+ * blocked: () => void;
1340
+ * }} opts
1341
+ */
1342
+ async function navigate({ url, scroll, keepfocus, redirect_chain, details, accepted, blocked }) {
1343
+ const from = current.url;
1344
+ let should_block = false;
1345
+
1346
+ const navigation = {
1347
+ from,
1348
+ to: url,
1349
+ cancel: () => (should_block = true)
1350
+ };
1351
+
1352
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1353
+
1354
+ if (should_block) {
1355
+ blocked();
1356
+ return;
1357
+ }
1358
+
1359
+ const pathname = normalize_path(url.pathname, trailing_slash);
1360
+ const normalized = new URL(url.origin + pathname + url.search + url.hash);
1361
+
1362
+ update_scroll_positions(current_history_index);
1363
+
1364
+ accepted();
1365
+
1366
+ if (started) {
1367
+ stores.navigating.set({
1368
+ from: current.url,
1369
+ to: normalized
1370
+ });
1371
+ }
1372
+
1373
+ await update(
1374
+ normalized,
1375
+ redirect_chain,
1376
+ false,
1377
+ {
1378
+ scroll,
1379
+ keepfocus,
1380
+ details
1381
+ },
1382
+ () => {
1383
+ const navigation = { from, to: normalized };
1384
+ callbacks.after_navigate.forEach((fn) => fn(navigation));
1385
+
1386
+ stores.navigating.set(null);
1387
+ }
1388
+ );
1389
+ }
1390
+
1391
+ /**
1392
+ * Loads `href` the old-fashioned way, with a full page reload.
1393
+ * Returns a `Promise` that never resolves (to prevent any
1394
+ * subsequent work, e.g. history manipulation, from happening)
1395
+ * @param {URL} url
1396
+ */
1397
+ function native_navigation(url) {
1398
+ location.href = url.href;
1399
+ return new Promise(() => {});
1400
+ }
1401
+
1402
+ if (import.meta.hot) {
1403
+ import.meta.hot.on('vite:beforeUpdate', () => {
1404
+ if (current.error) location.reload();
1405
+ });
1406
+ }
1407
+
1408
+ return {
1409
+ after_navigate: (fn) => {
1410
+ onMount(() => {
1411
+ callbacks.after_navigate.push(fn);
1412
+
1413
+ return () => {
1414
+ const i = callbacks.after_navigate.indexOf(fn);
1415
+ callbacks.after_navigate.splice(i, 1);
1416
+ };
1417
+ });
1418
+ },
1419
+
1420
+ before_navigate: (fn) => {
1421
+ onMount(() => {
1422
+ callbacks.before_navigate.push(fn);
1423
+
1424
+ return () => {
1425
+ const i = callbacks.before_navigate.indexOf(fn);
1426
+ callbacks.before_navigate.splice(i, 1);
1427
+ };
1428
+ });
1429
+ },
1430
+
1431
+ disable_scroll_handling: () => {
1432
+ if (import.meta.env.DEV && started && !updating) {
1433
+ throw new Error('Can only disable scroll handling during navigation');
1434
+ }
1435
+
1436
+ if (updating || !started) {
1437
+ autoscroll = false;
1438
+ }
1439
+ },
1440
+
1441
+ goto: (href, opts = {}) => goto(href, opts, []),
1442
+
1443
+ invalidate: (resource) => {
1444
+ if (typeof resource === 'function') {
1445
+ invalidated.push(resource);
1446
+ } else {
1447
+ const { href } = new URL(resource, location.href);
1448
+ invalidated.push((dep) => dep === href);
1449
+ }
1450
+
1451
+ if (!invalidating) {
1452
+ invalidating = Promise.resolve().then(async () => {
1453
+ await update(new URL(location.href), [], true);
1454
+
1455
+ invalidating = null;
1456
+ });
1457
+ }
1458
+
1459
+ return invalidating;
1460
+ },
1461
+
1462
+ prefetch: async (href) => {
1463
+ const url = new URL(href, get_base_uri(document));
1464
+ await prefetch(url);
1465
+ },
1466
+
1467
+ // TODO rethink this API
1468
+ prefetch_routes: async (pathnames) => {
1469
+ const matching = pathnames
1470
+ ? routes.filter((route) => pathnames.some((pathname) => route.exec(pathname)))
1471
+ : routes;
1472
+
1473
+ const promises = matching.map((r) => Promise.all(r.a.map((load) => load())));
1474
+
1475
+ await Promise.all(promises);
1476
+ },
1477
+
1478
+ _start_router: () => {
1479
+ history.scrollRestoration = 'manual';
1480
+
1481
+ // Adopted from Nuxt.js
1482
+ // Reset scrollRestoration to auto when leaving page, allowing page reload
1483
+ // and back-navigation from other pages to use the browser to restore the
1484
+ // scrolling position.
1485
+ addEventListener('beforeunload', (e) => {
1486
+ let should_block = false;
1487
+
1488
+ const navigation = {
1489
+ from: current.url,
1490
+ to: null,
1491
+ cancel: () => (should_block = true)
1492
+ };
1493
+
1494
+ callbacks.before_navigate.forEach((fn) => fn(navigation));
1495
+
1496
+ if (should_block) {
1497
+ e.preventDefault();
1498
+ e.returnValue = '';
1499
+ } else {
1500
+ history.scrollRestoration = 'auto';
1501
+ }
1502
+ });
1503
+
1504
+ addEventListener('visibilitychange', () => {
1505
+ if (document.visibilityState === 'hidden') {
1506
+ update_scroll_positions(current_history_index);
1507
+
1508
+ try {
1509
+ sessionStorage[SCROLL_KEY] = JSON.stringify(scroll_positions);
1510
+ } catch {
1511
+ // do nothing
1512
+ }
1513
+ }
1514
+ });
1515
+
1516
+ /** @param {Event} event */
1517
+ const trigger_prefetch = (event) => {
1518
+ const a = find_anchor(event);
1519
+ if (a && a.href && a.hasAttribute('sveltekit:prefetch')) {
1520
+ prefetch(get_href(a));
1521
+ }
1522
+ };
1523
+
1524
+ /** @type {NodeJS.Timeout} */
1525
+ let mousemove_timeout;
1526
+
1527
+ /** @param {MouseEvent|TouchEvent} event */
1528
+ const handle_mousemove = (event) => {
1529
+ clearTimeout(mousemove_timeout);
1530
+ mousemove_timeout = setTimeout(() => {
1531
+ // event.composedPath(), which is used in find_anchor, will be empty if the event is read in a timeout
1532
+ // add a layer of indirection to address that
1533
+ event.target?.dispatchEvent(
1534
+ new CustomEvent('sveltekit:trigger_prefetch', { bubbles: true })
1535
+ );
1536
+ }, 20);
1537
+ };
1538
+
1539
+ addEventListener('touchstart', trigger_prefetch);
1540
+ addEventListener('mousemove', handle_mousemove);
1541
+ addEventListener('sveltekit:trigger_prefetch', trigger_prefetch);
1542
+
1543
+ /** @param {MouseEvent} event */
1544
+ addEventListener('click', (event) => {
1545
+ if (!router_enabled) return;
1546
+
1547
+ // Adapted from https://github.com/visionmedia/page.js
1548
+ // MIT license https://github.com/visionmedia/page.js#license
1549
+ if (event.button || event.which !== 1) return;
1550
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
1551
+ if (event.defaultPrevented) return;
1552
+
1553
+ const a = find_anchor(event);
1554
+ if (!a) return;
1555
+
1556
+ if (!a.href) return;
1557
+
1558
+ const is_svg_a_element = a instanceof SVGAElement;
1559
+ const url = get_href(a);
1560
+
1561
+ // Ignore if url does not have origin (e.g. `mailto:`, `tel:`.)
1562
+ // MEMO: Without this condition, firefox will open mailer twice.
1563
+ // See: https://github.com/sveltejs/kit/issues/4045
1564
+ if (!is_svg_a_element && url.origin === 'null') return;
1565
+
1566
+ // Ignore if tag has
1567
+ // 1. 'download' attribute
1568
+ // 2. 'rel' attribute includes external
1569
+ const rel = (a.getAttribute('rel') || '').split(/\s+/);
1570
+
1571
+ if (
1572
+ a.hasAttribute('download') ||
1573
+ rel.includes('external') ||
1574
+ a.hasAttribute('sveltekit:reload')
1575
+ ) {
1576
+ return;
1577
+ }
1578
+
1579
+ // Ignore if <a> has a target
1580
+ if (is_svg_a_element ? a.target.baseVal : a.target) return;
1581
+
1582
+ // Check if new url only differs by hash and use the browser default behavior in that case
1583
+ // This will ensure the `hashchange` event is fired
1584
+ // Removing the hash does a full page navigation in the browser, so make sure a hash is present
1585
+ const [base, hash] = url.href.split('#');
1586
+ if (hash !== undefined && base === location.href.split('#')[0]) {
1587
+ // set this flag to distinguish between navigations triggered by
1588
+ // clicking a hash link and those triggered by popstate
1589
+ hash_navigating = true;
1590
+
1591
+ update_scroll_positions(current_history_index);
1592
+
1593
+ stores.page.set({ ...page, url });
1594
+ stores.page.notify();
1595
+
1596
+ return;
1597
+ }
1598
+
1599
+ navigate({
1600
+ url,
1601
+ scroll: a.hasAttribute('sveltekit:noscroll') ? scroll_state() : null,
1602
+ keepfocus: false,
1603
+ redirect_chain: [],
1604
+ details: {
1605
+ state: {},
1606
+ replaceState: url.href === location.href
1607
+ },
1608
+ accepted: () => event.preventDefault(),
1609
+ blocked: () => event.preventDefault()
1610
+ });
1611
+ });
1612
+
1613
+ addEventListener('popstate', (event) => {
1614
+ if (event.state && router_enabled) {
1615
+ // if a popstate-driven navigation is cancelled, we need to counteract it
1616
+ // with history.go, which means we end up back here, hence this check
1617
+ if (event.state[INDEX_KEY] === current_history_index) return;
1618
+
1619
+ navigate({
1620
+ url: new URL(location.href),
1621
+ scroll: scroll_positions[event.state[INDEX_KEY]],
1622
+ keepfocus: false,
1623
+ redirect_chain: [],
1624
+ details: null,
1625
+ accepted: () => {
1626
+ current_history_index = event.state[INDEX_KEY];
1627
+ },
1628
+ blocked: () => {
1629
+ const delta = current_history_index - event.state[INDEX_KEY];
1630
+ history.go(delta);
1631
+ }
1632
+ });
1633
+ }
1634
+ });
1635
+
1636
+ addEventListener('hashchange', () => {
1637
+ // if the hashchange happened as a result of clicking on a link,
1638
+ // we need to update history, otherwise we have to leave it alone
1639
+ if (hash_navigating) {
1640
+ hash_navigating = false;
1641
+ history.replaceState(
1642
+ { ...history.state, [INDEX_KEY]: ++current_history_index },
1643
+ '',
1644
+ location.href
1645
+ );
1646
+ }
1647
+ });
1648
+ },
1649
+
1650
+ _hydrate: async ({ status, error, nodes, params, routeId }) => {
1651
+ const url = new URL(location.href);
1652
+
1653
+ /** @type {Array<import('./types').BranchNode | undefined>} */
1654
+ const branch = [];
1655
+
1656
+ /** @type {Record<string, any>} */
1657
+ let stuff = {};
1658
+
1659
+ /** @type {import('./types').NavigationResult | undefined} */
1660
+ let result;
1661
+
1662
+ let error_args;
1663
+
1664
+ try {
1665
+ for (let i = 0; i < nodes.length; i += 1) {
1666
+ const is_leaf = i === nodes.length - 1;
1667
+
1668
+ let props;
1669
+
1670
+ if (is_leaf) {
1671
+ const serialized = document.querySelector('script[sveltekit\\:data-type="props"]');
1672
+ if (serialized) {
1673
+ props = JSON.parse(/** @type {string} */ (serialized.textContent));
1674
+ }
1675
+ }
1676
+
1677
+ const node = await load_node({
1678
+ module: await components[nodes[i]](),
1679
+ url,
1680
+ params,
1681
+ stuff,
1682
+ status: is_leaf ? status : undefined,
1683
+ error: is_leaf ? error : undefined,
1684
+ props,
1685
+ routeId
1686
+ });
1687
+
1688
+ if (props) {
1689
+ node.uses.dependencies.add(url.href);
1690
+ node.uses.url = true;
1691
+ }
1692
+
1693
+ branch.push(node);
1694
+
1695
+ if (node && node.loaded) {
1696
+ if (node.loaded.error) {
1697
+ if (error) throw node.loaded.error;
1698
+ error_args = {
1699
+ status: node.loaded.status,
1700
+ error: node.loaded.error,
1701
+ url,
1702
+ routeId
1703
+ };
1704
+ } else if (node.loaded.stuff) {
1705
+ stuff = {
1706
+ ...stuff,
1707
+ ...node.loaded.stuff
1708
+ };
1709
+ }
1710
+ }
1711
+ }
1712
+
1713
+ result = error_args
1714
+ ? await load_root_error_page(error_args)
1715
+ : await get_navigation_result_from_branch({
1716
+ url,
1717
+ params,
1718
+ stuff,
1719
+ branch,
1720
+ status,
1721
+ error,
1722
+ routeId
1723
+ });
1724
+ } catch (e) {
1725
+ if (error) throw e;
1726
+
1727
+ result = await load_root_error_page({
1728
+ status: 500,
1729
+ error: coalesce_to_error(e),
1730
+ url,
1731
+ routeId
1732
+ });
1733
+ }
1734
+
1735
+ if (result.redirect) {
1736
+ // this is a real edge case — `load` would need to return
1737
+ // a redirect but only in the browser
1738
+ await native_navigation(new URL(result.redirect, location.href));
1739
+ }
1740
+
1741
+ initialize(result);
1742
+ }
1743
+ };
1744
+ }
1745
+
1746
+ /**
1747
+ * @param {{
1748
+ * paths: {
1749
+ * assets: string;
1750
+ * base: string;
1751
+ * },
1752
+ * target: Element;
1753
+ * session: any;
1754
+ * route: boolean;
1755
+ * spa: boolean;
1756
+ * trailing_slash: import('types').TrailingSlash;
1757
+ * hydrate: {
1758
+ * status: number;
1759
+ * error: Error;
1760
+ * nodes: number[];
1761
+ * params: Record<string, string>;
1762
+ * routeId: string | null;
1763
+ * };
1764
+ * }} opts
1765
+ */
1766
+ async function start({ paths, target, session, route, spa, trailing_slash, hydrate }) {
1767
+ const client = create_client({
1768
+ target,
1769
+ session,
1770
+ base: paths.base,
1771
+ trailing_slash
1772
+ });
1773
+
1774
+ init({ client });
1775
+ set_paths(paths);
1776
+
1777
+ if (hydrate) {
1778
+ await client._hydrate(hydrate);
1779
+ }
1780
+
1781
+ if (route) {
1782
+ if (spa) client.goto(location.href, { replaceState: true });
1783
+ client._start_router();
1784
+ }
1785
+
1786
+ dispatchEvent(new CustomEvent('sveltekit:start'));
1787
+ }
1788
+
1789
+ export { start };