@sveltejs/kit 1.0.0-next.35 → 1.0.0-next.352

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