@sveltejs/kit 1.0.0-next.32 → 1.0.0-next.320

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