@seip/bluebird-js 0.1.6 → 0.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.
Files changed (152) hide show
  1. package/.vscode/extensions.json +7 -7
  2. package/.vscode/settings.json +10 -10
  3. package/AGENTS.md +266 -116
  4. package/README.md +258 -245
  5. package/app/models/user.js +19 -0
  6. package/app/resources/html/home.html +137 -0
  7. package/app/resources/html/layouts/main.html +54 -0
  8. package/app/resources/html/notFound.html +14 -0
  9. package/app/resources/html/terms.html +46 -0
  10. package/app/resources/index.html +27 -0
  11. package/app/resources/layouts/AppLayout.jsx +89 -0
  12. package/app/resources/main.jsx +18 -0
  13. package/app/resources/pages/Dashboard.jsx +98 -0
  14. package/app/resources/pages/Home.jsx +140 -0
  15. package/app/resources/pages/Login.jsx +35 -0
  16. package/app/resources/pages/NotFound.jsx +16 -0
  17. package/app/resources/pages/Register.jsx +55 -0
  18. package/app/resources/routes.jsx +54 -0
  19. package/app/resources/spa.js +67 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +85 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +49 -37
  24. package/core/ai.d.ts +151 -151
  25. package/core/ai.js +1071 -1051
  26. package/core/app.d.ts +2 -18
  27. package/core/app.js +978 -792
  28. package/core/auth.d.ts +2 -13
  29. package/core/auth.js +444 -326
  30. package/core/cli/backup.js +167 -167
  31. package/core/cli/build.js +37 -0
  32. package/core/cli/dev.js +155 -0
  33. package/core/cli/doctor.js +37 -2
  34. package/core/cli/export.js +191 -0
  35. package/core/cli/init.js +101 -332
  36. package/core/cli/nginx.js +1 -1
  37. package/core/cli/templates.js +139 -0
  38. package/core/cli/view.js +73 -136
  39. package/core/config.js +44 -2
  40. package/core/csrf.js +156 -24
  41. package/core/database.js +737 -684
  42. package/core/debug.js +1 -1
  43. package/core/html.js +8 -1
  44. package/core/index.d.ts +1286 -1431
  45. package/core/paths.js +55 -0
  46. package/core/ratelimit.js +10 -1
  47. package/core/react/client/api.js +237 -0
  48. package/core/react/client/auth.js +236 -0
  49. package/core/react/client/components.js +1321 -0
  50. package/core/react/client/i18n.js +338 -0
  51. package/core/react/client/index.d.ts +249 -0
  52. package/core/react/client/index.js +49 -0
  53. package/core/react/client/router.js +26 -0
  54. package/core/react/client/theme.css +512 -0
  55. package/core/render-cache.js +250 -212
  56. package/core/render.d.ts +25 -21
  57. package/core/render.js +613 -603
  58. package/core/router.d.ts +2 -3
  59. package/core/router.js +171 -171
  60. package/core/seo.js +10 -0
  61. package/core/spa.js +599 -0
  62. package/core/view-loader.js +81 -455
  63. package/core/vite-plugin.d.ts +18 -0
  64. package/core/vite-plugin.js +162 -0
  65. package/core/vite.js +250 -145
  66. package/index.js +22 -18
  67. package/jsconfig.json +5 -3
  68. package/package.json +114 -92
  69. package/production.md +8 -3
  70. package/public/js/bluebird.js +1160 -0
  71. package/templates/_auth/app/database.js +19 -0
  72. package/templates/_auth/app/models/user.js +22 -0
  73. package/templates/_auth/app/routes/auth-router.js +304 -0
  74. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  75. package/templates/_base/app/resources/html/notFound.html +14 -0
  76. package/templates/_base/app/resources/index.html +27 -0
  77. package/templates/_base/app/resources/styles.css +9 -0
  78. package/templates/api/app/models/note.js +18 -0
  79. package/templates/api/app/routes/api.js +82 -0
  80. package/templates/api/app/routes/auth.js +11 -0
  81. package/templates/api/index.js +19 -0
  82. package/templates/api/template.json +13 -0
  83. package/templates/auth/app/mail.js +11 -0
  84. package/templates/auth/app/models/password_reset.js +18 -0
  85. package/templates/auth/app/resources/html/home.html +21 -0
  86. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  87. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  88. package/templates/auth/app/resources/main.jsx +18 -0
  89. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  90. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  91. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  92. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  93. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  94. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  95. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  96. package/templates/auth/app/resources/routes.jsx +54 -0
  97. package/templates/auth/app/resources/spa.js +29 -0
  98. package/templates/auth/app/routes/api.js +17 -0
  99. package/templates/auth/app/routes/auth.js +13 -0
  100. package/templates/auth/app/routes/web.js +21 -0
  101. package/templates/auth/index.js +19 -0
  102. package/templates/auth/template.json +15 -0
  103. package/templates/blank/app/models/.gitkeep +0 -0
  104. package/templates/blank/app/resources/html/home.html +27 -0
  105. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  106. package/templates/blank/app/resources/main.jsx +16 -0
  107. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  108. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  109. package/templates/blank/app/resources/routes.jsx +15 -0
  110. package/templates/blank/app/resources/spa.js +24 -0
  111. package/templates/blank/app/routes/api.js +11 -0
  112. package/templates/blank/app/routes/web.js +21 -0
  113. package/templates/blank/index.js +13 -0
  114. package/templates/blank/template.json +12 -0
  115. package/templates/blog/app/lib/blog.js +149 -0
  116. package/templates/blog/app/models/post.js +22 -0
  117. package/templates/blog/app/resources/html/home.html +28 -0
  118. package/templates/blog/app/resources/html/not-found.html +5 -0
  119. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  120. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  121. package/templates/blog/app/resources/html/post.html +8 -0
  122. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  123. package/templates/blog/app/resources/main.jsx +18 -0
  124. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  125. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  126. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  127. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  128. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  129. package/templates/blog/app/resources/routes.jsx +51 -0
  130. package/templates/blog/app/resources/spa.js +25 -0
  131. package/templates/blog/app/resources/styles.css +40 -0
  132. package/templates/blog/app/routes/api.js +77 -0
  133. package/templates/blog/app/routes/auth.js +10 -0
  134. package/templates/blog/app/routes/web.js +114 -0
  135. package/templates/blog/index.js +21 -0
  136. package/templates/blog/template.json +14 -0
  137. package/vite.config.js +11 -0
  138. package/app/views/about.jsx +0 -98
  139. package/app/views/components/Header.jsx +0 -42
  140. package/app/views/components/LiveCounter.jsx +0 -66
  141. package/app/views/dashboard.jsx +0 -300
  142. package/app/views/index.jsx +0 -123
  143. package/app/views/layouts/main/view.jsx +0 -201
  144. package/app/views/legal/terms.html +0 -29
  145. package/app/views/login.jsx +0 -141
  146. package/core/actions.d.ts +0 -4
  147. package/core/actions.js +0 -329
  148. package/core/jsx.d.ts +0 -38
  149. package/core/jsx.js +0 -1432
  150. package/core/vite.d.ts +0 -3
  151. package/public/js/bluebird-client.js +0 -3161
  152. package/public/js/tailwind.js +0 -8
