@sveltejs/kit 1.0.0-next.37 → 1.0.0-next.372

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