@bquery/bquery 1.1.2 → 1.2.0

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,166 @@
1
+ import { computed as E, signal as S } from "./reactive.es.mjs";
2
+ let h = null;
3
+ const d = S({
4
+ path: "",
5
+ params: {},
6
+ query: {},
7
+ matched: null,
8
+ hash: ""
9
+ }), _ = E(() => d.value), z = (r) => {
10
+ if (r === "*")
11
+ return /^.*$/;
12
+ const o = "\0P\0", e = "\0W\0", a = [];
13
+ let t = r.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (u, p) => (a.push(p), o));
14
+ t = t.replace(/\*/g, e), t = t.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
15
+ let n = 0;
16
+ return t = t.replace(/\u0000P\u0000/g, () => `(?<${a[n++]}>[^/]+)`), t = t.replace(/\u0000W\u0000/g, ".*"), new RegExp(`^${t}$`);
17
+ }, N = (r) => {
18
+ const o = r.match(/:([a-zA-Z_][a-zA-Z0-9_]*)/g);
19
+ return o ? o.map((e) => e.slice(1)) : [];
20
+ }, W = (r, o) => {
21
+ for (const e of o) {
22
+ const a = z(e.path), t = r.match(a);
23
+ if (t) {
24
+ const n = N(e.path), u = {};
25
+ return t.groups ? Object.assign(u, t.groups) : n.forEach((p, w) => {
26
+ u[p] = t[w + 1] || "";
27
+ }), { matched: e, params: u };
28
+ }
29
+ }
30
+ return null;
31
+ }, C = (r) => {
32
+ const o = {};
33
+ return new URLSearchParams(r).forEach((a, t) => {
34
+ const n = o[t];
35
+ n === void 0 ? o[t] = a : Array.isArray(n) ? n.push(a) : o[t] = [n, a];
36
+ }), o;
37
+ }, y = (r, o, e, a) => {
38
+ const t = W(r, a);
39
+ return {
40
+ path: r,
41
+ params: t?.params ?? {},
42
+ query: C(o),
43
+ matched: t?.matched ?? null,
44
+ hash: e.replace(/^#/, "")
45
+ };
46
+ }, P = async (r, o = {}) => {
47
+ if (!h)
48
+ throw new Error("bQuery router: No router initialized. Call createRouter() first.");
49
+ await h[o.replace ? "replace" : "push"](r);
50
+ }, Q = () => {
51
+ h ? h.back() : history.back();
52
+ }, Z = () => {
53
+ h ? h.forward() : history.forward();
54
+ }, q = (r) => {
55
+ h && h.destroy();
56
+ const { routes: o, base: e = "", hash: a = !1 } = r, t = [], n = [], u = x(o, e), p = () => {
57
+ if (a) {
58
+ const c = window.location.hash.slice(1) || "/", [f, i = ""] = c.split("?"), [m, l = ""] = i.split("#");
59
+ return {
60
+ pathname: f,
61
+ search: m ? `?${m}` : "",
62
+ hash: l ? `#${l}` : ""
63
+ };
64
+ }
65
+ let s = window.location.pathname;
66
+ return e && s.startsWith(e) && (s = s.slice(e.length) || "/"), {
67
+ pathname: s,
68
+ search: window.location.search,
69
+ hash: window.location.hash
70
+ };
71
+ }, w = () => {
72
+ const { pathname: s, search: c, hash: f } = p(), i = y(s, c, f, u);
73
+ d.value = i;
74
+ }, $ = async (s, c) => {
75
+ const { pathname: f, search: i, hash: m } = p(), l = y(f, i, m, u), g = new URL(s, window.location.origin), R = a ? s : g.pathname, k = y(R, g.search, g.hash, u);
76
+ for (const v of t)
77
+ if (await v(k, l) === !1)
78
+ return;
79
+ const L = a ? `#${s}` : `${e}${s}`;
80
+ history[c]({}, "", L), w();
81
+ for (const v of n)
82
+ v(d.value, l);
83
+ }, b = async () => {
84
+ const { pathname: s, search: c, hash: f } = p(), i = d.value, m = y(s, c, f, u);
85
+ for (const l of t)
86
+ if (await l(m, i) === !1) {
87
+ const R = a ? `#${i.path}` : `${e}${i.path}`;
88
+ history.pushState({}, "", R);
89
+ return;
90
+ }
91
+ w();
92
+ for (const l of n)
93
+ l(d.value, i);
94
+ };
95
+ window.addEventListener("popstate", b), w();
96
+ const A = {
97
+ push: (s) => $(s, "pushState"),
98
+ replace: (s) => $(s, "replaceState"),
99
+ back: () => history.back(),
100
+ forward: () => history.forward(),
101
+ go: (s) => history.go(s),
102
+ beforeEach: (s) => (t.push(s), () => {
103
+ const c = t.indexOf(s);
104
+ c > -1 && t.splice(c, 1);
105
+ }),
106
+ afterEach: (s) => (n.push(s), () => {
107
+ const c = n.indexOf(s);
108
+ c > -1 && n.splice(c, 1);
109
+ }),
110
+ currentRoute: _,
111
+ routes: u,
112
+ destroy: () => {
113
+ window.removeEventListener("popstate", b), t.length = 0, n.length = 0, h = null;
114
+ }
115
+ };
116
+ return h = A, A;
117
+ }, x = (r, o = "") => {
118
+ const e = [];
119
+ for (const a of r) {
120
+ const t = a.path === "*" ? "*" : `${o}${a.path}`.replace(/\/+/g, "/");
121
+ e.push({
122
+ ...a,
123
+ path: t
124
+ }), a.children && e.push(...x(a.children, t));
125
+ }
126
+ return e;
127
+ }, I = (r, o = {}) => {
128
+ if (!h)
129
+ throw new Error("bQuery router: No router initialized.");
130
+ const e = h.routes.find((t) => t.name === r);
131
+ if (!e)
132
+ throw new Error(`bQuery router: Route "${r}" not found.`);
133
+ let a = e.path;
134
+ for (const [t, n] of Object.entries(o))
135
+ a = a.replace(`:${t}`, encodeURIComponent(n));
136
+ return a;
137
+ }, M = (r, o = !1) => {
138
+ const e = d.value.path;
139
+ return o ? e === r : e.startsWith(r);
140
+ }, U = (r, o = !1) => E(() => {
141
+ const e = d.value.path;
142
+ return o ? e === r : e.startsWith(r);
143
+ }), j = (r, o = {}) => (e) => {
144
+ e.preventDefault(), P(r, o);
145
+ }, H = (r = document.body) => {
146
+ const o = (e) => {
147
+ const t = e.target.closest("a");
148
+ if (!t || t.target || t.hasAttribute("download") || t.origin !== window.location.origin) return;
149
+ const n = t.pathname + t.search + t.hash;
150
+ e.preventDefault(), P(n);
151
+ };
152
+ return r.addEventListener("click", o), () => r.removeEventListener("click", o);
153
+ };
154
+ export {
155
+ Q as back,
156
+ q as createRouter,
157
+ _ as currentRoute,
158
+ Z as forward,
159
+ H as interceptLinks,
160
+ M as isActive,
161
+ U as isActiveSignal,
162
+ j as link,
163
+ P as navigate,
164
+ I as resolve
165
+ };
166
+ //# sourceMappingURL=router.es.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.es.mjs","sources":["../src/router/index.ts"],"sourcesContent":["/**\r\n * Minimal SPA router with History API integration.\r\n *\r\n * This module provides a lightweight, signal-based router for single-page\r\n * applications. Features include:\r\n * - History API navigation\r\n * - Route matching with params and wildcards\r\n * - Lazy route loading\r\n * - Navigation guards (beforeEach, afterEach)\r\n * - Reactive current route via signals\r\n * - Multi-value query params (e.g., `?tag=a&tag=b` → `{ tag: ['a', 'b'] }`)\r\n *\r\n * @module bquery/router\r\n *\r\n * @example\r\n * ```ts\r\n * import { createRouter, navigate, currentRoute } from 'bquery/router';\r\n * import { effect } from 'bquery/reactive';\r\n *\r\n * const router = createRouter({\r\n * routes: [\r\n * { path: '/', component: () => import('./Home') },\r\n * { path: '/user/:id', component: () => import('./User') },\r\n * { path: '*', component: () => import('./NotFound') },\r\n * ],\r\n * });\r\n *\r\n * effect(() => {\r\n * console.log('Route changed:', currentRoute.value);\r\n * });\r\n *\r\n * navigate('/user/42');\r\n * ```\r\n */\r\n\r\nimport { computed, signal, type ReadonlySignal, type Signal } from '../reactive/index';\r\n\r\n// ============================================================================\r\n// Types\r\n// ============================================================================\r\n\r\n/**\r\n * Represents a parsed route with matched params.\r\n */\r\nexport type Route = {\r\n /** The current path (e.g., '/user/42') */\r\n path: string;\r\n /** Extracted route params (e.g., { id: '42' }) */\r\n params: Record<string, string>;\r\n /**\r\n * Query string params.\r\n * Each key maps to a single string value by default.\r\n * Only keys that appear multiple times in the query string become arrays.\r\n * @example\r\n * // ?foo=1 → { foo: '1' }\r\n * // ?tag=a&tag=b → { tag: ['a', 'b'] }\r\n * // ?x=1&y=2&x=3 → { x: ['1', '3'], y: '2' }\r\n */\r\n query: Record<string, string | string[]>;\r\n /** The matched route definition */\r\n matched: RouteDefinition | null;\r\n /** Hash fragment without # */\r\n hash: string;\r\n};\r\n\r\n/**\r\n * Route definition for configuration.\r\n */\r\nexport type RouteDefinition = {\r\n /** Path pattern (e.g., '/user/:id', '/posts/*') */\r\n path: string;\r\n /** Component loader (sync or async) */\r\n component: () => unknown | Promise<unknown>;\r\n /** Optional route name for programmatic navigation */\r\n name?: string;\r\n /** Optional metadata */\r\n meta?: Record<string, unknown>;\r\n /** Nested child routes */\r\n children?: RouteDefinition[];\r\n};\r\n\r\n/**\r\n * Router configuration options.\r\n */\r\nexport type RouterOptions = {\r\n /** Array of route definitions */\r\n routes: RouteDefinition[];\r\n /** Base path for all routes (default: '') */\r\n base?: string;\r\n /** Use hash-based routing instead of history (default: false) */\r\n hash?: boolean;\r\n};\r\n\r\n/**\r\n * Navigation guard function type.\r\n */\r\nexport type NavigationGuard = (to: Route, from: Route) => boolean | void | Promise<boolean | void>;\r\n\r\n/**\r\n * Router instance returned by createRouter.\r\n */\r\nexport type Router = {\r\n /** Navigate to a path */\r\n push: (path: string) => Promise<void>;\r\n /** Replace current history entry */\r\n replace: (path: string) => Promise<void>;\r\n /** Go back in history */\r\n back: () => void;\r\n /** Go forward in history */\r\n forward: () => void;\r\n /** Go to a specific history entry */\r\n go: (delta: number) => void;\r\n /** Add a beforeEach guard */\r\n beforeEach: (guard: NavigationGuard) => () => void;\r\n /** Add an afterEach hook */\r\n afterEach: (hook: (to: Route, from: Route) => void) => () => void;\r\n /** Current route (reactive) */\r\n currentRoute: ReadonlySignal<Route>;\r\n /** All route definitions */\r\n routes: RouteDefinition[];\r\n /** Destroy the router and cleanup listeners */\r\n destroy: () => void;\r\n};\r\n\r\n// ============================================================================\r\n// Internal State\r\n// ============================================================================\r\n\r\n/** @internal */\r\nlet activeRouter: Router | null = null;\r\n\r\n/** @internal */\r\nconst routeSignal: Signal<Route> = signal<Route>({\r\n path: '',\r\n params: {},\r\n query: {},\r\n matched: null,\r\n hash: '',\r\n});\r\n\r\n/**\r\n * Reactive signal containing the current route.\r\n *\r\n * @example\r\n * ```ts\r\n * import { currentRoute } from 'bquery/router';\r\n * import { effect } from 'bquery/reactive';\r\n *\r\n * effect(() => {\r\n * document.title = `Page: ${currentRoute.value.path}`;\r\n * });\r\n * ```\r\n */\r\nexport const currentRoute: ReadonlySignal<Route> = computed(() => routeSignal.value);\r\n\r\n// ============================================================================\r\n// Route Matching\r\n// ============================================================================\r\n\r\n/**\r\n * Converts a route path pattern to a RegExp for matching.\r\n * Uses placeholder approach to preserve :param and * patterns during escaping.\r\n * @internal\r\n */\r\nconst pathToRegex = (path: string): RegExp => {\r\n // Handle wildcard-only route\r\n if (path === '*') {\r\n return /^.*$/;\r\n }\r\n\r\n // Unique placeholders using null chars (won't appear in normal paths)\r\n const PARAM_MARKER = '\\u0000P\\u0000';\r\n const WILDCARD_MARKER = '\\u0000W\\u0000';\r\n\r\n // Store param names for restoration\r\n const paramNames: string[] = [];\r\n\r\n // Step 1: Extract :param patterns before escaping\r\n let pattern = path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, name) => {\r\n paramNames.push(name);\r\n return PARAM_MARKER;\r\n });\r\n\r\n // Step 2: Extract * wildcards before escaping\r\n pattern = pattern.replace(/\\*/g, WILDCARD_MARKER);\r\n\r\n // Step 3: Escape ALL regex metacharacters: \\ ^ $ . * + ? ( ) [ ] { } |\r\n pattern = pattern.replace(/[\\\\^$.*+?()[\\]{}|]/g, '\\\\$&');\r\n\r\n // Step 4: Restore param capture groups\r\n let paramIdx = 0;\r\n pattern = pattern.replace(/\\u0000P\\u0000/g, () => `(?<${paramNames[paramIdx++]}>[^/]+)`);\r\n\r\n // Step 5: Restore wildcards as .*\r\n pattern = pattern.replace(/\\u0000W\\u0000/g, '.*');\r\n\r\n return new RegExp(`^${pattern}$`);\r\n};\r\n\r\n/**\r\n * Extracts param names from a route path.\r\n * @internal\r\n */\r\nconst extractParamNames = (path: string): string[] => {\r\n const matches = path.match(/:([a-zA-Z_][a-zA-Z0-9_]*)/g);\r\n return matches ? matches.map((m) => m.slice(1)) : [];\r\n};\r\n\r\n/**\r\n * Matches a path against route definitions and extracts params.\r\n * @internal\r\n */\r\nconst matchRoute = (\r\n path: string,\r\n routes: RouteDefinition[]\r\n): { matched: RouteDefinition; params: Record<string, string> } | null => {\r\n for (const route of routes) {\r\n const regex = pathToRegex(route.path);\r\n const match = path.match(regex);\r\n\r\n if (match) {\r\n const paramNames = extractParamNames(route.path);\r\n const params: Record<string, string> = {};\r\n\r\n // Extract named groups if available\r\n if (match.groups) {\r\n Object.assign(params, match.groups);\r\n } else {\r\n // Fallback for browsers without named groups\r\n paramNames.forEach((name, index) => {\r\n params[name] = match[index + 1] || '';\r\n });\r\n }\r\n\r\n return { matched: route, params };\r\n }\r\n }\r\n\r\n return null;\r\n};\r\n\r\n/**\r\n * Parses query string into an object.\r\n * Single values are stored as strings, duplicate keys become arrays.\r\n * @internal\r\n *\r\n * @example\r\n * parseQuery('?foo=1') // { foo: '1' }\r\n * parseQuery('?tag=a&tag=b') // { tag: ['a', 'b'] }\r\n * parseQuery('?x=1&y=2&x=3') // { x: ['1', '3'], y: '2' }\r\n */\r\nconst parseQuery = (search: string): Record<string, string | string[]> => {\r\n const query: Record<string, string | string[]> = {};\r\n const params = new URLSearchParams(search);\r\n\r\n params.forEach((value, key) => {\r\n const existing = query[key];\r\n if (existing === undefined) {\r\n // First occurrence: store as string\r\n query[key] = value;\r\n } else if (Array.isArray(existing)) {\r\n // Already an array: append\r\n existing.push(value);\r\n } else {\r\n // Second occurrence: convert to array\r\n query[key] = [existing, value];\r\n }\r\n });\r\n\r\n return query;\r\n};\r\n\r\n/**\r\n * Creates a Route object from the current URL.\r\n * @internal\r\n */\r\nconst createRoute = (\r\n pathname: string,\r\n search: string,\r\n hash: string,\r\n routes: RouteDefinition[]\r\n): Route => {\r\n const result = matchRoute(pathname, routes);\r\n\r\n return {\r\n path: pathname,\r\n params: result?.params ?? {},\r\n query: parseQuery(search),\r\n matched: result?.matched ?? null,\r\n hash: hash.replace(/^#/, ''),\r\n };\r\n};\r\n\r\n// ============================================================================\r\n// Navigation\r\n// ============================================================================\r\n\r\n/**\r\n * Navigates to a new path.\r\n *\r\n * @param path - The path to navigate to\r\n * @param options - Navigation options\r\n *\r\n * @example\r\n * ```ts\r\n * import { navigate } from 'bquery/router';\r\n *\r\n * // Push to history\r\n * await navigate('/dashboard');\r\n *\r\n * // Replace current entry\r\n * await navigate('/login', { replace: true });\r\n * ```\r\n */\r\nexport const navigate = async (\r\n path: string,\r\n options: { replace?: boolean } = {}\r\n): Promise<void> => {\r\n if (!activeRouter) {\r\n throw new Error('bQuery router: No router initialized. Call createRouter() first.');\r\n }\r\n\r\n await activeRouter[options.replace ? 'replace' : 'push'](path);\r\n};\r\n\r\n/**\r\n * Programmatically go back in history.\r\n *\r\n * @example\r\n * ```ts\r\n * import { back } from 'bquery/router';\r\n * back();\r\n * ```\r\n */\r\nexport const back = (): void => {\r\n if (activeRouter) {\r\n activeRouter.back();\r\n } else {\r\n history.back();\r\n }\r\n};\r\n\r\n/**\r\n * Programmatically go forward in history.\r\n *\r\n * @example\r\n * ```ts\r\n * import { forward } from 'bquery/router';\r\n * forward();\r\n * ```\r\n */\r\nexport const forward = (): void => {\r\n if (activeRouter) {\r\n activeRouter.forward();\r\n } else {\r\n history.forward();\r\n }\r\n};\r\n\r\n// ============================================================================\r\n// Router Creation\r\n// ============================================================================\r\n\r\n/**\r\n * Creates and initializes a router instance.\r\n *\r\n * @param options - Router configuration\r\n * @returns The router instance\r\n *\r\n * @example\r\n * ```ts\r\n * import { createRouter } from 'bquery/router';\r\n *\r\n * const router = createRouter({\r\n * routes: [\r\n * { path: '/', component: () => import('./pages/Home') },\r\n * { path: '/about', component: () => import('./pages/About') },\r\n * { path: '/user/:id', component: () => import('./pages/User') },\r\n * { path: '*', component: () => import('./pages/NotFound') },\r\n * ],\r\n * base: '/app',\r\n * });\r\n *\r\n * router.beforeEach((to, from) => {\r\n * if (to.path === '/admin' && !isAuthenticated()) {\r\n * return false; // Cancel navigation\r\n * }\r\n * });\r\n * ```\r\n */\r\nexport const createRouter = (options: RouterOptions): Router => {\r\n // Clean up any existing router to prevent guard leakage\r\n if (activeRouter) {\r\n activeRouter.destroy();\r\n }\r\n\r\n const { routes, base = '', hash: useHash = false } = options;\r\n\r\n // Instance-specific guards and hooks (not shared globally)\r\n const beforeGuards: NavigationGuard[] = [];\r\n const afterHooks: Array<(to: Route, from: Route) => void> = [];\r\n\r\n // Flatten nested routes\r\n const flatRoutes = flattenRoutes(routes, base);\r\n\r\n /**\r\n * Gets the current path from the URL.\r\n */\r\n const getCurrentPath = (): { pathname: string; search: string; hash: string } => {\r\n if (useHash) {\r\n const hashPath = window.location.hash.slice(1) || '/';\r\n const [pathname, rest = ''] = hashPath.split('?');\r\n const [search, hashPart = ''] = rest.split('#');\r\n return {\r\n pathname,\r\n search: search ? `?${search}` : '',\r\n hash: hashPart ? `#${hashPart}` : '',\r\n };\r\n }\r\n\r\n let pathname = window.location.pathname;\r\n if (base && pathname.startsWith(base)) {\r\n pathname = pathname.slice(base.length) || '/';\r\n }\r\n\r\n return {\r\n pathname,\r\n search: window.location.search,\r\n hash: window.location.hash,\r\n };\r\n };\r\n\r\n /**\r\n * Updates the route signal with current URL state.\r\n */\r\n const syncRoute = (): void => {\r\n const { pathname, search, hash } = getCurrentPath();\r\n const newRoute = createRoute(pathname, search, hash, flatRoutes);\r\n routeSignal.value = newRoute;\r\n };\r\n\r\n /**\r\n * Performs navigation with guards.\r\n */\r\n const performNavigation = async (\r\n path: string,\r\n method: 'pushState' | 'replaceState'\r\n ): Promise<void> => {\r\n const { pathname, search, hash } = getCurrentPath();\r\n const from = createRoute(pathname, search, hash, flatRoutes);\r\n\r\n // Parse the target path\r\n const url = new URL(path, window.location.origin);\r\n const toPath = useHash ? path : url.pathname;\r\n const to = createRoute(toPath, url.search, url.hash, flatRoutes);\r\n\r\n // Run beforeEach guards\r\n for (const guard of beforeGuards) {\r\n const result = await guard(to, from);\r\n if (result === false) {\r\n return; // Cancel navigation\r\n }\r\n }\r\n\r\n // Update browser history\r\n const fullPath = useHash ? `#${path}` : `${base}${path}`;\r\n history[method]({}, '', fullPath);\r\n\r\n // Update route signal\r\n syncRoute();\r\n\r\n // Run afterEach hooks\r\n for (const hook of afterHooks) {\r\n hook(routeSignal.value, from);\r\n }\r\n };\r\n\r\n /**\r\n * Handle popstate events (back/forward).\r\n */\r\n const handlePopState = async (): Promise<void> => {\r\n const { pathname, search, hash } = getCurrentPath();\r\n const from = routeSignal.value;\r\n const to = createRoute(pathname, search, hash, flatRoutes);\r\n\r\n // Run beforeEach guards (supports async guards)\r\n for (const guard of beforeGuards) {\r\n const result = await guard(to, from);\r\n if (result === false) {\r\n // Restore previous state\r\n const restorePath = useHash ? `#${from.path}` : `${base}${from.path}`;\r\n history.pushState({}, '', restorePath);\r\n return;\r\n }\r\n }\r\n\r\n syncRoute();\r\n\r\n for (const hook of afterHooks) {\r\n hook(routeSignal.value, from);\r\n }\r\n };\r\n\r\n // Attach popstate listener\r\n window.addEventListener('popstate', handlePopState);\r\n\r\n // Initialize route\r\n syncRoute();\r\n\r\n const router: Router = {\r\n push: (path: string) => performNavigation(path, 'pushState'),\r\n replace: (path: string) => performNavigation(path, 'replaceState'),\r\n back: () => history.back(),\r\n forward: () => history.forward(),\r\n go: (delta: number) => history.go(delta),\r\n\r\n beforeEach: (guard: NavigationGuard) => {\r\n beforeGuards.push(guard);\r\n return () => {\r\n const index = beforeGuards.indexOf(guard);\r\n if (index > -1) beforeGuards.splice(index, 1);\r\n };\r\n },\r\n\r\n afterEach: (hook: (to: Route, from: Route) => void) => {\r\n afterHooks.push(hook);\r\n return () => {\r\n const index = afterHooks.indexOf(hook);\r\n if (index > -1) afterHooks.splice(index, 1);\r\n };\r\n },\r\n\r\n currentRoute,\r\n routes: flatRoutes,\r\n\r\n destroy: () => {\r\n window.removeEventListener('popstate', handlePopState);\r\n beforeGuards.length = 0;\r\n afterHooks.length = 0;\r\n activeRouter = null;\r\n },\r\n };\r\n\r\n activeRouter = router;\r\n return router;\r\n};\r\n\r\n// ============================================================================\r\n// Utilities\r\n// ============================================================================\r\n\r\n/**\r\n * Flattens nested routes into a single array with full paths.\r\n * @internal\r\n */\r\nconst flattenRoutes = (routes: RouteDefinition[], base = ''): RouteDefinition[] => {\r\n const result: RouteDefinition[] = [];\r\n\r\n for (const route of routes) {\r\n const fullPath = route.path === '*' ? '*' : `${base}${route.path}`.replace(/\\/+/g, '/');\r\n\r\n result.push({\r\n ...route,\r\n path: fullPath,\r\n });\r\n\r\n if (route.children) {\r\n result.push(...flattenRoutes(route.children, fullPath));\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n\r\n/**\r\n * Resolves a route by name and params.\r\n *\r\n * @param name - The route name\r\n * @param params - Route params to interpolate\r\n * @returns The resolved path\r\n *\r\n * @example\r\n * ```ts\r\n * import { resolve } from 'bquery/router';\r\n *\r\n * const path = resolve('user', { id: '42' });\r\n * // Returns '/user/42' if route is defined as { name: 'user', path: '/user/:id' }\r\n * ```\r\n */\r\nexport const resolve = (name: string, params: Record<string, string> = {}): string => {\r\n if (!activeRouter) {\r\n throw new Error('bQuery router: No router initialized.');\r\n }\r\n\r\n const route = activeRouter.routes.find((r) => r.name === name);\r\n if (!route) {\r\n throw new Error(`bQuery router: Route \"${name}\" not found.`);\r\n }\r\n\r\n let path = route.path;\r\n for (const [key, value] of Object.entries(params)) {\r\n path = path.replace(`:${key}`, encodeURIComponent(value));\r\n }\r\n\r\n return path;\r\n};\r\n\r\n/**\r\n * Checks if a path matches the current route.\r\n *\r\n * @param path - Path to check\r\n * @param exact - Whether to match exactly (default: false)\r\n * @returns True if the path matches\r\n *\r\n * @example\r\n * ```ts\r\n * import { isActive } from 'bquery/router';\r\n *\r\n * if (isActive('/dashboard')) {\r\n * // Highlight nav item\r\n * }\r\n * ```\r\n */\r\nexport const isActive = (path: string, exact = false): boolean => {\r\n const current = routeSignal.value.path;\r\n return exact ? current === path : current.startsWith(path);\r\n};\r\n\r\n/**\r\n * Creates a computed signal that checks if a path is active.\r\n *\r\n * @param path - Path to check\r\n * @param exact - Whether to match exactly\r\n * @returns A reactive signal\r\n *\r\n * @example\r\n * ```ts\r\n * import { isActiveSignal } from 'bquery/router';\r\n * import { effect } from 'bquery/reactive';\r\n *\r\n * const dashboardActive = isActiveSignal('/dashboard');\r\n * effect(() => {\r\n * navItem.classList.toggle('active', dashboardActive.value);\r\n * });\r\n * ```\r\n */\r\nexport const isActiveSignal = (path: string, exact = false): ReadonlySignal<boolean> => {\r\n return computed(() => {\r\n const current = routeSignal.value.path;\r\n return exact ? current === path : current.startsWith(path);\r\n });\r\n};\r\n\r\n// ============================================================================\r\n// Router Link Helper\r\n// ============================================================================\r\n\r\n/**\r\n * Creates click handler for router links.\r\n * Attach to anchor elements to enable client-side navigation.\r\n *\r\n * @param path - Target path\r\n * @param options - Navigation options\r\n * @returns Click event handler\r\n *\r\n * @example\r\n * ```ts\r\n * import { link } from 'bquery/router';\r\n * import { $ } from 'bquery/core';\r\n *\r\n * $('#nav-home').on('click', link('/'));\r\n * $('#nav-about').on('click', link('/about'));\r\n * ```\r\n */\r\nexport const link = (path: string, options: { replace?: boolean } = {}): ((e: Event) => void) => {\r\n return (e: Event) => {\r\n e.preventDefault();\r\n navigate(path, options);\r\n };\r\n};\r\n\r\n/**\r\n * Intercepts all link clicks within a container for client-side routing.\r\n * Only intercepts links with matching origins and no target attribute.\r\n *\r\n * @param container - The container element to intercept links in\r\n * @returns Cleanup function to remove the listener\r\n *\r\n * @example\r\n * ```ts\r\n * import { interceptLinks } from 'bquery/router';\r\n *\r\n * // Intercept all links in the app\r\n * const cleanup = interceptLinks(document.body);\r\n *\r\n * // Later, remove the interceptor\r\n * cleanup();\r\n * ```\r\n */\r\nexport const interceptLinks = (container: Element = document.body): (() => void) => {\r\n const handler = (e: Event) => {\r\n const target = e.target as HTMLElement;\r\n const anchor = target.closest('a');\r\n\r\n if (!anchor) return;\r\n if (anchor.target) return; // Has target attribute\r\n if (anchor.hasAttribute('download')) return;\r\n if (anchor.origin !== window.location.origin) return; // External link\r\n\r\n const path = anchor.pathname + anchor.search + anchor.hash;\r\n\r\n e.preventDefault();\r\n navigate(path);\r\n };\r\n\r\n container.addEventListener('click', handler);\r\n return () => container.removeEventListener('click', handler);\r\n};\r\n"],"names":["activeRouter","routeSignal","signal","currentRoute","computed","pathToRegex","path","PARAM_MARKER","WILDCARD_MARKER","paramNames","pattern","_","name","paramIdx","extractParamNames","matches","m","matchRoute","routes","route","regex","match","params","index","parseQuery","search","query","value","key","existing","createRoute","pathname","hash","result","navigate","options","back","forward","createRouter","base","useHash","beforeGuards","afterHooks","flatRoutes","flattenRoutes","getCurrentPath","hashPath","rest","hashPart","syncRoute","newRoute","performNavigation","method","from","url","toPath","to","guard","fullPath","hook","handlePopState","restorePath","router","delta","resolve","r","isActive","exact","current","isActiveSignal","link","interceptLinks","container","handler","anchor"],"mappings":";AAiIA,IAAIA,IAA8B;AAGlC,MAAMC,IAA6BC,EAAc;AAAA,EAC/C,MAAM;AAAA,EACN,QAAQ,CAAA;AAAA,EACR,OAAO,CAAA;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AACR,CAAC,GAeYC,IAAsCC,EAAS,MAAMH,EAAY,KAAK,GAW7EI,IAAc,CAACC,MAAyB;AAE5C,MAAIA,MAAS;AACX,WAAO;AAIT,QAAMC,IAAe,SACfC,IAAkB,SAGlBC,IAAuB,CAAA;AAG7B,MAAIC,IAAUJ,EAAK,QAAQ,8BAA8B,CAACK,GAAGC,OAC3DH,EAAW,KAAKG,CAAI,GACbL,EACR;AAGD,EAAAG,IAAUA,EAAQ,QAAQ,OAAOF,CAAe,GAGhDE,IAAUA,EAAQ,QAAQ,uBAAuB,MAAM;AAGvD,MAAIG,IAAW;AACf,SAAAH,IAAUA,EAAQ,QAAQ,kBAAkB,MAAM,MAAMD,EAAWI,GAAU,CAAC,SAAS,GAGvFH,IAAUA,EAAQ,QAAQ,kBAAkB,IAAI,GAEzC,IAAI,OAAO,IAAIA,CAAO,GAAG;AAClC,GAMMI,IAAoB,CAACR,MAA2B;AACpD,QAAMS,IAAUT,EAAK,M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al state management built on signals.
3
+ *
4
+ * This module provides a lightweight store pattern inspired by Pinia/Vuex
5
+ * but built entirely on bQuery's reactive primitives. Features include:
6
+ * - Signal-based reactive state
7
+ * - Computed getters
8
+ * - Actions with async support
9
+ * - Devtools hooks for debugging
10
+ * - Plugin system for extensions
11
+ *
12
+ * @module bquery/store
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { createStore } from 'bquery/store';
17
+ * import { effect } from 'bquery/reactive';
18
+ *
19
+ * const counterStore = createStore({
20
+ * id: 'counter',
21
+ * state: () => ({ count: 0 }),
22
+ * getters: {
23
+ * doubled: (state) => state.count * 2,
24
+ * isPositive: (state) => state.count > 0,
25
+ * },
26
+ * actions: {
27
+ * increment() {
28
+ * this.count++;
29
+ * },
30
+ * async fetchAndSet(url: string) {
31
+ * const response = await fetch(url);
32
+ * const data = await response.json();
33
+ * this.count = data.count;
34
+ * },
35
+ * },
36
+ * });
37
+ *
38
+ * effect(() => {
39
+ * console.log('Count:', counterStore.count);
40
+ * console.log('Doubled:', counterStore.doubled);
41
+ * });
42
+ *
43
+ * counterStore.increment();
44
+ * ```
45
+ */
46
+ /**
47
+ * Store state factory function.
48
+ */
49
+ export type StateFactory<S> = () => S;
50
+ /**
51
+ * Getter definition - derives computed values from state.
52
+ */
53
+ export type Getters<S, G> = {
54
+ [K in keyof G]: (state: S, getters: G) => G[K];
55
+ };
56
+ /**
57
+ * Action definition - methods that can modify state.
58
+ */
59
+ export type Actions<S, A> = {
60
+ [K in keyof A]: A[K] extends (...args: infer P) => infer R ? (this: S & A, ...args: P) => R : never;
61
+ };
62
+ /**
63
+ * Store definition for createStore.
64
+ */
65
+ export type StoreDefinition<S extends Record<string, unknown> = Record<string, unknown>, G extends Record<string, unknown> = Record<string, unknown>, A extends Record<string, (...args: any[]) => any> = Record<string, never>> = {
66
+ /** Unique store identifier for devtools */
67
+ id: string;
68
+ /** State factory function */
69
+ state: StateFactory<S>;
70
+ /** Computed getters */
71
+ getters?: Getters<S, G>;
72
+ /** Action methods */
73
+ actions?: A;
74
+ };
75
+ /**
76
+ * The returned store instance with state, getters, and actions merged.
77
+ */
78
+ export type Store<S extends Record<string, unknown>, G extends Record<string, unknown>, A extends Record<string, (...args: any[]) => any>> = S & G & A & {
79
+ /** Store identifier */
80
+ $id: string;
81
+ /** Reset state to initial values */
82
+ $reset: () => void;
83
+ /** Subscribe to state changes */
84
+ $subscribe: (callback: (state: S) => void) => () => void;
85
+ /** Patch multiple state properties at once (shallow) */
86
+ $patch: (partial: Partial<S> | ((state: S) => void)) => void;
87
+ /**
88
+ * Patch with deep reactivity support.
89
+ * Unlike $patch, this method deep-clones nested objects before mutation,
90
+ * ensuring that all changes trigger reactive updates.
91
+ */
92
+ $patchDeep: (partial: Partial<S> | ((state: S) => void)) => void;
93
+ /** Get raw state object (non-reactive snapshot) */
94
+ $state: S;
95
+ };
96
+ /**
97
+ * Plugin that can extend store functionality.
98
+ */
99
+ export type StorePlugin<S = unknown> = (context: {
100
+ store: Store<any, any, any>;
101
+ options: StoreDefinition<any, any, any>;
102
+ }) => Partial<S> | void;
103
+ /** @internal Devtools hook */
104
+ declare global {
105
+ interface Window {
106
+ __BQUERY_DEVTOOLS__?: {
107
+ stores: Map<string, unknown>;
108
+ onStoreCreated?: (id: string, store: unknown) => void;
109
+ onStateChange?: (id: string, state: unknown) => void;
110
+ };
111
+ }
112
+ }
113
+ /**
114
+ * Creates a reactive store with state, getters, and actions.
115
+ *
116
+ * @template S - State type
117
+ * @template G - Getters type
118
+ * @template A - Actions type
119
+ * @param definition - Store definition
120
+ * @returns The reactive store instance
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * import { createStore } from 'bquery/store';
125
+ *
126
+ * // Simple counter store
127
+ * const useCounter = createStore({
128
+ * id: 'counter',
129
+ * state: () => ({ count: 0, step: 1 }),
130
+ * getters: {
131
+ * doubled: (state) => state.count * 2,
132
+ * next: (state) => state.count + state.step,
133
+ * },
134
+ * actions: {
135
+ * increment() {
136
+ * this.count += this.step;
137
+ * },
138
+ * decrement() {
139
+ * this.count -= this.step;
140
+ * },
141
+ * setStep(newStep: number) {
142
+ * this.step = newStep;
143
+ * },
144
+ * async loadFromServer() {
145
+ * const res = await fetch('/api/counter');
146
+ * const data = await res.json();
147
+ * this.count = data.count;
148
+ * },
149
+ * },
150
+ * });
151
+ *
152
+ * // Use the store
153
+ * useCounter.increment();
154
+ * console.log(useCounter.count); // 1
155
+ * console.log(useCounter.doubled); // 2
156
+ * ```
157
+ */
158
+ export declare const createStore: <S extends Record<string, unknown>, G extends Record<string, unknown> = Record<string, never>, A extends Record<string, (...args: any[]) => any> = Record<string, never>>(definition: StoreDefinition<S, G, A>) => Store<S, G, A>;
159
+ /**
160
+ * Retrieves an existing store by its ID.
161
+ *
162
+ * @param id - The store identifier
163
+ * @returns The store instance or undefined if not found
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * import { getStore } from 'bquery/store';
168
+ *
169
+ * const counter = getStore('counter');
170
+ * if (counter) {
171
+ * counter.increment();
172
+ * }
173
+ * ```
174
+ */
175
+ export declare const getStore: <T = unknown>(id: string) => T | undefined;
176
+ /**
177
+ * Lists all registered store IDs.
178
+ *
179
+ * @returns Array of store IDs
180
+ *
181
+ * @example
182
+ * ```ts
183
+ * import { listStores } from 'bquery/store';
184
+ *
185
+ * console.log('Active stores:', listStores());
186
+ * ```
187
+ */
188
+ export declare const listStores: () => string[];
189
+ /**
190
+ * Removes a store from the registry.
191
+ *
192
+ * @param id - The store identifier
193
+ *
194
+ * @example
195
+ * ```ts
196
+ * import { destroyStore } from 'bquery/store';
197
+ *
198
+ * destroyStore('counter');
199
+ * ```
200
+ */
201
+ export declare const destroyStore: (id: string) => void;
202
+ /**
203
+ * Registers a plugin that extends all stores.
204
+ *
205
+ * @param plugin - The plugin function
206
+ *
207
+ * @example
208
+ * ```ts
209
+ * import { registerPlugin } from 'bquery/store';
210
+ *
211
+ * // Add localStorage persistence
212
+ * registerPlugin(({ store, options }) => {
213
+ * const key = `bquery-store-${options.id}`;
214
+ *
215
+ * // Load saved state
216
+ * const saved = localStorage.getItem(key);
217
+ * if (saved) {
218
+ * store.$patch(JSON.parse(saved));
219
+ * }
220
+ *
221
+ * // Save on changes
222
+ * store.$subscribe((state) => {
223
+ * localStorage.setItem(key, JSON.stringify(state));
224
+ * });
225
+ * });
226
+ * ```
227
+ */
228
+ export declare const registerPlugin: (plugin: StorePlugin) => void;
229
+ /**
230
+ * Creates a store with automatic persistence to localStorage.
231
+ *
232
+ * @param definition - Store definition
233
+ * @param storageKey - Optional custom storage key
234
+ * @returns The reactive store instance
235
+ *
236
+ * @example
237
+ * ```ts
238
+ * import { createPersistedStore } from 'bquery/store';
239
+ *
240
+ * const settings = createPersistedStore({
241
+ * id: 'settings',
242
+ * state: () => ({
243
+ * theme: 'dark',
244
+ * language: 'en',
245
+ * }),
246
+ * });
247
+ *
248
+ * // State is automatically saved/loaded from localStorage
249
+ * settings.theme = 'light';
250
+ * ```
251
+ */
252
+ export declare const createPersistedStore: <S extends Record<string, unknown>, G extends Record<string, unknown> = Record<string, never>, A extends Record<string, (...args: unknown[]) => unknown> = Record<string, never>>(definition: StoreDefinition<S, G, A>, storageKey?: string) => Store<S, G, A>;
253
+ /**
254
+ * Maps store state properties to a reactive object for use in components.
255
+ *
256
+ * @param store - The store instance
257
+ * @param keys - State keys to map
258
+ * @returns Object with mapped properties
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * import { mapState } from 'bquery/store';
263
+ *
264
+ * const counter = useCounter();
265
+ * const { count, step } = mapState(counter, ['count', 'step']);
266
+ * ```
267
+ */
268
+ export declare const mapState: <S extends Record<string, unknown>, K extends keyof S>(store: S, keys: K[]) => Pick<S, K>;
269
+ /**
270
+ * Maps store actions to an object for easier destructuring.
271
+ *
272
+ * @param store - The store instance
273
+ * @param keys - Action keys to map
274
+ * @returns Object with mapped actions
275
+ *
276
+ * @example
277
+ * ```ts
278
+ * import { mapActions } from 'bquery/store';
279
+ *
280
+ * const counter = useCounter();
281
+ * const { increment, decrement } = mapActions(counter, ['increment', 'decrement']);
282
+ *
283
+ * // Use directly
284
+ * increment();
285
+ * ```
286
+ */
287
+ export declare const mapActions: <A extends Record<string, (...args: unknown[]) => unknown>, K extends keyof A>(store: A, keys: K[]) => Pick<A, K>;
288
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AAQH;;GAEG;AACH,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC;AAEtC;;GAEG;AACH,MAAM,MAAM,OAAO,CAAC,CAAC,EAAE,CAAC,IAAI;KACzB,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;CAC/C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,OAAO,CAAC,CAAC,EAAE,CAAC,IAAI;KACzB,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,MAAM,CAAC,GACtD,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,CAAC,GAC9B,KAAK;CACV,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,eAAe,CACzB,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC3D,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAE3D,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,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