package/core/paths.js ADDED
@@ -0,0 +1,55 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /**
5
+ * Conventional project-relative locations of client-side resources.
6
+ * - `resources`: React SPA sources, `index.html` shell, and `styles.css`.
7
+ * - `html`: HTML `{{ }}` SSR views, `layouts/`, and `partials/` rendered by `Render`.
8
+ * - `spaTemplate`: default `router.spa()` / `npx bluebird-js export` HTML shell.
9
+ */
10
+ export const PATHS = {
11
+ resources: "app/resources",
12
+ html: "app/resources/html",
13
+ spaTemplate: "app/resources/index.html",
14
+ spaConfig: "app/resources/spa.js",
15
+ entries: [
16
+ "app/resources/main.jsx",
17
+ "app/resources/main.tsx",
18
+ "app/resources/main.js",
19
+ "app/resources/main.ts",
20
+ ],
21
+ styles: ["app/resources/styles.css", "app/resources/css/app.css"],
22
+ };
23
+
24
+ /**
25
+ * Returns the first project-relative path from `candidates` that exists under `root`.
26
+ * @param {string} root
27
+ * @param {string[]} candidates
28
+ * @returns {string|null}
29
+ */
30
+ export function findFirst(root, candidates) {
31
+ for (const rel of candidates) {
32
+ if (fs.existsSync(path.join(root, rel))) return rel;
33
+ }
34
+ return null;
35
+ }
36
+
37
+ /**
38
+ * Resolves the default React SPA entry (`app/resources/main.jsx`, `.tsx`, `.js`, or `.ts`).
39
+ * @param {string} root
40
+ * @returns {string|null}
41
+ */
42
+ export function defaultEntry(root) {
43
+ return findFirst(root, PATHS.entries);
44
+ }
45
+
46
+ /**
47
+ * Resolves the default Tailwind CSS entry (`app/resources/styles.css`).
48
+ * @param {string} root
49
+ * @returns {string|null}
50
+ */
51
+ export function defaultStyles(root) {
52
+ return findFirst(root, PATHS.styles);
53
+ }
54
+
55
+ export default PATHS;
package/core/ratelimit.js CHANGED
@@ -7,6 +7,13 @@ import { getRedisClient } from "./cache.js";
7
7
  */
