@ecopages/browser-router 0.2.0-beta.31 → 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,347 +1,355 @@
1
- import { getEcoNavigationRuntime } from "@ecopages/core/router/navigation-coordinator";
2
- import {
3
- getAnchorFromNavigationEvent,
4
- isStaticAssetHref,
5
- recoverPendingNavigationHref
6
- } from "@ecopages/core/router/link-intent";
7
- import { getNavigableHrefFromClick } from "@ecopages/core/router/link-navigation-policy";
8
- import { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS } from "./types.js";
9
- import { DomSwapper } from "./dom/dom-swapper.js";
10
- import { PrefetchManager } from "./services/prefetch-manager.js";
11
- import { ViewTransitionManager } from "./services/view-transition-manager.js";
12
- import { NavigationCommit } from "./navigation-commit.js";
13
- import { fetchNavigationPage } from "./navigation-fetch.js";
14
- class EcoRouter {
15
- options;
16
- unregisterNavigationRuntime = null;
17
- started = false;
18
- pendingNavigations = 0;
19
- pendingPointerNavigation = null;
20
- queuedNavigationHref = null;
21
- domSwapper;
22
- viewTransitionManager;
23
- prefetchManager = null;
24
- navigationCommit;
25
- constructor(options = {}) {
26
- this.options = {
27
- ...DEFAULT_OPTIONS,
28
- ...options,
29
- documentElementAttributesToSync: [
30
- ...options.documentElementAttributesToSync ?? DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC
31
- ]
32
- };
33
- this.domSwapper = new DomSwapper(this.options.persistAttribute);
34
- this.viewTransitionManager = new ViewTransitionManager(this.options.viewTransitions);
35
- if (this.options.prefetch !== false) {
36
- this.prefetchManager = new PrefetchManager({
37
- ...this.options.prefetch,
38
- linkSelector: this.options.linkSelector
39
- });
1
+ /**
2
+ * Client-side router for Ecopages with morphdom-based DOM diffing.
3
+ * @module eco-router
4
+ */
5
+ import { getEcoNavigationRuntime } from '@ecopages/core/router/navigation-coordinator';
6
+ import { getAnchorFromNavigationEvent, isStaticAssetHref, recoverPendingNavigationHref, } from '@ecopages/core/router/link-intent';
7
+ import { getNavigableHrefFromClick } from '@ecopages/core/router/link-navigation-policy';
8
+ import { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS } from './types.js';
9
+ import { DomSwapper } from './dom/dom-swapper.js';
10
+ import { PrefetchManager } from './services/prefetch-manager.js';
11
+ import { ViewTransitionManager } from './services/view-transition-manager.js';
12
+ import { NavigationCommit } from './navigation-commit.js';
13
+ import { fetchNavigationPage } from './navigation-fetch.js';
14
+ /**
15
+ * Intercepts same-origin link clicks and performs client-side navigation
16
+ * using morphdom for efficient DOM diffing. Supports View Transitions API.
17
+ */
18
+ export class EcoRouter {
19
+ options;
20
+ unregisterNavigationRuntime = null;
21
+ started = false;
22
+ pendingNavigations = 0;
23
+ pendingPointerNavigation = null;
24
+ queuedNavigationHref = null;
25
+ domSwapper;
26
+ viewTransitionManager;
27
+ prefetchManager = null;
28
+ navigationCommit;
29
+ constructor(options = {}) {
30
+ this.options = {
31
+ ...DEFAULT_OPTIONS,
32
+ ...options,
33
+ documentElementAttributesToSync: [
34
+ ...(options.documentElementAttributesToSync ?? DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC),
35
+ ],
36
+ };
37
+ this.domSwapper = new DomSwapper(this.options.persistAttribute);
38
+ this.viewTransitionManager = new ViewTransitionManager(this.options.viewTransitions);
39
+ if (this.options.prefetch !== false) {
40
+ this.prefetchManager = new PrefetchManager({
41
+ ...this.options.prefetch,
42
+ linkSelector: this.options.linkSelector,
43
+ });
44
+ }
45
+ this.handleClick = this.handleClick.bind(this);
46
+ this.handlePointerDown = this.handlePointerDown.bind(this);
47
+ this.handlePopState = this.handlePopState.bind(this);
48
+ this.navigationCommit = new NavigationCommit(this.domSwapper, this.viewTransitionManager, this.prefetchManager, this.options);
40
49
  }
41
- this.handleClick = this.handleClick.bind(this);
42
- this.handlePointerDown = this.handlePointerDown.bind(this);
43
- this.handlePopState = this.handlePopState.bind(this);
44
- this.navigationCommit = new NavigationCommit(
45
- this.domSwapper,
46
- this.viewTransitionManager,
47
- this.prefetchManager,
48
- this.options
49
- );
50
- }
51
- getRecoveredPointerHref() {
52
- const href = recoverPendingNavigationHref(
53
- this.pendingPointerNavigation,
54
- this.pendingNavigations > 0,
55
- performance.now()
56
- );
57
- if (!href) {
58
- this.pendingPointerNavigation = null;
50
+ getRecoveredPointerHref() {
51
+ const href = recoverPendingNavigationHref(this.pendingPointerNavigation, this.pendingNavigations > 0, performance.now());
52
+ if (!href) {
53
+ this.pendingPointerNavigation = null;
54
+ }
55
+ return href;
59
56
  }
60
- return href;
61
- }
62
- isAnotherNavigationRuntimeActive() {
63
- const ownerState = getEcoNavigationRuntime(window).getOwnerState();
64
- return ownerState.owner !== "none" && ownerState.owner !== "browser-router" && ownerState.canHandleSpaNavigation;
65
- }
66
- /**
67
- * Starts the router and begins intercepting navigation.
68
- *
69
- * Attaches click handlers for links and popstate handlers for browser
70
- * back/forward buttons. Also starts the prefetch manager if configured.
71
- */
72
- start() {
73
- if (this.started) {
74
- return;
57
+ isAnotherNavigationRuntimeActive() {
58
+ const ownerState = getEcoNavigationRuntime(window).getOwnerState();
59
+ return (ownerState.owner !== 'none' && ownerState.owner !== 'browser-router' && ownerState.canHandleSpaNavigation);
75
60
  }
76
- const navigationRuntime = getEcoNavigationRuntime(window);
77
- navigationRuntime.cancelCurrentNavigationTransaction();
78
- this.pendingNavigations = 0;
79
- this.queuedNavigationHref = null;
80
- this.pendingPointerNavigation = null;
81
- document.addEventListener("pointerdown", this.handlePointerDown, true);
82
- document.addEventListener("click", this.handleClick, true);
83
- window.addEventListener("popstate", this.handlePopState);
84
- this.prefetchManager?.start();
85
- this.unregisterNavigationRuntime?.();
86
- this.unregisterNavigationRuntime = navigationRuntime.register({
87
- owner: "browser-router",
88
- navigate: async (request) => {
89
- await this.performNavigation(
90
- new URL(request.href, window.location.origin),
91
- request.direction ?? "forward"
92
- );
93
- return true;
94
- },
95
- handoffNavigation: async (request) => {
96
- const { isStaleNavigation, complete } = this.beginNavigationTransaction();
97
- if (isStaleNavigation()) return true;
98
- try {
99
- await this.navigationCommit.commit(
100
- new URL(request.finalHref ?? request.href, window.location.origin),
101
- request.direction ?? "forward",
102
- request.document,
103
- { html: request.html, isStaleNavigation }
104
- );
105
- } finally {
106
- complete();
61
+ /**
62
+ * Starts the router and begins intercepting navigation.
63
+ *
64
+ * Attaches click handlers for links and popstate handlers for browser
65
+ * back/forward buttons. Also starts the prefetch manager if configured.
66
+ */
67
+ start() {
68
+ if (this.started) {
69
+ return;
107
70
  }
108
- return true;
109
- },
110
- reloadCurrentPage: async (request) => {
111
- if (this.pendingNavigations > 0) {
112
- return false;
113
- }
114
- const currentUrl = window.location.pathname + window.location.search;
115
- if (request?.clearCache) {
116
- this.prefetchManager?.invalidate(currentUrl);
117
- }
118
- return await this.performNavigation(new URL(currentUrl, window.location.origin), "replace", {
119
- bypassPrefetchCache: !!request?.clearCache,
120
- allowFullDocumentFallback: false
71
+ const navigationRuntime = getEcoNavigationRuntime(window);
72
+ navigationRuntime.cancelCurrentNavigationTransaction();
73
+ this.pendingNavigations = 0;
74
+ this.queuedNavigationHref = null;
75
+ this.pendingPointerNavigation = null;
76
+ document.addEventListener('pointerdown', this.handlePointerDown, true);
77
+ document.addEventListener('click', this.handleClick, true);
78
+ window.addEventListener('popstate', this.handlePopState);
79
+ this.prefetchManager?.start();
80
+ this.unregisterNavigationRuntime?.();
81
+ this.unregisterNavigationRuntime = navigationRuntime.register({
82
+ owner: 'browser-router',
83
+ navigate: async (request) => {
84
+ await this.performNavigation(new URL(request.href, window.location.origin), request.direction ?? 'forward');
85
+ return true;
86
+ },
87
+ handoffNavigation: async (request) => {
88
+ const { isStaleNavigation, complete } = this.beginNavigationTransaction();
89
+ if (isStaleNavigation())
90
+ return true;
91
+ try {
92
+ await this.navigationCommit.commit(new URL(request.finalHref ?? request.href, window.location.origin), request.direction ?? 'forward', request.document, { html: request.html, isStaleNavigation });
93
+ }
94
+ finally {
95
+ complete();
96
+ }
97
+ return true;
98
+ },
99
+ reloadCurrentPage: async (request) => {
100
+ if (this.pendingNavigations > 0) {
101
+ return false;
102
+ }
103
+ const currentUrl = window.location.pathname + window.location.search;
104
+ if (request?.clearCache) {
105
+ this.prefetchManager?.invalidate(currentUrl);
106
+ }
107
+ return await this.performNavigation(new URL(currentUrl, window.location.origin), 'replace', {
108
+ bypassPrefetchCache: !!request?.clearCache,
109
+ allowFullDocumentFallback: false,
110
+ });
111
+ },
112
+ cleanupBeforeHandoff: async () => {
113
+ this.cancelNavigationTransaction();
114
+ },
121
115
  });
122
- },
123
- cleanupBeforeHandoff: async () => {
124
- this.cancelNavigationTransaction();
125
- }
126
- });
127
- getEcoNavigationRuntime(window).adoptDocumentOwner(document, "browser-router");
128
- const initialHtml = document.documentElement.outerHTML;
129
- this.prefetchManager?.cacheVisitedPage(window.location.href, initialHtml);
130
- this.started = true;
131
- }
132
- /**
133
- * Stops the router and cleans up all event listeners.
134
- * After calling this, navigation will fall back to full page reloads.
135
- */
136
- stop() {
137
- if (!this.started) {
138
- return;
116
+ getEcoNavigationRuntime(window).adoptDocumentOwner(document, 'browser-router');
117
+ // Cache the initial page for instant back-navigation
118
+ const initialHtml = document.documentElement.outerHTML;
119
+ this.prefetchManager?.cacheVisitedPage(window.location.href, initialHtml);
120
+ this.started = true;
139
121
  }
140
- this.cancelNavigationTransaction();
141
- document.removeEventListener("pointerdown", this.handlePointerDown, true);
142
- document.removeEventListener("click", this.handleClick, true);
143
- window.removeEventListener("popstate", this.handlePopState);
144
- this.prefetchManager?.stop();
145
- this.unregisterNavigationRuntime?.();
146
- this.unregisterNavigationRuntime = null;
147
- this.started = false;
148
- this.pendingPointerNavigation = null;
149
- this.queuedNavigationHref = null;
150
- const win = window;
151
- if (win[ACTIVE_ROUTER_KEY] === this) {
152
- delete win[ACTIVE_ROUTER_KEY];
122
+ /**
123
+ * Stops the router and cleans up all event listeners.
124
+ * After calling this, navigation will fall back to full page reloads.
125
+ */
126
+ stop() {
127
+ if (!this.started) {
128
+ return;
129
+ }
130
+ this.cancelNavigationTransaction();
131
+ document.removeEventListener('pointerdown', this.handlePointerDown, true);
132
+ document.removeEventListener('click', this.handleClick, true);
133
+ window.removeEventListener('popstate', this.handlePopState);
134
+ this.prefetchManager?.stop();
135
+ this.unregisterNavigationRuntime?.();
136
+ this.unregisterNavigationRuntime = null;
137
+ this.started = false;
138
+ this.pendingPointerNavigation = null;
139
+ this.queuedNavigationHref = null;
140
+ const win = window;
141
+ if (win[ACTIVE_ROUTER_KEY] === this) {
142
+ delete win[ACTIVE_ROUTER_KEY];
143
+ }
153
144
  }
154
- }
155
- /**
156
- * Programmatic navigation.
157
- * Falls back to full page reload for cross-origin URLs.
158
- * @param href - The URL to navigate to
159
- * @param options - Navigation options
160
- * @param options.replace - If true, replaces the current history entry instead of pushing
161
- */
162
- async navigate(href, options = {}) {
163
- const url = new URL(href, window.location.origin);
164
- if (url.origin !== window.location.origin) {
165
- window.location.href = href;
166
- return;
145
+ /**
146
+ * Programmatic navigation.
147
+ * Falls back to full page reload for cross-origin URLs.
148
+ * @param href - The URL to navigate to
149
+ * @param options - Navigation options
150
+ * @param options.replace - If true, replaces the current history entry instead of pushing
151
+ */
152
+ async navigate(href, options = {}) {
153
+ const url = new URL(href, window.location.origin);
154
+ if (url.origin !== window.location.origin) {
155
+ window.location.href = href;
156
+ return;
157
+ }
158
+ if (isStaticAssetHref(href)) {
159
+ window.location.assign(url.href);
160
+ return;
161
+ }
162
+ await this.performNavigation(url, options.replace ? 'replace' : 'forward');
167
163
  }
168
- if (isStaticAssetHref(href)) {
169
- window.location.assign(url.href);
170
- return;
164
+ /**
165
+ * Manually prefetch a URL.
166
+ * @param href - The URL to prefetch
167
+ */
168
+ async prefetch(href) {
169
+ if (!this.prefetchManager) {
170
+ console.warn('[ecopages] Prefetching is disabled. Enable it in router options.');
171
+ return;
172
+ }
173
+ return this.prefetchManager.prefetch(href);
171
174
  }
172
- await this.performNavigation(url, options.replace ? "replace" : "forward");
173
- }
174
- /**
175
- * Manually prefetch a URL.
176
- * @param href - The URL to prefetch
177
- */
178
- async prefetch(href) {
179
- if (!this.prefetchManager) {
180
- console.warn("[ecopages] Prefetching is disabled. Enable it in router options.");
181
- return;
175
+ /**
176
+ * Intercepts link clicks for client-side navigation.
177
+ *
178
+ * Filters out clicks with modifier keys (opens new tab), non-left clicks,
179
+ * external links, download links, and links with the reload attribute.
180
+ *
181
+ * Uses `event.composedPath()` to correctly detect clicks on anchors inside
182
+ * Shadow DOM boundaries (Web Components).
183
+ */
184
+ handlePointerDown(event) {
185
+ const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
186
+ if (!link) {
187
+ this.pendingPointerNavigation = null;
188
+ return;
189
+ }
190
+ const href = getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute });
191
+ this.pendingPointerNavigation = href
192
+ ? {
193
+ href,
194
+ timestamp: performance.now(),
195
+ }
196
+ : null;
197
+ if (href && this.pendingNavigations > 0) {
198
+ this.queuedNavigationHref = href;
199
+ }
182
200
  }
183
- return this.prefetchManager.prefetch(href);
184
- }
185
- /**
186
- * Intercepts link clicks for client-side navigation.
187
- *
188
- * Filters out clicks with modifier keys (opens new tab), non-left clicks,
189
- * external links, download links, and links with the reload attribute.
190
- *
191
- * Uses `event.composedPath()` to correctly detect clicks on anchors inside
192
- * Shadow DOM boundaries (Web Components).
193
- */
194
- handlePointerDown(event) {
195
- const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
196
- if (!link) {
197
- this.pendingPointerNavigation = null;
198
- return;
201
+ handleClick(event) {
202
+ const navigationRuntime = getEcoNavigationRuntime(window);
203
+ const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
204
+ const href = link
205
+ ? getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute })
206
+ : this.getRecoveredPointerHref();
207
+ this.pendingPointerNavigation = null;
208
+ if (!href)
209
+ return;
210
+ this.queuedNavigationHref = null;
211
+ if (this.isAnotherNavigationRuntimeActive()) {
212
+ event.preventDefault();
213
+ event.stopImmediatePropagation();
214
+ void navigationRuntime.requestNavigation({
215
+ href,
216
+ direction: 'forward',
217
+ source: 'browser-router',
218
+ });
219
+ return;
220
+ }
221
+ const url = new URL(href, window.location.origin);
222
+ event.preventDefault();
223
+ if (this.pendingNavigations > 0) {
224
+ this.queuedNavigationHref = href;
225
+ this.cancelNavigationTransaction();
226
+ return;
227
+ }
228
+ this.performNavigation(url, 'forward');
199
229
  }
200
- const href = getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute });
201
- this.pendingPointerNavigation = href ? {
202
- href,
203
- timestamp: performance.now()
204
- } : null;
205
- if (href && this.pendingNavigations > 0) {
206
- this.queuedNavigationHref = href;
230
+ /**
231
+ * Handles browser back/forward navigation.
232
+ * Triggered by the History API's popstate event.
233
+ */
234
+ handlePopState(_event) {
235
+ if (this.isAnotherNavigationRuntimeActive())
236
+ return;
237
+ const url = new URL(window.location.href);
238
+ this.performNavigation(url, 'back');
207
239
  }
208
- }
209
- handleClick(event) {
210
- const navigationRuntime = getEcoNavigationRuntime(window);
211
- const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
212
- const href = link ? getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute }) : this.getRecoveredPointerHref();
213
- this.pendingPointerNavigation = null;
214
- if (!href) return;
215
- this.queuedNavigationHref = null;
216
- if (this.isAnotherNavigationRuntimeActive()) {
217
- event.preventDefault();
218
- event.stopImmediatePropagation();
219
- void navigationRuntime.requestNavigation({
220
- href,
221
- direction: "forward",
222
- source: "browser-router"
223
- });
224
- return;
240
+ cancelNavigationTransaction() {
241
+ getEcoNavigationRuntime(window).cancelCurrentNavigationTransaction();
225
242
  }
226
- const url = new URL(href, window.location.origin);
227
- event.preventDefault();
228
- if (this.pendingNavigations > 0) {
229
- this.queuedNavigationHref = href;
230
- this.cancelNavigationTransaction();
231
- return;
243
+ beginNavigationTransaction() {
244
+ const transaction = getEcoNavigationRuntime(window).beginNavigationTransaction();
245
+ return {
246
+ isStaleNavigation: () => !transaction.isCurrent(),
247
+ signal: transaction.signal,
248
+ complete: () => transaction.complete(),
249
+ };
232
250
  }
233
- this.performNavigation(url, "forward");
234
- }
235
- /**
236
- * Handles browser back/forward navigation.
237
- * Triggered by the History API's popstate event.
238
- */
239
- handlePopState(_event) {
240
- if (this.isAnotherNavigationRuntimeActive()) return;
241
- const url = new URL(window.location.href);
242
- this.performNavigation(url, "back");
243
- }
244
- cancelNavigationTransaction() {
245
- getEcoNavigationRuntime(window).cancelCurrentNavigationTransaction();
246
- }
247
- beginNavigationTransaction() {
248
- const transaction = getEcoNavigationRuntime(window).beginNavigationTransaction();
249
- return {
250
- isStaleNavigation: () => !transaction.isCurrent(),
251
- signal: transaction.signal,
252
- complete: () => transaction.complete()
253
- };
254
- }
255
- /**
256
- * Executes the core navigation flow.
257
- *
258
- * Orchestrates fetching, DOM swapping, and lifecycle events:
259
- *
260
- * 1. **Fetch** - Retrieves HTML (from cache or network)
261
- * 2. **eco:before-swap** - Allows listeners to force a full reload
262
- * 3. **History update** - Updates URL before DOM swap so Web Components
263
- * see the correct URL in their `connectedCallback`
264
- * 4. **Stylesheet preload** - Prevents FOUC by loading styles first
265
- * 5. **DOM swap** - Morphs head/body, optionally with View Transition
266
- * 6. **Lifecycle events** - Dispatches `eco:after-swap` and `eco:page-load`
267
- *
268
- * Falls back to full page reload on network errors.
269
- *
270
- * @param url - The target URL to navigate to
271
- * @param direction - Navigation direction ('forward', 'back', or 'replace')
272
- */
273
- async performNavigation(url, direction, options = {}) {
274
- const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
275
- this.pendingNavigations++;
276
- const { isStaleNavigation, signal, complete } = this.beginNavigationTransaction();
277
- let queuedNavigationHref = null;
278
- let committed = false;
279
- try {
280
- const html = await fetchNavigationPage(url, signal, {
281
- bypassCache: options.bypassPrefetchCache,
282
- getCachedHtml: this.prefetchManager ? (href) => this.prefetchManager.getCachedHtml(href) : void 0
283
- });
284
- if (isStaleNavigation()) {
285
- return false;
286
- }
287
- const newDocument = this.domSwapper.parseHTML(html, url);
288
- if (isStaleNavigation()) {
289
- return false;
290
- }
291
- committed = await this.navigationCommit.commit(url, direction, newDocument, {
292
- html,
293
- isStaleNavigation,
294
- allowFullDocumentFallback
295
- });
296
- return committed;
297
- } catch (error) {
298
- if (isStaleNavigation()) {
299
- return false;
300
- }
301
- if (error instanceof Error && error.name === "AbortError") {
302
- return false;
303
- }
304
- console.error("[ecopages] Navigation failed:", error);
305
- if (allowFullDocumentFallback) {
306
- window.location.href = url.href;
307
- }
308
- return false;
309
- } finally {
310
- complete();
311
- this.pendingNavigations--;
312
- const navigationRuntime = getEcoNavigationRuntime(window);
313
- if (!navigationRuntime.hasPendingNavigationTransaction()) {
314
- queuedNavigationHref = this.queuedNavigationHref;
315
- this.queuedNavigationHref = null;
316
- }
317
- if (queuedNavigationHref && queuedNavigationHref !== window.location.pathname + window.location.search) {
318
- const ownerState = navigationRuntime.getOwnerState();
319
- if (ownerState.owner !== "none" && ownerState.owner !== "browser-router" && ownerState.canHandleSpaNavigation) {
320
- void navigationRuntime.requestNavigation({
321
- href: queuedNavigationHref,
322
- direction: "forward",
323
- source: "browser-router"
324
- });
325
- } else {
326
- void this.performNavigation(new URL(queuedNavigationHref, window.location.origin), "forward");
251
+ /**
252
+ * Executes the core navigation flow.
253
+ *
254
+ * Orchestrates fetching, DOM swapping, and lifecycle events:
255
+ *
256
+ * 1. **Fetch** - Retrieves HTML (from cache or network)
257
+ * 2. **eco:before-swap** - Allows listeners to force a full reload
258
+ * 3. **History update** - Updates URL before DOM swap so Web Components
259
+ * see the correct URL in their `connectedCallback`
260
+ * 4. **Stylesheet preload** - Prevents FOUC by loading styles first
261
+ * 5. **DOM swap** - Morphs head/body, optionally with View Transition
262
+ * 6. **Lifecycle events** - Dispatches `eco:after-swap` and `eco:page-load`
263
+ *
264
+ * Falls back to full page reload on network errors.
265
+ *
266
+ * @param url - The target URL to navigate to
267
+ * @param direction - Navigation direction ('forward', 'back', or 'replace')
268
+ */
269
+ async performNavigation(url, direction, options = {}) {
270
+ const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
271
+ this.pendingNavigations++;
272
+ const { isStaleNavigation, signal, complete } = this.beginNavigationTransaction();
273
+ let queuedNavigationHref = null;
274
+ let committed = false;
275
+ try {
276
+ const html = await fetchNavigationPage(url, signal, {
277
+ bypassCache: options.bypassPrefetchCache,
278
+ getCachedHtml: this.prefetchManager ? (href) => this.prefetchManager.getCachedHtml(href) : undefined,
279
+ });
280
+ if (isStaleNavigation()) {
281
+ return false;
282
+ }
283
+ const newDocument = this.domSwapper.parseHTML(html, url);
284
+ if (isStaleNavigation()) {
285
+ return false;
286
+ }
287
+ committed = await this.navigationCommit.commit(url, direction, newDocument, {
288
+ html,
289
+ isStaleNavigation,
290
+ allowFullDocumentFallback,
291
+ });
292
+ return committed;
293
+ }
294
+ catch (error) {
295
+ if (isStaleNavigation()) {
296
+ return false;
297
+ }
298
+ if (error instanceof Error && error.name === 'AbortError') {
299
+ return false;
300
+ }
301
+ console.error('[ecopages] Navigation failed:', error);
302
+ if (allowFullDocumentFallback) {
303
+ window.location.href = url.href;
304
+ }
305
+ return false;
306
+ }
307
+ finally {
308
+ complete();
309
+ this.pendingNavigations--;
310
+ const navigationRuntime = getEcoNavigationRuntime(window);
311
+ if (!navigationRuntime.hasPendingNavigationTransaction()) {
312
+ queuedNavigationHref = this.queuedNavigationHref;
313
+ this.queuedNavigationHref = null;
314
+ }
315
+ if (queuedNavigationHref && queuedNavigationHref !== window.location.pathname + window.location.search) {
316
+ const ownerState = navigationRuntime.getOwnerState();
317
+ if (ownerState.owner !== 'none' &&
318
+ ownerState.owner !== 'browser-router' &&
319
+ ownerState.canHandleSpaNavigation) {
320
+ void navigationRuntime.requestNavigation({
321
+ href: queuedNavigationHref,
322
+ direction: 'forward',
323
+ source: 'browser-router',
324
+ });
325
+ }
326
+ else {
327
+ void this.performNavigation(new URL(queuedNavigationHref, window.location.origin), 'forward');
328
+ }
329
+ }
327
330
  }
328
- }
329
331
  }
330
- }
331
332
  }
332
- const ACTIVE_ROUTER_KEY = "__ecopages_browser_router__";
333
- function createRouter(options) {
334
- const win = window;
335
- const existingRouter = win[ACTIVE_ROUTER_KEY];
336
- if (existingRouter) {
337
- return existingRouter;
338
- }
339
- const router = new EcoRouter(options);
340
- win[ACTIVE_ROUTER_KEY] = router;
341
- router.start();
342
- return router;
333
+ const ACTIVE_ROUTER_KEY = '__ecopages_browser_router__';
334
+ /**
335
+ * Creates and starts a router instance.
336
+ *
337
+ * Stops the previously active router (if any) before creating a new one so
338
+ * click listeners and coordinator registrations from earlier instances are
339
+ * cleaned up on re-execution (e.g. when the layout script is re-run via
340
+ * `data-eco-rerun` after a browser-router page commit).
341
+ *
342
+ * @param options - Configuration options for the router
343
+ * @returns A started EcoRouter instance
344
+ */
345
+ export function createRouter(options) {
346
+ const win = window;
347
+ const existingRouter = win[ACTIVE_ROUTER_KEY];
348
+ if (existingRouter) {
349
+ return existingRouter;
350
+ }
351
+ const router = new EcoRouter(options);
352
+ win[ACTIVE_ROUTER_KEY] = router;
353
+ router.start();
354
+ return router;
343
355
  }
344
- export {
345
- EcoRouter,
346
- createRouter
347
- };