@flight-framework/router 0.3.0 → 0.3.2

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