@sveltejs/kit 1.0.0-next.28 → 1.0.0-next.280

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