@flight-framework/router 0.0.6 → 0.0.7

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.
@@ -0,0 +1,479 @@
1
+ // src/context.ts
2
+ var isBrowser = typeof window !== "undefined";
3
+ var currentContext = {
4
+ path: "/",
5
+ searchParams: new URLSearchParams(),
6
+ navigate: () => {
7
+ },
8
+ back: () => {
9
+ },
10
+ forward: () => {
11
+ }
12
+ };
13
+ var subscribers = /* @__PURE__ */ new Set();
14
+ function subscribe(callback) {
15
+ subscribers.add(callback);
16
+ return () => subscribers.delete(callback);
17
+ }
18
+ function getRouterContext() {
19
+ return currentContext;
20
+ }
21
+ function updateContext(updates) {
22
+ currentContext = { ...currentContext, ...updates };
23
+ subscribers.forEach((cb) => cb(currentContext));
24
+ }
25
+ function navigateTo(to, options = {}) {
26
+ if (!isBrowser) return;
27
+ const { replace = false, scroll = true, state } = options;
28
+ if (replace) {
29
+ window.history.replaceState(state ?? null, "", to);
30
+ } else {
31
+ window.history.pushState(state ?? null, "", to);
32
+ }
33
+ const url = new URL(to, window.location.origin);
34
+ updateContext({
35
+ path: url.pathname,
36
+ searchParams: url.searchParams
37
+ });
38
+ if (scroll) {
39
+ window.scrollTo({ top: 0, left: 0, behavior: "instant" });
40
+ }
41
+ }
42
+ function initRouter(options = {}) {
43
+ const { initialPath, basePath = "" } = options;
44
+ let path;
45
+ let searchParams;
46
+ if (isBrowser) {
47
+ path = window.location.pathname;
48
+ searchParams = new URLSearchParams(window.location.search);
49
+ } else {
50
+ path = initialPath || "/";
51
+ searchParams = new URLSearchParams();
52
+ }
53
+ if (basePath && path.startsWith(basePath)) {
54
+ path = path.slice(basePath.length) || "/";
55
+ }
56
+ currentContext = {
57
+ path,
58
+ searchParams,
59
+ navigate: navigateTo,
60
+ back: () => isBrowser && window.history.back(),
61
+ forward: () => isBrowser && window.history.forward()
62
+ };
63
+ if (isBrowser) {
64
+ window.addEventListener("popstate", () => {
65
+ updateContext({
66
+ path: window.location.pathname,
67
+ searchParams: new URLSearchParams(window.location.search)
68
+ });
69
+ });
70
+ const originalPushState = history.pushState.bind(history);
71
+ const originalReplaceState = history.replaceState.bind(history);
72
+ history.pushState = function(state, unused, url) {
73
+ originalPushState(state, unused, url);
74
+ if (url) {
75
+ const newUrl = new URL(url.toString(), window.location.origin);
76
+ updateContext({
77
+ path: newUrl.pathname,
78
+ searchParams: newUrl.searchParams
79
+ });
80
+ }
81
+ };
82
+ history.replaceState = function(state, unused, url) {
83
+ originalReplaceState(state, unused, url);
84
+ if (url) {
85
+ const newUrl = new URL(url.toString(), window.location.origin);
86
+ updateContext({
87
+ path: newUrl.pathname,
88
+ searchParams: newUrl.searchParams
89
+ });
90
+ }
91
+ };
92
+ }
93
+ }
94
+ var initialized = false;
95
+ if (isBrowser && !initialized) {
96
+ initialized = true;
97
+ initRouter();
98
+ }
99
+ var RouterContext = null;
100
+ var RouterProvider = null;
101
+ var useRouter = getRouterContext;
102
+ if (typeof globalThis !== "undefined") {
103
+ try {
104
+ const React = globalThis.React;
105
+ if (React?.createContext) {
106
+ const { createContext, useState, useEffect, useContext } = React;
107
+ const ReactRouterContext = createContext(currentContext);
108
+ RouterContext = ReactRouterContext;
109
+ RouterProvider = function FlightRouterProvider({
110
+ children,
111
+ initialPath,
112
+ basePath = ""
113
+ }) {
114
+ const [routerState, setRouterState] = useState(() => {
115
+ const path = isBrowser ? window.location.pathname : initialPath || "/";
116
+ const searchParams = isBrowser ? new URLSearchParams(window.location.search) : new URLSearchParams();
117
+ return {
118
+ path: basePath && path.startsWith(basePath) ? path.slice(basePath.length) || "/" : path,
119
+ searchParams,
120
+ navigate: navigateTo,
121
+ back: () => isBrowser && window.history.back(),
122
+ forward: () => isBrowser && window.history.forward()
123
+ };
124
+ });
125
+ useEffect(() => {
126
+ if (!isBrowser) return;
127
+ const handlePopState = () => {
128
+ let path = window.location.pathname;
129
+ if (basePath && path.startsWith(basePath)) {
130
+ path = path.slice(basePath.length) || "/";
131
+ }
132
+ setRouterState((prev) => ({
133
+ ...prev,
134
+ path,
135
+ searchParams: new URLSearchParams(window.location.search)
136
+ }));
137
+ };
138
+ window.addEventListener("popstate", handlePopState);
139
+ return () => window.removeEventListener("popstate", handlePopState);
140
+ }, [basePath]);
141
+ useEffect(() => {
142
+ return subscribe((ctx) => {
143
+ setRouterState((prev) => ({
144
+ ...prev,
145
+ path: ctx.path,
146
+ searchParams: ctx.searchParams
147
+ }));
148
+ });
149
+ }, []);
150
+ return React.createElement(
151
+ ReactRouterContext.Provider,
152
+ { value: routerState },
153
+ children
154
+ );
155
+ };
156
+ useRouter = function useFlightRouter() {
157
+ return useContext(ReactRouterContext);
158
+ };
159
+ }
160
+ } catch {
161
+ }
162
+ }
163
+
164
+ // src/prefetch.ts
165
+ var isBrowser2 = typeof window !== "undefined";
166
+ var supportsIntersectionObserver = isBrowser2 && "IntersectionObserver" in window;
167
+ var prefetchedUrls = /* @__PURE__ */ new Set();
168
+ var prefetchingUrls = /* @__PURE__ */ new Set();
169
+ var viewportObservers = /* @__PURE__ */ new Map();
170
+ function prefetch(href, options = {}) {
171
+ if (!isBrowser2) return;
172
+ const {
173
+ priority = "auto",
174
+ includeModules = true,
175
+ includeData = false
176
+ } = options;
177
+ const url = normalizeUrl(href);
178
+ if (prefetchedUrls.has(url) || prefetchingUrls.has(url)) {
179
+ return;
180
+ }
181
+ prefetchingUrls.add(url);
182
+ createPrefetchLink(url, "document", priority);
183
+ if (includeModules) {
184
+ prefetchModules(url, priority);
185
+ }
186
+ if (includeData) {
187
+ prefetchData(url, priority);
188
+ }
189
+ prefetchedUrls.add(url);
190
+ prefetchingUrls.delete(url);
191
+ }
192
+ function prefetchAll(hrefs, options = {}) {
193
+ for (const href of hrefs) {
194
+ prefetch(href, options);
195
+ }
196
+ }
197
+ function isPrefetched(href) {
198
+ return prefetchedUrls.has(normalizeUrl(href));
199
+ }
200
+ function clearPrefetchCache() {
201
+ prefetchedUrls.clear();
202
+ prefetchingUrls.clear();
203
+ }
204
+ function createPrefetchLink(href, as, priority) {
205
+ if (!isBrowser2) return null;
206
+ const existing = document.querySelector(
207
+ `link[rel="prefetch"][href="${href}"], link[rel="modulepreload"][href="${href}"]`
208
+ );
209
+ if (existing) return existing;
210
+ const link = document.createElement("link");
211
+ if (as === "script") {
212
+ link.rel = "modulepreload";
213
+ } else {
214
+ link.rel = "prefetch";
215
+ link.as = as;
216
+ }
217
+ link.href = href;
218
+ if (priority !== "auto" && "fetchPriority" in link) {
219
+ link.fetchPriority = priority;
220
+ }
221
+ if (priority === "low" && "requestIdleCallback" in window) {
222
+ window.requestIdleCallback(() => {
223
+ document.head.appendChild(link);
224
+ });
225
+ } else {
226
+ document.head.appendChild(link);
227
+ }
228
+ return link;
229
+ }
230
+ function prefetchModules(href, priority) {
231
+ const manifest = window.__FLIGHT_MANIFEST__;
232
+ if (!manifest?.routes) return;
233
+ const routeModules = manifest.routes[href];
234
+ if (!routeModules) return;
235
+ for (const module of routeModules) {
236
+ createPrefetchLink(module, "script", priority);
237
+ }
238
+ }
239
+ function prefetchData(href, priority) {
240
+ const dataUrl = `/_flight/data${href === "/" ? "/index" : href}.json`;
241
+ createPrefetchLink(dataUrl, "fetch", priority);
242
+ }
243
+ var sharedObserver = null;
244
+ var observerCallbacks = /* @__PURE__ */ new Map();
245
+ function getViewportObserver() {
246
+ if (!supportsIntersectionObserver) return null;
247
+ if (!sharedObserver) {
248
+ sharedObserver = new IntersectionObserver(
249
+ (entries) => {
250
+ for (const entry of entries) {
251
+ if (entry.isIntersecting) {
252
+ const callback = observerCallbacks.get(entry.target);
253
+ if (callback) {
254
+ callback();
255
+ sharedObserver?.unobserve(entry.target);
256
+ observerCallbacks.delete(entry.target);
257
+ }
258
+ }
259
+ }
260
+ },
261
+ {
262
+ // Start prefetching when link is 25% visible or within 100px of viewport
263
+ rootMargin: "100px",
264
+ threshold: 0.25
265
+ }
266
+ );
267
+ }
268
+ return sharedObserver;
269
+ }
270
+ function observeForPrefetch(element, href) {
271
+ if (!supportsIntersectionObserver) {
272
+ return () => {
273
+ };
274
+ }
275
+ const observer = getViewportObserver();
276
+ if (!observer) return () => {
277
+ };
278
+ const callback = () => {
279
+ prefetch(href, { priority: "low" });
280
+ };
281
+ observerCallbacks.set(element, callback);
282
+ observer.observe(element);
283
+ const cleanup = () => {
284
+ observer.unobserve(element);
285
+ observerCallbacks.delete(element);
286
+ viewportObservers.delete(element);
287
+ };
288
+ viewportObservers.set(element, cleanup);
289
+ return cleanup;
290
+ }
291
+ function setupIntentPrefetch(element, href) {
292
+ if (!isBrowser2) return () => {
293
+ };
294
+ let prefetchTriggered = false;
295
+ const handleIntent = () => {
296
+ if (!prefetchTriggered) {
297
+ prefetchTriggered = true;
298
+ prefetch(href, { priority: "auto" });
299
+ }
300
+ };
301
+ element.addEventListener("mouseenter", handleIntent, { passive: true });
302
+ element.addEventListener("focus", handleIntent, { passive: true });
303
+ element.addEventListener("touchstart", handleIntent, { passive: true });
304
+ return () => {
305
+ element.removeEventListener("mouseenter", handleIntent);
306
+ element.removeEventListener("focus", handleIntent);
307
+ element.removeEventListener("touchstart", handleIntent);
308
+ };
309
+ }
310
+ function normalizeUrl(href) {
311
+ if (isBrowser2 && !href.startsWith("http")) {
312
+ try {
313
+ const url = new URL(href, window.location.origin);
314
+ return url.pathname + url.search;
315
+ } catch {
316
+ return href;
317
+ }
318
+ }
319
+ return href;
320
+ }
321
+
322
+ // src/prefetch-links.ts
323
+ var isBrowser3 = typeof window !== "undefined";
324
+ var PrefetchPageLinks = null;
325
+ if (typeof globalThis !== "undefined") {
326
+ try {
327
+ const React = globalThis.React;
328
+ if (React?.createElement && "useEffect" in React) {
329
+ const { useEffect, useState } = React;
330
+ PrefetchPageLinks = function FlightPrefetchPageLinks({
331
+ page,
332
+ options = {}
333
+ }) {
334
+ const [shouldRender, setShouldRender] = useState(false);
335
+ useEffect(() => {
336
+ if (!isBrowser3) return;
337
+ if (isPrefetched(page)) {
338
+ return;
339
+ }
340
+ prefetch(page, {
341
+ priority: "low",
342
+ includeModules: true,
343
+ ...options
344
+ });
345
+ setShouldRender(false);
346
+ }, [page, options]);
347
+ return null;
348
+ };
349
+ }
350
+ } catch {
351
+ }
352
+ }
353
+ function prefetchPages(pages, options = {}) {
354
+ if (!isBrowser3) return;
355
+ for (const page of pages) {
356
+ if (!isPrefetched(page)) {
357
+ prefetch(page, {
358
+ priority: "low",
359
+ ...options
360
+ });
361
+ }
362
+ }
363
+ }
364
+ function prefetchWhenIdle(page, options = {}) {
365
+ if (!isBrowser3) return;
366
+ const doPrefetch = () => {
367
+ if (!isPrefetched(page)) {
368
+ prefetch(page, {
369
+ priority: "low",
370
+ ...options
371
+ });
372
+ }
373
+ };
374
+ if ("requestIdleCallback" in window) {
375
+ window.requestIdleCallback(doPrefetch, { timeout: 3e3 });
376
+ } else {
377
+ setTimeout(doPrefetch, 100);
378
+ }
379
+ }
380
+
381
+ // src/navigate.ts
382
+ var isBrowser4 = typeof window !== "undefined";
383
+ function navigate(to, options = {}) {
384
+ const { navigate: routerNavigate } = getRouterContext();
385
+ routerNavigate(to, options);
386
+ }
387
+ function patternToRegex(pattern) {
388
+ const paramNames = [];
389
+ let regexStr = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\\\[\.\.\.(\w+)\\\]/g, (_, name) => {
390
+ paramNames.push(name);
391
+ return "(.+)";
392
+ }).replace(/\\\[(\w+)\\\]/g, (_, name) => {
393
+ paramNames.push(name);
394
+ return "([^/]+)";
395
+ }).replace(/:(\w+)/g, (_, name) => {
396
+ paramNames.push(name);
397
+ return "([^/]+)";
398
+ });
399
+ regexStr = `^${regexStr}$`;
400
+ return {
401
+ regex: new RegExp(regexStr),
402
+ paramNames
403
+ };
404
+ }
405
+ function matchRoute(pathname, pattern) {
406
+ const { regex, paramNames } = patternToRegex(pattern);
407
+ const match = pathname.match(regex);
408
+ if (!match) {
409
+ return { matched: false, params: {} };
410
+ }
411
+ const params = {};
412
+ paramNames.forEach((name, index) => {
413
+ params[name] = match[index + 1] || "";
414
+ });
415
+ return { matched: true, params };
416
+ }
417
+ function parseParams(pathname, pattern) {
418
+ const { params } = matchRoute(pathname, pattern);
419
+ return params;
420
+ }
421
+ function findRoute(pathname, routes) {
422
+ for (const route of routes) {
423
+ const { matched, params } = matchRoute(pathname, route.path);
424
+ if (matched) {
425
+ return {
426
+ route,
427
+ params,
428
+ pathname
429
+ };
430
+ }
431
+ }
432
+ return null;
433
+ }
434
+ function generatePath(pattern, params = {}) {
435
+ let path = pattern;
436
+ path = path.replace(/\[(\w+)\]/g, (_, name) => {
437
+ return params[name] || "";
438
+ });
439
+ path = path.replace(/:(\w+)/g, (_, name) => {
440
+ return params[name] || "";
441
+ });
442
+ return path;
443
+ }
444
+ function isActive(pattern) {
445
+ const { path } = getRouterContext();
446
+ const { matched } = matchRoute(path, pattern);
447
+ return matched;
448
+ }
449
+ function redirect(url) {
450
+ if (isBrowser4) {
451
+ window.location.href = url;
452
+ }
453
+ throw new Error(`Redirect to: ${url}`);
454
+ }
455
+
456
+ export {
457
+ subscribe,
458
+ getRouterContext,
459
+ initRouter,
460
+ RouterContext,
461
+ RouterProvider,
462
+ useRouter,
463
+ prefetch,
464
+ prefetchAll,
465
+ isPrefetched,
466
+ clearPrefetchCache,
467
+ observeForPrefetch,
468
+ setupIntentPrefetch,
469
+ PrefetchPageLinks,
470
+ prefetchPages,
471
+ prefetchWhenIdle,
472
+ navigate,
473
+ matchRoute,
474
+ parseParams,
475
+ findRoute,
476
+ generatePath,
477
+ isActive,
478
+ redirect
479
+ };