Skip to content

Commit 948c980

Browse files
authored
don't warn about window.fetch during hydration (#5041)
* failing test for #5031 * move fetch logic into separate module - fixes #5031 * changeset * remove .only
1 parent d5cf5e0 commit 948c980

File tree

7 files changed

+105
-64
lines changed

7 files changed

+105
-64
lines changed

.changeset/young-scissors-collect.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/kit': patch
3+
---
4+
5+
don't warn about window.fetch during hydration

packages/kit/src/runtime/client/client.js

+5-32
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import {
88
find_anchor,
99
get_base_uri,
1010
get_href,
11-
initial_fetch,
1211
notifiable_store,
1312
scroll_state
1413
} from './utils.js';
14+
import * as fetcher from './fetcher.js';
1515
import { parse } from './parse.js';
1616

1717
import Root from '__GENERATED__/root.svelte';
@@ -48,33 +48,6 @@ function update_scroll_positions(index) {
4848
scroll_positions[index] = scroll_state();
4949
}
5050

51-
const fetch = window.fetch;
52-
let loading = 0;
53-
54-
if (import.meta.env.DEV) {
55-
let can_inspect_stack_trace = false;
56-
57-
const check_stack_trace = async () => {
58-
const stack = /** @type {string} */ (new Error().stack);
59-
can_inspect_stack_trace = stack.includes('check_stack_trace');
60-
};
61-
62-
check_stack_trace();
63-
64-
window.fetch = (input, init) => {
65-
const url = input instanceof Request ? input.url : input.toString();
66-
const stack = /** @type {string} */ (new Error().stack);
67-
68-
const heuristic = can_inspect_stack_trace ? stack.includes('load_node') : loading;
69-
if (heuristic) {
70-
console.warn(
71-
`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`
72-
);
73-
}
74-
return fetch(input, init);
75-
};
76-
}
77-
7851
/**
7952
* @param {{
8053
* target: Element;
@@ -621,7 +594,7 @@ export function create_client({ target, session, base, trailing_slash }) {
621594
add_dependency(normalized);
622595

623596
// prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be normalized
624-
return started ? fetch(normalized, init) : initial_fetch(requested, init);
597+
return started ? fetcher.native(normalized, init) : fetcher.initial(requested, init);
625598
},
626599
status: status ?? null,
627600
error: error ?? null
@@ -640,10 +613,10 @@ export function create_client({ target, session, base, trailing_slash }) {
640613

641614
if (import.meta.env.DEV) {
642615
try {
643-
loading += 1;
616+
fetcher.increment();
644617
loaded = await module.load.call(null, load_input);
645618
} finally {
646-
loading -= 1;
619+
fetcher.decrement();
647620
}
648621
} else {
649622
loaded = await module.load.call(null, load_input);
@@ -731,7 +704,7 @@ export function create_client({ target, session, base, trailing_slash }) {
731704
const is_shadow_page = has_shadow && i === a.length - 1;
732705

733706
if (is_shadow_page) {
734-
const res = await fetch(
707+
const res = await fetcher.native(
735708
`${url.pathname}${url.pathname.endsWith('/') ? '' : '/'}__data.json${url.search}`,
736709
{
737710
headers: {
+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import { hash } from '../hash.js';
2+
3+
let loading = 0;
4+
5+
export const native = window.fetch;
6+
7+
export function increment() {
8+
loading += 1;
9+
}
10+
11+
export function decrement() {
12+
loading -= 1;
13+
}
14+
15+
if (import.meta.env.DEV) {
16+
let can_inspect_stack_trace = false;
17+
18+
const check_stack_trace = async () => {
19+
const stack = /** @type {string} */ (new Error().stack);
20+
can_inspect_stack_trace = stack.includes('check_stack_trace');
21+
};
22+
23+
check_stack_trace();
24+
25+
window.fetch = (input, init) => {
26+
const url = input instanceof Request ? input.url : input.toString();
27+
const stack = /** @type {string} */ (new Error().stack);
28+
29+
const heuristic = can_inspect_stack_trace ? stack.includes('load_node') : loading;
30+
if (heuristic) {
31+
console.warn(
32+
`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`
33+
);
34+
}
35+
return native(input, init);
36+
};
37+
}
38+
39+
/**
40+
* @param {RequestInfo} resource
41+
* @param {RequestInit} [opts]
42+
*/
43+
export function initial(resource, opts) {
44+
const url = JSON.stringify(typeof resource === 'string' ? resource : resource.url);
45+
46+
let selector = `script[sveltekit\\:data-type="data"][sveltekit\\:data-url=${url}]`;
47+
48+
if (opts && typeof opts.body === 'string') {
49+
selector += `[sveltekit\\:data-body="${hash(opts.body)}"]`;
50+
}
51+
52+
const script = document.querySelector(selector);
53+
if (script && script.textContent) {
54+
const { body, ...init } = JSON.parse(script.textContent);
55+
return Promise.resolve(new Response(body, init));
56+
}
57+
58+
return native(resource, opts);
59+
}

