@ecopages/browser-router 0.2.0-beta.30 → 0.2.0-beta.32

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.
@@ -1,371 +1,397 @@
1
- import { assertHtmlPageResponse, shouldPrefetchLink } from "@ecopages/core/router/link-navigation-policy";
2
- import { discoverNewStylesheetLinks, getCurrentStylesheetHrefs } from "../dom/stylesheet-discovery.js";
1
+ /**
2
+ * Prefetch manager for client-side navigation.
3
+ * Uses a single IntersectionObserver and hover detection for optimal performance.
4
+ * @module prefetch-manager
5
+ */
6
+ import { assertHtmlPageResponse, shouldPrefetchLink } from '@ecopages/core/router/link-navigation-policy';
7
+ import { discoverNewStylesheetLinks, getCurrentStylesheetHrefs } from '../dom/stylesheet-discovery.js';
3
8
  const DEFAULT_PREFETCH_OPTIONS = {
4
- strategy: "intent",
5
- delay: 65,
6
- noPrefetchAttribute: "data-eco-no-prefetch",
7
- respectDataSaver: true,
8
- linkSelector: "a[href]"
9
+ strategy: 'intent',
10
+ delay: 65,
11
+ noPrefetchAttribute: 'data-eco-no-prefetch',
12
+ respectDataSaver: true,
13
+ linkSelector: 'a[href]',
9
14
  };