8
8
  const memoryBuckets = new Map();
9
9
 
10
+ /**
11
+ * Monotonic counter used to isolate the buckets of each limiter instance, so a global limiter
12
+ * and a per-route limiter never share (and double count) the same client key.
13
+ * @type {number}
14
+ */
15
+ let limiterInstanceCounter = 0;
16
+
10
17
  setInterval(() => {
11
18
  if (memoryBuckets.size === 0) return;
12
19
  const now = Date.now();
@@ -32,6 +39,7 @@ class RateLimit {
32
39
  * @param {"memory"|"redis"} [options.driver="memory"] - Storage backend.
33
40
  * @param {Function} [options.keyGenerator] - Custom key generator: (req) => string.
34
41
  * @param {Function} [options.skip] - Predicate to bypass rate limiting: (req) => boolean.
42
+ * @param {string} [options.prefix] - Bucket namespace (defaults to a deterministic per-instance id).
35
43
  * @returns {Function} Express middleware function.
36
44
  */
37
45
  static middleware(options = {}) {
@@ -46,13 +54,14 @@ class RateLimit {
46
54
  ? options.keyGenerator
47
55
  : (req) => req.ip || req.socket?.remoteAddress || "unknown";
48
56
  const skip = typeof options.skip === "function" ? options.skip : null;
57
+ const prefix = options.prefix ?? `i${++limiterInstanceCounter}`;
49
58
 
50
59
  return async (req, res, next) => {
51
60
  if (skip && skip(req)) {
52
61
  return next();
53
62
  }
54
63
 
55
- const clientKey = `rl:${keyGenerator(req)}`;
64
+ const clientKey = `rl:${prefix}:${keyGenerator(req)}`;
56
65
  const now = Date.now();
57
66
  let count = 0;
58
67
  let resetTime = now + windowMs;
@@ -0,0 +1,237 @@
1
+ import { t as translate } from "./i18n.js";
2
+
3
+ const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
4
+
5
+ /**
6
+ * Build-time configuration injected by `npx bluebird-js export` (`null` on the web server build).
7
+ * @type {{ apiUrl?: string, router?: "hash"|"browser"|"memory", basename?: string, auth?: "token"|"cookie" }|null}
8
+ */
9
+ const EXPORT_CONFIG = typeof __BLUEBIRD_EXPORT__ !== "undefined" ? __BLUEBIRD_EXPORT__ : null;
10
+
11
+ const TOKEN_STORAGE_KEY = "bb-auth-token";
12
+
13
+ let apiBaseUrl = String(EXPORT_CONFIG?.apiUrl || "").replace(/\/+$/, "");
14
+ let authMode = EXPORT_CONFIG ? EXPORT_CONFIG.auth || "token" : "cookie";
15
+ let memoryToken = "";
16
+
17
+ /**
18
+ * Returns the static export configuration, or `null` when running from the Bluebird server.
19
+ * @returns {{ apiUrl?: string, router?: string, basename?: string, auth?: string }|null}
20
+ */
21
+ export function getExportConfig() {
22
+ return EXPORT_CONFIG;
23
+ }
24
+
25
+ /**
26
+ * Checks whether the app runs from a static `npx bluebird-js export` build (Electron, Capacitor, any static host).
27
+ * @returns {boolean}
28
+ */
29
+ export function isExported() {
30
+ return EXPORT_CONFIG !== null;
31
+ }
32
+
33
+ /**
34
+ * Configures an optional base URL prepended to relative `/api/*` requests (useful for Electron/Capacitor builds).
35
+ * @param {string} baseUrl
36
+ */
37
+ export function setApiBaseUrl(baseUrl) {
38
+ apiBaseUrl = String(baseUrl || "").replace(/\/+$/, "");
39
+ }
40
+
41
+ /**
42
+ * Configures the API client.
43
+ * - `auth: "cookie"` (web default): HttpOnly session cookie + `X-CSRF-Token` header.
44
+ * - `auth: "token"` (export default): `Authorization: Bearer` token stored in `localStorage`, no cookies.
45
+ * @param {{ baseUrl?: string, auth?: "cookie"|"token" }} [options={}]
46
+ */
47
+ export function configureApi(options = {}) {
48
+ if (options.baseUrl !== undefined) setApiBaseUrl(options.baseUrl);
49
+ if (options.auth === "cookie" || options.auth === "token") authMode = options.auth;
50
+ }
51
+
52
+ /**
53
+ * Returns the active authentication transport (`"cookie"` or `"token"`).
54
+ * @returns {"cookie"|"token"}
55
+ */
56
+ export function getAuthMode() {
57
+ return authMode === "token" ? "token" : "cookie";
58
+ }
59
+
60
+ /**
61
+ * Returns the stored bearer token used in `"token"` auth mode.
62
+ * @returns {string}
63
+ */
64
+ export function getAuthToken() {
65
+ try {
66
+ return window.localStorage.getItem(TOKEN_STORAGE_KEY) || memoryToken;
67
+ } catch {
68
+ return memoryToken;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Stores (or clears with `null`) the bearer token used in `"token"` auth mode.
74
+ * @param {string|null} token
75
+ */
76
+ export function setAuthToken(token) {
77
+ memoryToken = token ? String(token) : "";
78
+ try {
79
+ if (memoryToken) window.localStorage.setItem(TOKEN_STORAGE_KEY, memoryToken);
80
+ else window.localStorage.removeItem(TOKEN_STORAGE_KEY);
81
+ } catch {}
82
+ }
83
+
84
+ /**
85
+ * Returns the configured API base URL.
86
+ * @returns {string}
87
+ */
88
+ export function getApiBaseUrl() {
89
+ return apiBaseUrl;
90
+ }
91
+
92
+ /**
93
+ * Reads the double-submit CSRF token from the `_csrf` cookie.
94
+ * @returns {string}
95
+ */
96
+ export function getCsrfToken() {
97
+ if (!isBrowser) return "";
98
+ const match = document.cookie.match(/(?:^|;\s*)_csrf=([^;]*)/);
99
+ if (!match?.[1]) return "";
100
+ try {
101
+ return decodeURIComponent(match[1]);
102
+ } catch {
103
+ return match[1];
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Normalizes array or object validation error payloads into a field-keyed map.
109
+ * @param {any} errors
110
+ * @returns {Record<string, string>|null}
111
+ */
112
+ function normalizeErrors(errors) {
113
+ if (!errors) return null;
114
+ if (Array.isArray(errors)) {
115
+ const out = {};
116
+ for (const item of errors) {
117
+ if (item && typeof item === "object" && item.field && !out[item.field]) {
118
+ out[item.field] = String(item.message || translate("value.invalid"));
119
+ }
120
+ }
121
+ return Object.keys(out).length ? out : null;
122
+ }
123
+ if (typeof errors === "object") {
124
+ return errors;
125
+ }
126
+ return null;
127
+ }
128
+
129
+ /**
130
+ * Error thrown by `api()` when an HTTP request fails or returns an error envelope.
131
+ */
132
+ export class ApiError extends Error {
133
+ /**
134
+ * @param {string} message
135
+ * @param {{ status?: number, data?: any, errors?: any }} [info]
136
+ */
137
+ constructor(message, info = {}) {
138
+ super(message);
139
+ this.name = "ApiError";
140
+ this.status = info.status || 0;
141
+ this.data = info.data ?? null;
142
+ this.errors = normalizeErrors(info.errors);
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Resolves a request URL against the configured API base URL when applicable.
148
+ * @param {string} url
149
+ * @returns {string}
150
+ */
151
+ function resolveUrl(url) {
152
+ if (!apiBaseUrl || /^https?:\/\//i.test(url)) return url;
153
+ return `${apiBaseUrl}${url.startsWith("/") ? url : `/${url}`}`;
154
+ }
155
+
156
+ /**
157
+ * Sends a fetch request to a Bluebird REST endpoint with credentials and the `X-CSRF-Token` header.
158
+ * Automatically serializes JSON bodies, parses JSON responses, and throws `ApiError` on failure.
159
+ * @template T
160
+ * @param {string} url
161
+ * @param {Object} [options={}]
162
+ * @param {string} [options.method="GET"]
163
+ * @param {any} [options.body]
164
+ * @param {Record<string, string>} [options.headers]
165
+ * @param {RequestCredentials} [options.credentials]
166
+ * @param {AbortSignal} [options.signal]
167
+ * @returns {Promise<T>}
168
+ */
169
+ export async function api(url, options = {}) {
170
+ const method = String(options.method || (options.body !== undefined ? "POST" : "GET")).toUpperCase();
171
+ const isForm = typeof FormData !== "undefined" && options.body instanceof FormData;
172
+ const headers = {
173
+ Accept: "application/json",
174
+ ...(options.headers || {}),
175
+ };
176
+
177
+ const tokenMode = authMode === "token";
178
+ if (tokenMode) {
179
+ headers["X-Auth-Mode"] = "token";
180
+ const token = getAuthToken();
181
+ if (token && !headers.Authorization) headers.Authorization = `Bearer ${token}`;
182
+ } else if (method !== "GET" && method !== "HEAD") {
183
+ const csrf = getCsrfToken();
184
+ if (csrf && !headers["X-CSRF-Token"]) {
185
+ headers["X-CSRF-Token"] = csrf;
186
+ }
187
+ }
188
+
189
+ if (!isForm && options.body !== undefined && !headers["Content-Type"]) {
190
+ headers["Content-Type"] = "application/json";
191
+ }
192
+
193
+ const res = await fetch(resolveUrl(url), {
194
+ method,
195
+ credentials: options.credentials || (tokenMode ? "omit" : apiBaseUrl ? "include" : "same-origin"),
196
+ headers,
197
+ signal: options.signal,
198
+ body:
199
+ method === "GET" || method === "HEAD" || options.body === undefined
200
+ ? undefined
201
+ : isForm || typeof options.body === "string"
202
+ ? options.body
203
+ : JSON.stringify(options.body),
204
+ });
205
+
206
+ let data = null;
207
+ const contentType = res.headers.get("Content-Type") || "";
208
+ if (contentType.includes("application/json")) {
209
+ try {
210
+ data = await res.json();
211
+ } catch {}
212
+ } else {
213
+ try {
214
+ const text = await res.text();
215
+ data = text ? { message: text } : null;
216
+ } catch {}
217
+ }
218
+
219
+ if (!res.ok || data?.status === "error") {
220
+ const rawMsg = Array.isArray(data?.message) ? data.message.join(", ") : data?.message;
221
+ throw new ApiError(rawMsg || data?.error || `Request failed (HTTP ${res.status})`, {
222
+ status: res.status,
223
+ data,
224
+ errors: data?.errors,
225
+ });
226
+ }
227
+
228
+ return data && typeof data === "object" && "data" in data ? data.data : data;
229
+ }
230
+
231
+ api.get = (url, options = {}) => api(url, { ...options, method: "GET" });
232
+ api.post = (url, body, options = {}) => api(url, { ...options, method: "POST", body });
233
+ api.put = (url, body, options = {}) => api(url, { ...options, method: "PUT", body });
234
+ api.patch = (url, body, options = {}) => api(url, { ...options, method: "PATCH", body });
235
+ api.delete = (url, options = {}) => api(url, { ...options, method: "DELETE" });
236
+
237
+ export const request = api;
@@ -0,0 +1,236 @@
1
+ import {
2
+ createContext,
3
+ createElement as h,
4
+ useCallback,
5
+ useContext,
6
+ useEffect,
7
+ useMemo,
8
+ useState,
9
+ } from "react";
10
+ import { Navigate, Outlet, useLocation } from "react-router";
11
+ import { api, getAuthMode, setAuthToken } from "./api.js";
12
+ import { PageSkeleton } from "./components.js";
13
+ import { t as translate } from "./i18n.js";
14
+
15
+ const DEFAULT_ENDPOINTS = {
16
+ me: "/api/auth/me",
17
+ login: "/api/auth/login",
18
+ register: "/api/auth/register",
19
+ logout: "/api/auth/logout",
20
+ };
21
+
22
+ const AuthContext = createContext(null);
23
+
24
+ /**
25
+ * Checks whether a user object holds at least one of the required roles.
26
+ * Returns `true` for any authenticated user when `roles` is omitted or empty.
27
+ * @param {Object|null|undefined} user
28
+ * @param {string|string[]|null|undefined} roles
29
+ * @returns {boolean}
30
+ */
31
+ export function matchUserRole(user, roles) {
32
+ if (!user) return false;
33
+ const required = Array.isArray(roles) ? roles.filter(Boolean) : roles ? [roles] : [];
34
+ if (required.length === 0) return true;
35
+ const userRoles = new Set();
36
+ if (typeof user.role === "string" && user.role) userRoles.add(user.role);
37
+ if (Array.isArray(user.roles)) {
38
+ for (const r of user.roles) {
39
+ if (typeof r === "string" && r) userRoles.add(r);
40
+ }
41
+ }
42
+ return required.some((r) => userRoles.has(r));
43
+ }
44
+
45
+ /**
46
+ * Provides authentication state synchronized with `/api/auth/me`, plus `login`, `register`, `logout`,
47
+ * `refresh`, and `hasRole` helpers for React Router routes and components.
48
+ * @param {Object} props
49
+ * @param {Object} [props.endpoints]
50
+ * @param {any} [props.initialUser]
51
+ * @param {any} props.children
52
+ */
53
+ export function AuthProvider({ endpoints, initialUser, children }) {
54
+ const urls = useMemo(() => ({ ...DEFAULT_ENDPOINTS, ...(endpoints || {}) }), [endpoints]);
55
+ const [user, setUser] = useState(initialUser === undefined ? null : initialUser);
56
+ const [loading, setLoading] = useState(initialUser === undefined);
57
+ const [registerEnabled, setRegisterEnabled] = useState(true);
58
+
59
+ const refresh = useCallback(
60
+ async (signal) => {
61
+ try {
62
+ const res = await api.get(urls.me, { signal });
63
+ const resolvedUser = res && typeof res === "object" && "user" in res ? res.user : res;
64
+ setUser(resolvedUser || null);
65
+ if (res && typeof res === "object" && "registerEnabled" in res) {
66
+ setRegisterEnabled(Boolean(res.registerEnabled));
67
+ }
68
+ return resolvedUser || null;
69
+ } catch (err) {
70
+ if (err?.name === "AbortError" || signal?.aborted) return null;
71
+ if (err?.status === 401 && getAuthMode() === "token") setAuthToken(null);
72
+ setUser(null);
73
+ return null;
74
+ } finally {
75
+ if (!signal?.aborted) setLoading(false);
76
+ }
77
+ },
78
+ [urls.me]
79
+ );
80
+
81
+ useEffect(() => {
82
+ if (initialUser !== undefined) return;
83
+ const ctrl = new AbortController();
84
+ refresh(ctrl.signal);
85
+ return () => ctrl.abort();
86
+ }, [initialUser, refresh]);
87
+
88
+ const login = useCallback(
89
+ async (credentials) => {
90
+ const res = await api.post(urls.login, credentials);
91
+ if (res && typeof res === "object" && res.token) setAuthToken(res.token);
92
+ const nextUser = res && typeof res === "object" && "user" in res ? res.user : res;
93
+ if (nextUser) {
94
+ setUser(nextUser);
95
+ } else {
96
+ await refresh();
97
+ }
98
+ return nextUser;
99
+ },
100
+ [urls.login, refresh]
101
+ );
102
+
103
+ const register = useCallback(
104
+ async (payload) => {
105
+ const res = await api.post(urls.register, payload);
106
+ if (res && typeof res === "object" && res.token) setAuthToken(res.token);
107
+ const nextUser = res && typeof res === "object" && "user" in res ? res.user : res;
108
+ if (nextUser) {
109
+ setUser(nextUser);
110
+ } else {
111
+ await refresh();
112
+ }
113
+ return nextUser;
114
+ },
115
+ [urls.register, refresh]
116
+ );
117
+
118
+ const logout = useCallback(async () => {
119
+ try {
120
+ await api.post(urls.logout, {});
121
+ } finally {
122
+ if (getAuthMode() === "token") setAuthToken(null);
123
+ setUser(null);
124
+ }
125
+ }, [urls.logout]);
126
+
127
+ const hasRole = useCallback((roles) => matchUserRole(user, roles), [user]);
128
+
129
+ const value = useMemo(
130
+ () => ({
131
+ user,
132
+ loading,
133
+ authenticated: Boolean(user),
134
+ registerEnabled,
135
+ login,
136
+ register,
137
+ logout,
138
+ refresh,
139
+ setUser,
140
+ hasRole,
141
+ }),
142
+ [user, loading, registerEnabled, login, register, logout, refresh, hasRole]
143
+ );
144
+
145
+ return h(AuthContext.Provider, { value }, children);
146
+ }
147
+
148
+ /**
149
+ * Returns the active auth context (`user`, `loading`, `authenticated`, `registerEnabled`, `login`, `register`, `logout`, `refresh`, `hasRole`).
150
+ */
151
+ export function useAuth() {
152
+ const ctx = useContext(AuthContext);
153
+ if (!ctx) {
154
+ throw new Error("useAuth() must be used inside <AuthProvider>.");
155
+ }
156
+ return ctx;
157
+ }
158
+
159
+ /**
160
+ * Protects routes or components for authenticated users and optional roles.
161
+ * Works both as a wrapper component and as a React Router layout route (`<Outlet />`).
162
+ * @param {Object} [props]
163
+ * @param {string|string[]} [props.roles]
164
+ * @param {string} [props.redirectTo="/login"]
165
+ * @param {string} [props.forbiddenRedirect]
166
+ * @param {any} [props.fallback]
167
+ * @param {any} [props.forbidden]
168
+ * @param {any} [props.children]
169
+ */
170
+ export function RequireAuth({
171
+ roles,
172
+ redirectTo = "/login",
173
+ forbiddenRedirect,
174
+ fallback,
175
+ forbidden,
176
+ children,
177
+ } = {}) {
178
+ const { user, loading, hasRole } = useAuth();
179
+ const location = useLocation();
180
+
181
+ if (loading) {
182
+ return fallback !== undefined ? fallback : h(PageSkeleton, null);
183
+ }
184
+
185
+ if (!user) {
186
+ return h(Navigate, { to: redirectTo, state: { from: location }, replace: true });
187
+ }
188
+
189
+ if (roles && !hasRole(roles)) {
190
+ if (forbiddenRedirect) {
191
+ return h(Navigate, { to: forbiddenRedirect, replace: true });
192
+ }
193
+ if (forbidden !== undefined) {
194
+ return forbidden;
195
+ }
196
+ return h(
197
+ "div",
198
+ {
199
+ className:
200
+ "card mx-auto my-12 max-w-md text-center",
201
+ },
202
+ h("h2", { className: "text-lg font-semibold tracking-tight" }, translate("auth.deniedTitle")),
203
+ h(
204
+ "p",
205
+ { className: "mt-1 text-sm text-muted-foreground" },
206
+ translate("auth.deniedText")
207
+ )
208
+ );
209
+ }
210
+
211
+ return children !== undefined ? children : h(Outlet, null);
212
+ }
213
+
214
+ /**
215
+ * Restricts routes (such as Login or Register) to unauthenticated guests, redirecting signed-in users.
216
+ * Works both as a wrapper component and as a React Router layout route (`<Outlet />`).
217
+ * @param {Object} [props]
218
+ * @param {string} [props.redirectTo="/"]
219
+ * @param {any} [props.fallback]
220
+ * @param {any} [props.children]
221
+ */
222
+ export function GuestOnly({ redirectTo = "/", fallback, children } = {}) {
223
+ const { user, loading } = useAuth();
224
+ const location = useLocation();
225
+
226
+ if (loading) {
227
+ return fallback !== undefined ? fallback : h(PageSkeleton, null);
228
+ }
229
+
230
+ if (user) {
231
+ const target = location.state?.from?.pathname || redirectTo;
232
+ return h(Navigate, { to: target, replace: true });
233
+ }
234
+
235
+ return children !== undefined ? children : h(Outlet, null);
236
+ }