packages/kit/src/runtime/client/utils.js

-23
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { writable } from 'svelte/store';
2-
import { hash } from '../hash.js';
32
import { assets } from '../paths.js';
43

54
/** @param {HTMLDocument} doc */
@@ -115,25 +114,3 @@ export function create_updated_store() {
115114
check
116115
};
117116
}
118-
119-
/**
120-
* @param {RequestInfo} resource
121-
* @param {RequestInit} [opts]
122-
*/
123-
export function initial_fetch(resource, opts) {
124-
const url = JSON.stringify(typeof resource === 'string' ? resource : resource.url);
125-
126-
let selector = `script[sveltekit\\:data-type="data"][sveltekit\\:data-url=${url}]`;
127-
128-
if (opts && typeof opts.body === 'string') {
129-
selector += `[sveltekit\\:data-body="${hash(opts.body)}"]`;
130-
}
131-
132-
const script = document.querySelector(selector);
133-
if (script && script.textContent) {
134-
const { body, ...init } = JSON.parse(script.textContent);
135-
return Promise.resolve(new Response(body, init));
136-
}
137-
138-
return fetch(resource, opts);
139-
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<script context="module">
2+
/** @type {import('./index').Load} */
3+
export async function load({ url, fetch }) {
4+
const res = await fetch(`${url.origin}/load/window-fetch/data.json`);
5+
const { answer } = await res.json();
6+
7+
return {
8+
props: { answer }
9+
};
10+
}
11+
</script>
12+
13+
<script>
14+
/** @type {number} */
15+
export let answer;
16+
</script>
17+
18+
<h1>{answer}</h1>

packages/kit/test/apps/basics/test/test.js

+18-9
Original file line numberDiff line numberDiff line change
@@ -1506,21 +1506,30 @@ test.describe.parallel('Load', () => {
15061506
});
15071507

15081508
test('using window.fetch causes a warning', async ({ page, javaScriptEnabled }) => {
1509-
const warnings = [];
1509+
if (javaScriptEnabled && process.env.DEV) {
1510+
const warnings = [];
15101511

1511-
page.on('console', (msg) => {
1512-
if (msg.type() === 'warning') {
1513-
warnings.push(msg.text());
1514-
}
1515-
});
1512+
page.on('console', (msg) => {
1513+
if (msg.type() === 'warning') {
1514+
warnings.push(msg.text());
1515+
}
1516+
});
15161517

1517-
await page.goto('/load/window-fetch');
1518-
expect(await page.textContent('h1')).toBe('42');
1518+
await page.goto('/load/window-fetch/incorrect');
1519+
expect(await page.textContent('h1')).toBe('42');
15191520

1520-
if (javaScriptEnabled && process.env.DEV) {
15211521
expect(warnings).toContain(
15221522
'Loading http://localhost:3000/load/window-fetch/data.json using `window.fetch`. For best results, use the `fetch` that is passed to your `load` function: https://kit.svelte.dev/docs/loading#input-fetch'
15231523
);
1524+
1525+
warnings.length = 0;
1526+
1527+
await page.goto('/load/window-fetch/correct');
1528+
expect(await page.textContent('h1')).toBe('42');
1529+
1530+
expect(warnings).not.toContain(
1531+
'Loading http://localhost:3000/load/window-fetch/data.json using `window.fetch`. For best results, use the `fetch` that is passed to your `load` function: https://kit.svelte.dev/docs/loading#input-fetch'
1532+
);
15241533
}
15251534
});
15261535
});

0 commit comments

Comments
 (0)