10
- class PrefetchManager {
11
- options;
12
- prefetched = /* @__PURE__ */ new Set();
13
- prefetchedStylesheets = /* @__PURE__ */ new Set();
14
- htmlCache = /* @__PURE__ */ new Map();
15
- observer = null;
16
- hoverTimeouts = /* @__PURE__ */ new Map();
17
- constructor(options) {
18
- this.options = { ...DEFAULT_PREFETCH_OPTIONS, ...options };
19
- }
20
- /**
21
- * Initializes prefetching based on the configured strategy.
22
- *
23
- * Sets up IntersectionObserver for viewport-based prefetching and/or
24
- * hover/focus listeners for intent-based prefetching. Immediately begins
25
- * observing existing links on the page.
26
- */
27
- start() {
28
- if (!this.shouldPrefetch()) return;
29
- if (this.options.strategy === "viewport" || this.options.strategy === "intent") {
30
- this.setupIntersectionObserver();
15
+ export class PrefetchManager {
16
+ options;
17
+ prefetched = new Set();
18
+ prefetchedStylesheets = new Set();
19
+ htmlCache = new Map();
20
+ observer = null;
21
+ hoverTimeouts = new Map();
22
+ constructor(options) {
23
+ this.options = { ...DEFAULT_PREFETCH_OPTIONS, ...options };
31
24
  }
32
- if (this.options.strategy === "hover" || this.options.strategy === "intent") {
33
- this.setupHoverListeners();
25
+ /**
26
+ * Initializes prefetching based on the configured strategy.
27
+ *
28
+ * Sets up IntersectionObserver for viewport-based prefetching and/or
29
+ * hover/focus listeners for intent-based prefetching. Immediately begins
30
+ * observing existing links on the page.
31
+ */
32
+ start() {
33
+ if (!this.shouldPrefetch())
34
+ return;
35
+ if (this.options.strategy === 'viewport' || this.options.strategy === 'intent') {
36
+ this.setupIntersectionObserver();
37
+ }
38
+ if (this.options.strategy === 'hover' || this.options.strategy === 'intent') {
39
+ this.setupHoverListeners();
40
+ }
41
+ this.observeLinks();
34
42
  }
35
- this.observeLinks();
36
- }
37
- /**
38
- * Cleans up all prefetch-related observers and event listeners.
39
- * Cancels any pending hover timeouts.
40
- */
41
- stop() {
42
- this.observer?.disconnect();
43
- this.observer = null;
44
- document.removeEventListener("mouseover", this.handleMouseOver);
45
- document.removeEventListener("mouseout", this.handleMouseOut);
46
- document.removeEventListener("focusin", this.handleFocusIn);
47
- document.removeEventListener("focusout", this.handleFocusOut);
48
- this.hoverTimeouts.forEach((timeout) => clearTimeout(timeout));
49
- this.hoverTimeouts.clear();
50
- }
51
- /**
52
- * Fetches and caches HTML content for a given URL.
53
- *
54
- * Skips cross-origin URLs or already-prefetched URLs. On success, both the
55
- * HTML content is cached and any new stylesheets are preloaded to prevent
56
- * FOUC during navigation.
57
- *
58
- * @param href - The URL to prefetch
59
- */
60
- async prefetch(href) {
61
- const url = new URL(href, window.location.origin);
62
- if (url.origin !== window.location.origin) return;
63
- if (this.prefetched.has(url.href)) return;
64
- const currentPath = window.location.pathname + window.location.search;
65
- const targetPath = url.pathname + url.search;
66
- if (currentPath === targetPath) return;
67
- this.prefetched.add(url.href);
68
- try {
69
- const response = await fetch(url.href, {
70
- headers: { Accept: "text/html" },
71
- priority: "low"
72
- });
73
- if (!response.ok) {
74
- this.prefetched.delete(url.href);
75
- return;
76
- }
77
- await assertHtmlPageResponse(response);
78
- const html = await response.text();
79
- this.htmlCache.set(url.href, html);
80
- await this.prefetchStylesheets(html, url);
81
- } catch {
82
- this.prefetched.delete(url.href);
43
+ /**
44
+ * Cleans up all prefetch-related observers and event listeners.
45
+ * Cancels any pending hover timeouts.
46
+ */
47
+ stop() {
48
+ this.observer?.disconnect();
49
+ this.observer = null;
50
+ document.removeEventListener('mouseover', this.handleMouseOver);
51
+ document.removeEventListener('mouseout', this.handleMouseOut);
52
+ document.removeEventListener('focusin', this.handleFocusIn);
53
+ document.removeEventListener('focusout', this.handleFocusOut);
54
+ this.hoverTimeouts.forEach((timeout) => clearTimeout(timeout));
55
+ this.hoverTimeouts.clear();
83
56
  }
84
- }
85
- /**
86
- * Retrieves cached HTML for a URL.
87
- *
88
- * Returns cached content without consuming it, enabling stale-while-revalidate:
89
- * - Returns cached HTML immediately for instant navigation
90
- * - Use cacheVisitedPage() after navigation to update cache in background
91
- *
92
- * @param href - The URL to look up
93
- * @returns The cached HTML string, or null if not cached
94
- */
95
- getCachedHtml(href) {
96
- const url = new URL(href, window.location.origin);
97
- return this.htmlCache.get(url.href) ?? null;
98
- }
99
- invalidate(href) {
100
- const url = new URL(href, window.location.origin);
101
- this.htmlCache.delete(url.href);
102
- this.prefetched.delete(url.href);
103
- }
104
- /**
105
- * Caches HTML content for a visited page and triggers background revalidation.
106
- *
107
- * Implements stale-while-revalidate pattern:
108
- * - Immediately caches the provided HTML for instant revisits
109
- * - Fetches fresh content in background for next visit (unless it's the current page)
110
- *
111
- * @param href - The URL of the visited page
112
- * @param html - The HTML content to cache initially
113
- */
114
- cacheVisitedPage(href, html) {
115
- const url = new URL(href, window.location.origin);
116
- if (url.origin !== window.location.origin) return;
117
- this.htmlCache.set(url.href, html);
118
- this.prefetched.add(url.href);
119
- const currentPath = window.location.pathname + window.location.search;
120
- const targetPath = url.pathname + url.search;
121
- if (currentPath === targetPath) return;
122
- setTimeout(() => {
123
- fetch(url.href, {
124
- headers: { Accept: "text/html" },
125
- priority: "low"
126
- }).then(async (response) => {
127
- if (!response.ok) {
128
- return null;
129
- }
57
+ /**
58
+ * Fetches and caches HTML content for a given URL.
59
+ *
60
+ * Skips cross-origin URLs or already-prefetched URLs. On success, both the
61
+ * HTML content is cached and any new stylesheets are preloaded to prevent
62
+ * FOUC during navigation.
63
+ *
64
+ * @param href - The URL to prefetch
65
+ */
66
+ async prefetch(href) {
67
+ const url = new URL(href, window.location.origin);
68
+ if (url.origin !== window.location.origin)
69
+ return;
70
+ if (this.prefetched.has(url.href))
71
+ return;
72
+ const currentPath = window.location.pathname + window.location.search;
73
+ const targetPath = url.pathname + url.search;
74
+ if (currentPath === targetPath)
75
+ return;
76
+ this.prefetched.add(url.href);
130
77
  try {
131
- await assertHtmlPageResponse(response);
132
- } catch {
133
- return null;
78
+ const response = await fetch(url.href, {
79
+ headers: { Accept: 'text/html' },
80
+ priority: 'low',
81
+ });
82
+ if (!response.ok) {
83
+ this.prefetched.delete(url.href);
84
+ return;
85
+ }
86
+ await assertHtmlPageResponse(response);
87
+ const html = await response.text();
88
+ this.htmlCache.set(url.href, html);
89
+ await this.prefetchStylesheets(html, url);
134
90
  }
135
- return response.text();
136
- }).then((freshHtml) => {
137
- if (freshHtml) {
138
- this.htmlCache.set(url.href, freshHtml);
91
+ catch {
92
+ this.prefetched.delete(url.href);
139
93
  }
140
- }).catch(() => {
141
- });
142
- }, 100);
143
- }
144
- /**
145
- * Checks if a URL has already been prefetched.
146
- * @param href - The URL to check
147
- */
148
- isPrefetched(href) {
149
- const url = new URL(href, window.location.origin);
150
- return this.prefetched.has(url.href);
151
- }
152
- /**
153
- * Determines if prefetching should be enabled based on network conditions.
154
- *
155
- * Respects the user's data saver settings and avoids prefetching on slow
156
- * connections (2g or slower) when `respectDataSaver` is enabled.
157
- */
158
- shouldPrefetch() {
159
- if (!this.options.respectDataSaver) return true;
160
- const conn = navigator.connection;
161
- if (!conn) return true;
162
- if (conn.saveData) return false;
163
- if (conn.effectiveType === "2g" || conn.effectiveType === "slow-2g") return false;
164
- return true;
165
- }
166
- /**
167
- * Creates an IntersectionObserver to prefetch links as they enter the viewport.
168
- *
169
- * Uses a 50px root margin to trigger prefetching slightly before elements
170
- * become visible, improving perceived performance.
171
- */
172
- setupIntersectionObserver() {
173
- this.observer = new IntersectionObserver(
174
- (entries) => {
175
- for (const entry of entries) {
176
- if (entry.isIntersecting) {
177
- const link = entry.target;
178
- const strategy = this.getLinkStrategy(link);
179
- if (strategy === "viewport" || strategy === "eager") {
180
- this.scheduleIdlePrefetch(link.href, strategy === "eager");
94
+ }
95
+ /**
96
+ * Retrieves cached HTML for a URL.
97
+ *
98
+ * Returns cached content without consuming it, enabling stale-while-revalidate:
99
+ * - Returns cached HTML immediately for instant navigation
100
+ * - Use cacheVisitedPage() after navigation to update cache in background
101
+ *
102
+ * @param href - The URL to look up
103
+ * @returns The cached HTML string, or null if not cached
104
+ */
105
+ getCachedHtml(href) {
106
+ const url = new URL(href, window.location.origin);
107
+ return this.htmlCache.get(url.href) ?? null;
108
+ }
109
+ invalidate(href) {
110
+ const url = new URL(href, window.location.origin);
111
+ this.htmlCache.delete(url.href);
112
+ this.prefetched.delete(url.href);
113
+ }
114
+ /**
115
+ * Caches HTML content for a visited page and triggers background revalidation.
116
+ *
117
+ * Implements stale-while-revalidate pattern:
118
+ * - Immediately caches the provided HTML for instant revisits
119
+ * - Fetches fresh content in background for next visit (unless it's the current page)
120
+ *
121
+ * @param href - The URL of the visited page
122
+ * @param html - The HTML content to cache initially
123
+ */
124
+ cacheVisitedPage(href, html) {
125
+ const url = new URL(href, window.location.origin);
126
+ if (url.origin !== window.location.origin)
127
+ return;
128
+ this.htmlCache.set(url.href, html);
129
+ this.prefetched.add(url.href);
130
+ const currentPath = window.location.pathname + window.location.search;
131
+ const targetPath = url.pathname + url.search;
132
+ if (currentPath === targetPath)
133
+ return;
134
+ setTimeout(() => {
135
+ fetch(url.href, {
136
+ headers: { Accept: 'text/html' },
137
+ priority: 'low',
138
+ })
139
+ .then(async (response) => {
140
+ if (!response.ok) {
141
+ return null;
142
+ }
143
+ try {
144
+ await assertHtmlPageResponse(response);
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ return response.text();
150
+ })
151
+ .then((freshHtml) => {
152
+ if (freshHtml) {
153
+ this.htmlCache.set(url.href, freshHtml);
154
+ }
155
+ })
156
+ .catch(() => { });
157
+ }, 100);
158
+ }
159
+ /**
160
+ * Checks if a URL has already been prefetched.
161
+ * @param href - The URL to check
162
+ */
163
+ isPrefetched(href) {
164
+ const url = new URL(href, window.location.origin);
165
+ return this.prefetched.has(url.href);
166
+ }
167
+ /**
168
+ * Determines if prefetching should be enabled based on network conditions.
169
+ *
170
+ * Respects the user's data saver settings and avoids prefetching on slow
171
+ * connections (2g or slower) when `respectDataSaver` is enabled.
172
+ */
173
+ shouldPrefetch() {
174
+ if (!this.options.respectDataSaver)
175
+ return true;
176
+ const conn = navigator.connection;
177
+ if (!conn)
178
+ return true;
179
+ if (conn.saveData)
180
+ return false;
181
+ if (conn.effectiveType === '2g' || conn.effectiveType === 'slow-2g')
182
+ return false;
183
+ return true;
184
+ }
185
+ /**
186
+ * Creates an IntersectionObserver to prefetch links as they enter the viewport.
187
+ *
188
+ * Uses a 50px root margin to trigger prefetching slightly before elements
189
+ * become visible, improving perceived performance.
190
+ */
191
+ setupIntersectionObserver() {
192
+ this.observer = new IntersectionObserver((entries) => {
193
+ for (const entry of entries) {
194
+ if (entry.isIntersecting) {
195
+ const link = entry.target;
196
+ const strategy = this.getLinkStrategy(link);
197
+ if (strategy === 'viewport' || strategy === 'eager') {
198
+ this.scheduleIdlePrefetch(link.href, strategy === 'eager');
199
+ }
200
+ }
181
201
  }
182
- }
183
- }
184
- },
185
- { rootMargin: "50px", threshold: 0 }
186
- );
187
- }
188
- /**
189
- * Attaches delegated event listeners for hover and focus-based prefetching.
190
- *
191
- * Uses event delegation on the document for efficient handling without
192
- * attaching listeners to individual links.
193
- */
194
- setupHoverListeners() {
195
- document.addEventListener("mouseover", this.handleMouseOver);
196
- document.addEventListener("mouseout", this.handleMouseOut);
197
- document.addEventListener("focusin", this.handleFocusIn);
198
- document.addEventListener("focusout", this.handleFocusOut);
199
- }
200
- handleMouseOver = (event) => {
201
- const link = this.getLinkFromEvent(event);
202
- if (!link) return;
203
- const strategy = this.getLinkStrategy(link);
204
- if (strategy === "hover" || strategy === "intent" || strategy === "eager") {
205
- const delay = strategy === "eager" ? 0 : this.getLinkDelay(link);
206
- this.scheduleHoverPrefetch(link.href, delay);
202
+ }, { rootMargin: '50px', threshold: 0 });
207
203
  }
208
- };
209
- handleMouseOut = (event) => {
210
- const link = this.getLinkFromEvent(event);
211
- if (!link) return;
212
- this.cancelHoverPrefetch(link.href);
213
- };
214
- handleFocusIn = (event) => {
215
- const link = this.getLinkFromEvent(event);
216
- if (!link) return;
217
- const strategy = this.getLinkStrategy(link);
218
- if (strategy === "hover" || strategy === "intent" || strategy === "eager") {
219
- const delay = strategy === "eager" ? 0 : this.getLinkDelay(link);
220
- this.scheduleHoverPrefetch(link.href, delay);
204
+ /**
205
+ * Attaches delegated event listeners for hover and focus-based prefetching.
206
+ *
207
+ * Uses event delegation on the document for efficient handling without
208
+ * attaching listeners to individual links.
209
+ */
210
+ setupHoverListeners() {
211
+ document.addEventListener('mouseover', this.handleMouseOver);
212
+ document.addEventListener('mouseout', this.handleMouseOut);
213
+ document.addEventListener('focusin', this.handleFocusIn);
214
+ document.addEventListener('focusout', this.handleFocusOut);
215
+ }
216
+ handleMouseOver = (event) => {
217
+ const link = this.getLinkFromEvent(event);
218
+ if (!link)
219
+ return;
220
+ const strategy = this.getLinkStrategy(link);
221
+ if (strategy === 'hover' || strategy === 'intent' || strategy === 'eager') {
222
+ const delay = strategy === 'eager' ? 0 : this.getLinkDelay(link);
223
+ this.scheduleHoverPrefetch(link.href, delay);
224
+ }
225
+ };
226
+ handleMouseOut = (event) => {
227
+ const link = this.getLinkFromEvent(event);
228
+ if (!link)
229
+ return;
230
+ this.cancelHoverPrefetch(link.href);
231
+ };
232
+ handleFocusIn = (event) => {
233
+ const link = this.getLinkFromEvent(event);
234
+ if (!link)
235
+ return;
236
+ const strategy = this.getLinkStrategy(link);
237
+ if (strategy === 'hover' || strategy === 'intent' || strategy === 'eager') {
238
+ const delay = strategy === 'eager' ? 0 : this.getLinkDelay(link);
239
+ this.scheduleHoverPrefetch(link.href, delay);
240
+ }
241
+ };
242
+ handleFocusOut = (event) => {
243
+ const link = this.getLinkFromEvent(event);
244
+ if (!link)
245
+ return;
246
+ this.cancelHoverPrefetch(link.href);
247
+ };
248
+ /**
249
+ * Extracts a valid anchor element from a DOM event.
250
+ *
251
+ * Returns null for links that should not be prefetched (opt-outs, downloads,
252
+ * hash links, javascript: URLs).
253
+ */
254
+ getLinkFromEvent(event) {
255
+ const target = event.target;
256
+ const link = target.closest(this.options.linkSelector);
257
+ if (!link)
258
+ return null;
259
+ if (!shouldPrefetchLink(link, { noPrefetchAttribute: this.options.noPrefetchAttribute })) {
260
+ return null;
261
+ }
262
+ return link;
221
263
  }
222
- };
223
- handleFocusOut = (event) => {
224
- const link = this.getLinkFromEvent(event);
225
- if (!link) return;
226
- this.cancelHoverPrefetch(link.href);
227
- };
228
- /**
229
- * Extracts a valid anchor element from a DOM event.
230
- *
231
- * Returns null for links that should not be prefetched (opt-outs, downloads,
232
- * hash links, javascript: URLs).
233
- */
234
- getLinkFromEvent(event) {
235
- const target = event.target;
236
- const link = target.closest(this.options.linkSelector);
237
- if (!link) return null;
238
- if (!shouldPrefetchLink(link, { noPrefetchAttribute: this.options.noPrefetchAttribute })) {
239
- return null;
264
+ /**
265
+ * Resolves the prefetch strategy for a link element.
266
+ *
267
+ * Checks for per-link overrides via `data-eco-prefetch` attribute,
268
+ * falling back to the global strategy.
269
+ */
270
+ getLinkStrategy(link) {
271
+ const override = link.getAttribute('data-eco-prefetch');
272
+ if (override === 'eager' || override === 'viewport' || override === 'hover' || override === 'intent') {
273
+ return override;
274
+ }
275
+ return this.options.strategy;
240
276
  }
241
- return link;
242
- }
243
- /**
244
- * Resolves the prefetch strategy for a link element.
245
- *
246
- * Checks for per-link overrides via `data-eco-prefetch` attribute,
247
- * falling back to the global strategy.
248
- */
249
- getLinkStrategy(link) {
250
- const override = link.getAttribute("data-eco-prefetch");
251
- if (override === "eager" || override === "viewport" || override === "hover" || override === "intent") {
252
- return override;
277
+ /**
278
+ * Resolves the prefetch delay for a link element.
279
+ *
280
+ * Checks for per-link overrides via `data-eco-prefetch-delay` attribute,
281
+ * falling back to the global delay.
282
+ */
283
+ getLinkDelay(link) {
284
+ const delayAttr = link.getAttribute('data-eco-prefetch-delay');
285
+ if (delayAttr) {
286
+ const delay = parseInt(delayAttr, 10);
287
+ if (!isNaN(delay) && delay >= 0)
288
+ return delay;
289
+ }
290
+ return this.options.delay;
253
291
  }
254
- return this.options.strategy;
255
- }
256
- /**
257
- * Resolves the prefetch delay for a link element.
258
- *
259
- * Checks for per-link overrides via `data-eco-prefetch-delay` attribute,
260
- * falling back to the global delay.
261
- */
262
- getLinkDelay(link) {
263
- const delayAttr = link.getAttribute("data-eco-prefetch-delay");
264
- if (delayAttr) {
265
- const delay = parseInt(delayAttr, 10);
266
- if (!isNaN(delay) && delay >= 0) return delay;
292
+ /**
293
+ * Schedules a prefetch request during browser idle time.
294
+ *
295
+ * Uses `requestIdleCallback` when available for non-blocking execution.
296
+ * Eager prefetches execute immediately.
297
+ *
298
+ * @param href - The URL to prefetch
299
+ * @param eager - If true, prefetch immediately without waiting for idle
300
+ */
301
+ scheduleIdlePrefetch(href, eager = false) {
302
+ if (this.prefetched.has(href))
303
+ return;
304
+ const prefetch = () => this.prefetch(href);
305
+ if (eager) {
306
+ prefetch();
307
+ return;
308
+ }
309
+ if ('requestIdleCallback' in window) {
310
+ requestIdleCallback(prefetch, { timeout: 2000 });
311
+ }
312
+ else {
313
+ setTimeout(prefetch, 0);
314
+ }
267
315
  }
268
- return this.options.delay;
269
- }
270
- /**
271
- * Schedules a prefetch request during browser idle time.
272
- *
273
- * Uses `requestIdleCallback` when available for non-blocking execution.
274
- * Eager prefetches execute immediately.
275
- *
276
- * @param href - The URL to prefetch
277
- * @param eager - If true, prefetch immediately without waiting for idle
278
- */
279
- scheduleIdlePrefetch(href, eager = false) {
280
- if (this.prefetched.has(href)) return;
281
- const prefetch = () => this.prefetch(href);
282
- if (eager) {
283
- prefetch();
284
- return;
316
+ /**
317
+ * Schedules a prefetch after a hover delay.
318
+ *
319
+ * The delay prevents prefetching when users briefly pass over links
320
+ * without intent to navigate.
321
+ *
322
+ * @param href - The URL to prefetch
323
+ * @param delay - Milliseconds to wait before prefetching
324
+ */
325
+ scheduleHoverPrefetch(href, delay = this.options.delay) {
326
+ if (this.prefetched.has(href))
327
+ return;
328
+ if (this.hoverTimeouts.has(href))
329
+ return;
330
+ const timeout = setTimeout(() => {
331
+ this.hoverTimeouts.delete(href);
332
+ this.prefetch(href);
333
+ }, delay);
334
+ this.hoverTimeouts.set(href, timeout);
285
335
  }
286
- if ("requestIdleCallback" in window) {
287
- requestIdleCallback(prefetch, { timeout: 2e3 });
288
- } else {
289
- setTimeout(prefetch, 0);
336
+ /**
337
+ * Cancels a pending hover-initiated prefetch.
338
+ * @param href - The URL whose prefetch should be cancelled
339
+ */
340
+ cancelHoverPrefetch(href) {
341
+ const timeout = this.hoverTimeouts.get(href);
342
+ if (timeout) {
343
+ clearTimeout(timeout);
344
+ this.hoverTimeouts.delete(href);
345
+ }
290
346
  }
291
- }
292
- /**
293
- * Schedules a prefetch after a hover delay.
294
- *
295
- * The delay prevents prefetching when users briefly pass over links
296
- * without intent to navigate.
297
- *
298
- * @param href - The URL to prefetch
299
- * @param delay - Milliseconds to wait before prefetching
300
- */
301
- scheduleHoverPrefetch(href, delay = this.options.delay) {
302
- if (this.prefetched.has(href)) return;
303
- if (this.hoverTimeouts.has(href)) return;
304
- const timeout = setTimeout(() => {
305
- this.hoverTimeouts.delete(href);
306
- this.prefetch(href);
307
- }, delay);
308
- this.hoverTimeouts.set(href, timeout);
309
- }
310
- /**
311
- * Cancels a pending hover-initiated prefetch.
312
- * @param href - The URL whose prefetch should be cancelled
313
- */
314
- cancelHoverPrefetch(href) {
315
- const timeout = this.hoverTimeouts.get(href);
316
- if (timeout) {
317
- clearTimeout(timeout);
318
- this.hoverTimeouts.delete(href);
347
+ /**
348
+ * Observes links for prefetching within `root`.
349
+ */
350
+ observeLinks(root = document) {
351
+ const links = root.querySelectorAll(this.options.linkSelector);
352
+ for (const link of links) {
353
+ if (link.hasAttribute(this.options.noPrefetchAttribute))
354
+ continue;
355
+ const strategy = this.getLinkStrategy(link);
356
+ if (strategy === 'eager') {
357
+ this.scheduleIdlePrefetch(link.href, true);
358
+ }
359
+ else if (this.observer && strategy === 'viewport') {
360
+ this.observer.observe(link);
361
+ }
362
+ }
319
363
  }
320
- }
321
- /**
322
- * Observes links for prefetching within `root`.
323
- */
324
- observeLinks(root = document) {
325
- const links = root.querySelectorAll(this.options.linkSelector);
326
- for (const link of links) {
327
- if (link.hasAttribute(this.options.noPrefetchAttribute)) continue;
328
- const strategy = this.getLinkStrategy(link);
329
- if (strategy === "eager") {
330
- this.scheduleIdlePrefetch(link.href, true);
331
- } else if (this.observer && strategy === "viewport") {
332
- this.observer.observe(link);
333
- }
364
+ /**
365
+ * Prefetches stylesheets discovered in HTML content.
366
+ *
367
+ * Parses the HTML to find stylesheet links, then warms the HTTP cache for
368
+ * stylesheets not already present in the current document. This keeps future
369
+ * navigation CSS warm without injecting `preload` hints that browsers expect
370
+ * the current page to consume immediately.
371
+ *
372
+ * @param html - The raw HTML string to parse
373
+ * @param url - The base URL for resolving relative stylesheet paths
374
+ */
375
+ async prefetchStylesheets(html, url) {
376
+ const parser = new DOMParser();
377
+ const doc = parser.parseFromString(`<base href="${url.href}">${html}`, 'text/html');
378
+ const existingHrefs = new Set([...getCurrentStylesheetHrefs(), ...this.prefetchedStylesheets]);
379
+ const newStylesheetHrefs = discoverNewStylesheetLinks(doc, existingHrefs).map((link) => link.href);
380
+ const stylesheetFetches = newStylesheetHrefs.map((href) => {
381
+ this.prefetchedStylesheets.add(href);
382
+ return this.prefetchStylesheet(href);
383
+ });
384
+ await Promise.allSettled(stylesheetFetches);
334
385
  }
335
- }
336
- /**
337
- * Prefetches stylesheets discovered in HTML content.
338
- *
339
- * Parses the HTML to find stylesheet links, then warms the HTTP cache for
340
- * stylesheets not already present in the current document. This keeps future
341
- * navigation CSS warm without injecting `preload` hints that browsers expect
342
- * the current page to consume immediately.
343
- *
344
- * @param html - The raw HTML string to parse
345
- * @param url - The base URL for resolving relative stylesheet paths
346
- */
347
- async prefetchStylesheets(html, url) {
348
- const parser = new DOMParser();
349
- const doc = parser.parseFromString(`<base href="${url.href}">${html}`, "text/html");
350
- const existingHrefs = /* @__PURE__ */ new Set([...getCurrentStylesheetHrefs(), ...this.prefetchedStylesheets]);
351
- const newStylesheetHrefs = discoverNewStylesheetLinks(doc, existingHrefs).map((link) => link.href);
352
- const stylesheetFetches = newStylesheetHrefs.map((href) => {
353
- this.prefetchedStylesheets.add(href);
354
- return this.prefetchStylesheet(href);
355
- });
356
- await Promise.allSettled(stylesheetFetches);
357
- }
358
- async prefetchStylesheet(href) {
359
- try {
360
- await fetch(href, {
361
- credentials: "same-origin",
362
- priority: "low"
363
- });
364
- } catch {
365
- this.prefetchedStylesheets.delete(href);
386
+ async prefetchStylesheet(href) {
387
+ try {
388
+ await fetch(href, {
389
+ credentials: 'same-origin',
390
+ priority: 'low',
391
+ });
392
+ }
393
+ catch {
394
+ this.prefetchedStylesheets.delete(href);
395
+ }
366
396
  }
367
- }
368
397
  }
369
- export {
370
- PrefetchManager
371
- };