@alepha/react 0.11.11 → 0.11.12

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 (128) hide show
  1. package/README.md +1 -183
  2. package/dist/auth/index.browser.js +1460 -0
  3. package/dist/auth/index.browser.js.map +1 -0
  4. package/dist/auth/index.cjs +3647 -0
  5. package/dist/auth/index.cjs.map +1 -0
  6. package/dist/auth/index.d.cts +564 -0
  7. package/dist/auth/index.d.cts.map +1 -0
  8. package/dist/auth/index.d.ts +564 -0
  9. package/dist/auth/index.d.ts.map +1 -0
  10. package/dist/auth/index.js +3615 -0
  11. package/dist/auth/index.js.map +1 -0
  12. package/dist/{index.browser.js → core/index.browser.js} +36 -35
  13. package/dist/core/index.browser.js.map +1 -0
  14. package/dist/{index.cjs → core/index.cjs} +141 -140
  15. package/dist/core/index.cjs.map +1 -0
  16. package/dist/{index.d.cts → core/index.d.cts} +68 -68
  17. package/dist/core/index.d.cts.map +1 -0
  18. package/dist/{index.d.ts → core/index.d.ts} +68 -68
  19. package/dist/core/index.d.ts.map +1 -0
  20. package/dist/{index.js → core/index.js} +39 -38
  21. package/dist/core/index.js.map +1 -0
  22. package/dist/form/index.cjs +2054 -0
  23. package/dist/form/index.cjs.map +1 -0
  24. package/dist/form/index.d.cts +211 -0
  25. package/dist/form/index.d.cts.map +1 -0
  26. package/dist/form/index.d.ts +211 -0
  27. package/dist/form/index.d.ts.map +1 -0
  28. package/dist/form/index.js +2026 -0
  29. package/dist/form/index.js.map +1 -0
  30. package/dist/head/index.browser.js +1503 -0
  31. package/dist/head/index.browser.js.map +1 -0
  32. package/dist/head/index.cjs +1908 -0
  33. package/dist/head/index.cjs.map +1 -0
  34. package/dist/head/index.d.cts +595 -0
  35. package/dist/head/index.d.cts.map +1 -0
  36. package/dist/head/index.d.ts +601 -0
  37. package/dist/head/index.d.ts.map +1 -0
  38. package/dist/head/index.js +1880 -0
  39. package/dist/head/index.js.map +1 -0
  40. package/dist/i18n/index.cjs +1886 -0
  41. package/dist/i18n/index.cjs.map +1 -0
  42. package/dist/i18n/index.d.cts +168 -0
  43. package/dist/i18n/index.d.cts.map +1 -0
  44. package/dist/i18n/index.d.ts +168 -0
  45. package/dist/i18n/index.d.ts.map +1 -0
  46. package/dist/i18n/index.js +1857 -0
  47. package/dist/i18n/index.js.map +1 -0
  48. package/dist/websocket/index.cjs +1774 -0
  49. package/dist/websocket/index.cjs.map +1 -0
  50. package/dist/websocket/index.d.cts +118 -0
  51. package/dist/websocket/index.d.cts.map +1 -0
  52. package/dist/websocket/index.d.ts +118 -0
  53. package/dist/websocket/index.d.ts.map +1 -0
  54. package/dist/websocket/index.js +1750 -0
  55. package/dist/websocket/index.js.map +1 -0
  56. package/package.json +89 -67
  57. package/src/auth/descriptors/$auth.ts +436 -0
  58. package/src/auth/descriptors/$authApple.ts +8 -0
  59. package/src/auth/descriptors/$authGithub.ts +81 -0
  60. package/src/auth/descriptors/$authGoogle.ts +38 -0
  61. package/src/auth/errors/SessionExpiredError.ts +6 -0
  62. package/src/auth/hooks/useAuth.ts +31 -0
  63. package/src/auth/index.browser.ts +16 -0
  64. package/src/auth/index.shared.ts +3 -0
  65. package/src/auth/index.ts +47 -0
  66. package/src/auth/providers/ReactAuthProvider.ts +629 -0
  67. package/src/auth/schemas/tokenResponseSchema.ts +11 -0
  68. package/src/auth/schemas/tokensSchema.ts +21 -0
  69. package/src/auth/schemas/userinfoResponseSchema.ts +10 -0
  70. package/src/auth/services/ReactAuth.ts +124 -0
  71. package/src/{components → core/components}/ErrorViewer.tsx +3 -2
  72. package/src/{components → core/components}/NestedView.tsx +1 -1
  73. package/src/{contexts → core/contexts}/AlephaContext.ts +1 -1
  74. package/src/{descriptors → core/descriptors}/$page.ts +4 -4
  75. package/src/{hooks → core/hooks}/useAction.ts +1 -1
  76. package/src/{hooks → core/hooks}/useAlepha.ts +1 -1
  77. package/src/{hooks → core/hooks}/useClient.ts +1 -1
  78. package/src/{hooks → core/hooks}/useEvents.ts +1 -1
  79. package/src/{hooks → core/hooks}/useInject.ts +1 -1
  80. package/src/{hooks → core/hooks}/useQueryParams.ts +1 -1
  81. package/src/{hooks → core/hooks}/useRouterState.ts +1 -1
  82. package/src/{hooks → core/hooks}/useSchema.ts +3 -3
  83. package/src/{hooks → core/hooks}/useStore.ts +2 -2
  84. package/src/{index.browser.ts → core/index.browser.ts} +4 -4
  85. package/src/{index.ts → core/index.ts} +6 -6
  86. package/src/{providers → core/providers}/ReactBrowserProvider.ts +6 -6
  87. package/src/{providers → core/providers}/ReactBrowserRendererProvider.ts +2 -2
  88. package/src/{providers → core/providers}/ReactBrowserRouterProvider.ts +3 -3
  89. package/src/{providers → core/providers}/ReactPageProvider.ts +3 -3
  90. package/src/{providers → core/providers}/ReactServerProvider.ts +7 -7
  91. package/src/{services → core/services}/ReactPageServerService.ts +2 -2
  92. package/src/{services → core/services}/ReactPageService.ts +1 -1
  93. package/src/{services → core/services}/ReactRouter.ts +1 -1
  94. package/src/form/components/FormState.tsx +17 -0
  95. package/src/form/hooks/useForm.ts +47 -0
  96. package/src/form/hooks/useFormState.ts +130 -0
  97. package/src/form/index.ts +38 -0
  98. package/src/form/services/FormModel.ts +548 -0
  99. package/src/head/descriptors/$head.ts +25 -0
  100. package/src/head/hooks/useHead.ts +62 -0
  101. package/src/head/index.browser.ts +25 -0
  102. package/src/head/index.ts +47 -0
  103. package/src/head/interfaces/Head.ts +46 -0
  104. package/src/head/providers/BrowserHeadProvider.ts +105 -0
  105. package/src/head/providers/HeadProvider.ts +73 -0
  106. package/src/head/providers/ServerHeadProvider.ts +109 -0
  107. package/src/i18n/README.md +76 -0
  108. package/src/i18n/components/Localize.tsx +35 -0
  109. package/src/i18n/descriptors/$dictionary.ts +65 -0
  110. package/src/i18n/hooks/useI18n.ts +18 -0
  111. package/src/i18n/index.ts +34 -0
  112. package/src/i18n/providers/I18nProvider.ts +277 -0
  113. package/src/websocket/hooks/useRoom.tsx +223 -0
  114. package/src/websocket/index.ts +7 -0
  115. package/dist/index.browser.js.map +0 -1
  116. package/dist/index.cjs.map +0 -1
  117. package/dist/index.d.cts.map +0 -1
  118. package/dist/index.d.ts.map +0 -1
  119. package/dist/index.js.map +0 -1
  120. /package/src/{components → core/components}/ClientOnly.tsx +0 -0
  121. /package/src/{components → core/components}/ErrorBoundary.tsx +0 -0
  122. /package/src/{components → core/components}/Link.tsx +0 -0
  123. /package/src/{components → core/components}/NotFound.tsx +0 -0
  124. /package/src/{contexts → core/contexts}/RouterLayerContext.ts +0 -0
  125. /package/src/{errors → core/errors}/Redirection.ts +0 -0
  126. /package/src/{hooks → core/hooks}/useActive.ts +0 -0
  127. /package/src/{hooks → core/hooks}/useRouter.ts +0 -0
  128. /package/src/{index.shared.ts → core/index.shared.ts} +0 -0
@@ -0,0 +1,1503 @@
1
+ import { $atom, $env, $hook, $inject, $module, $use, Alepha, AlephaError, Atom, Descriptor, KIND, createDescriptor, t } from "alepha";
2
+ import { AlephaDateTime, DateTimeProvider } from "alepha/datetime";
3
+ import { AlephaServer } from "alepha/server";
4
+ import { AlephaServerLinks, LinkProvider } from "alepha/server/links";
5
+ import { $logger } from "alepha/logger";
6
+ import { RouterProvider } from "alepha/router";
7
+ import React, { StrictMode, createContext, createElement, memo, use, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
8
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
+ import { createRoot, hydrateRoot } from "react-dom/client";
10
+
11
+ //#region src/core/services/ReactPageService.ts
12
+ var ReactPageService = class {
13
+ fetch(pathname, options = {}) {
14
+ throw new AlephaError("Fetch is not available for this environment.");
15
+ }
16
+ render(name, options = {}) {
17
+ throw new AlephaError("Render is not available for this environment.");
18
+ }
19
+ };
20
+
21
+ //#endregion
22
+ //#region src/core/descriptors/$page.ts
23
+ /**
24
+ * Main descriptor for defining a React route in the application.
25
+ *
26
+ * The $page descriptor is the core building block for creating type-safe, SSR-enabled React routes.
27
+ * It provides a declarative way to define pages with powerful features:
28
+ *
29
+ * **Routing & Navigation**
30
+ * - URL pattern matching with parameters (e.g., `/users/:id`)
31
+ * - Nested routing with parent-child relationships
32
+ * - Type-safe URL parameter and query string validation
33
+ *
34
+ * **Data Loading**
35
+ * - Server-side data fetching with the `resolve` function
36
+ * - Automatic serialization and hydration for SSR
37
+ * - Access to request context, URL params, and parent data
38
+ *
39
+ * **Component Loading**
40
+ * - Direct component rendering or lazy loading for code splitting
41
+ * - Client-only rendering when browser APIs are needed
42
+ * - Automatic fallback handling during hydration
43
+ *
44
+ * **Performance Optimization**
45
+ * - Static generation for pre-rendered pages at build time
46
+ * - Server-side caching with configurable TTL and providers
47
+ * - Code splitting through lazy component loading
48
+ *
49
+ * **Error Handling**
50
+ * - Custom error handlers with support for redirects
51
+ * - Hierarchical error handling (child → parent)
52
+ * - HTTP status code handling (404, 401, etc.)
53
+ *
54
+ * **Page Animations**
55
+ * - CSS-based enter/exit animations
56
+ * - Dynamic animations based on page state
57
+ * - Custom timing and easing functions
58
+ *
59
+ * **Lifecycle Management**
60
+ * - Server response hooks for headers and status codes
61
+ * - Page leave handlers for cleanup (browser only)
62
+ * - Permission-based access control
63
+ *
64
+ * @example Simple page with data fetching
65
+ * ```typescript
66
+ * const userProfile = $page({
67
+ * path: "/users/:id",
68
+ * schema: {
69
+ * params: t.object({ id: t.int() }),
70
+ * query: t.object({ tab: t.optional(t.text()) })
71
+ * },
72
+ * resolve: async ({ params }) => {
73
+ * const user = await userApi.getUser(params.id);
74
+ * return { user };
75
+ * },
76
+ * lazy: () => import("./UserProfile.tsx")
77
+ * });
78
+ * ```
79
+ *
80
+ * @example Nested routing with error handling
81
+ * ```typescript
82
+ * const projectSection = $page({
83
+ * path: "/projects/:id",
84
+ * children: () => [projectBoard, projectSettings],
85
+ * resolve: async ({ params }) => {
86
+ * const project = await projectApi.get(params.id);
87
+ * return { project };
88
+ * },
89
+ * errorHandler: (error) => {
90
+ * if (HttpError.is(error, 404)) {
91
+ * return <ProjectNotFound />;
92
+ * }
93
+ * }
94
+ * });
95
+ * ```
96
+ *
97
+ * @example Static generation with caching
98
+ * ```typescript
99
+ * const blogPost = $page({
100
+ * path: "/blog/:slug",
101
+ * static: {
102
+ * entries: posts.map(p => ({ params: { slug: p.slug } }))
103
+ * },
104
+ * resolve: async ({ params }) => {
105
+ * const post = await loadPost(params.slug);
106
+ * return { post };
107
+ * }
108
+ * });
109
+ * ```
110
+ */
111
+ const $page = (options) => {
112
+ return createDescriptor(PageDescriptor, options);
113
+ };
114
+ var PageDescriptor = class extends Descriptor {
115
+ reactPageService = $inject(ReactPageService);
116
+ onInit() {
117
+ if (this.options.static) this.options.cache ??= { store: {
118
+ provider: "memory",
119
+ ttl: [1, "week"]
120
+ } };
121
+ }
122
+ get name() {
123
+ return this.options.name ?? this.config.propertyKey;
124
+ }
125
+ /**
126
+ * For testing or build purposes.
127
+ *
128
+ * This will render the page (HTML layout included or not) and return the HTML + context.
129
+ * Only valid for server-side rendering, it will throw an error if called on the client-side.
130
+ */
131
+ async render(options) {
132
+ return this.reactPageService.render(this.name, options);
133
+ }
134
+ async fetch(options) {
135
+ return this.reactPageService.fetch(this.options.path || "", options);
136
+ }
137
+ match(url) {
138
+ return false;
139
+ }
140
+ pathname(config) {
141
+ return this.options.path || "";
142
+ }
143
+ };
144
+ $page[KIND] = PageDescriptor;
145
+
146
+ //#endregion
147
+ //#region src/core/components/NotFound.tsx
148
+ function NotFoundPage(props) {
149
+ return /* @__PURE__ */ jsx("div", {
150
+ style: {
151
+ height: "100vh",
152
+ display: "flex",
153
+ flexDirection: "column",
154
+ justifyContent: "center",
155
+ alignItems: "center",
156
+ textAlign: "center",
157
+ fontFamily: "sans-serif",
158
+ padding: "1rem",
159
+ ...props.style
160
+ },
161
+ children: /* @__PURE__ */ jsx("h1", {
162
+ style: {
163
+ fontSize: "1rem",
164
+ marginBottom: "0.5rem"
165
+ },
166
+ children: "404 - This page does not exist"
167
+ })
168
+ });
169
+ }
170
+
171
+ //#endregion
172
+ //#region src/core/components/ClientOnly.tsx
173
+ /**
174
+ * A small utility component that renders its children only on the client side.
175
+ *
176
+ * Optionally, you can provide a fallback React node that will be rendered.
177
+ *
178
+ * You should use this component when
179
+ * - you have code that relies on browser-specific APIs
180
+ * - you want to avoid server-side rendering for a specific part of your application
181
+ * - you want to prevent pre-rendering of a component
182
+ */
183
+ const ClientOnly = (props) => {
184
+ const [mounted, setMounted] = useState(false);
185
+ useEffect(() => setMounted(true), []);
186
+ if (props.disabled) return props.children;
187
+ return mounted ? props.children : props.fallback;
188
+ };
189
+ var ClientOnly_default = ClientOnly;
190
+
191
+ //#endregion
192
+ //#region src/core/components/ErrorViewer.tsx
193
+ const ErrorViewer = ({ error, alepha }) => {
194
+ const [expanded, setExpanded] = useState(false);
195
+ if (alepha.isProduction()) return /* @__PURE__ */ jsx(ErrorViewerProduction, {});
196
+ const stackLines = error.stack?.split("\n") ?? [];
197
+ const previewLines = stackLines.slice(0, 5);
198
+ const hiddenLineCount = stackLines.length - previewLines.length;
199
+ const copyToClipboard = (text) => {
200
+ navigator.clipboard.writeText(text).catch((err) => {
201
+ console.error("Clipboard error:", err);
202
+ });
203
+ };
204
+ const styles = {
205
+ container: {
206
+ padding: "24px",
207
+ backgroundColor: "#FEF2F2",
208
+ color: "#7F1D1D",
209
+ border: "1px solid #FECACA",
210
+ borderRadius: "16px",
211
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
212
+ fontFamily: "monospace",
213
+ maxWidth: "768px",
214
+ margin: "40px auto"
215
+ },
216
+ heading: {
217
+ fontSize: "20px",
218
+ fontWeight: "bold",
219
+ marginBottom: "10px"
220
+ },
221
+ name: {
222
+ fontSize: "16px",
223
+ fontWeight: 600
224
+ },
225
+ message: {
226
+ fontSize: "14px",
227
+ marginBottom: "16px"
228
+ },
229
+ sectionHeader: {
230
+ display: "flex",
231
+ justifyContent: "space-between",
232
+ alignItems: "center",
233
+ fontSize: "12px",
234
+ marginBottom: "4px",
235
+ color: "#991B1B"
236
+ },
237
+ copyButton: {
238
+ fontSize: "12px",
239
+ color: "#DC2626",
240
+ background: "none",
241
+ border: "none",
242
+ cursor: "pointer",
243
+ textDecoration: "underline"
244
+ },
245
+ stackContainer: {
246
+ backgroundColor: "#FEE2E2",
247
+ padding: "12px",
248
+ borderRadius: "8px",
249
+ fontSize: "13px",
250
+ lineHeight: "1.4",
251
+ overflowX: "auto",
252
+ whiteSpace: "pre-wrap"
253
+ },
254
+ expandLine: {
255
+ color: "#F87171",
256
+ cursor: "pointer",
257
+ marginTop: "8px"
258
+ }
259
+ };
260
+ return /* @__PURE__ */ jsxs("div", {
261
+ style: styles.container,
262
+ children: [/* @__PURE__ */ jsxs("div", { children: [
263
+ /* @__PURE__ */ jsx("div", {
264
+ style: styles.heading,
265
+ children: "🔥 Error"
266
+ }),
267
+ /* @__PURE__ */ jsx("div", {
268
+ style: styles.name,
269
+ children: error.name
270
+ }),
271
+ /* @__PURE__ */ jsx("div", {
272
+ style: styles.message,
273
+ children: error.message
274
+ })
275
+ ] }), stackLines.length > 0 && /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
276
+ style: styles.sectionHeader,
277
+ children: [/* @__PURE__ */ jsx("span", { children: "Stack trace" }), /* @__PURE__ */ jsx("button", {
278
+ type: "button",
279
+ onClick: () => copyToClipboard(error.stack),
280
+ style: styles.copyButton,
281
+ children: "Copy all"
282
+ })]
283
+ }), /* @__PURE__ */ jsxs("pre", {
284
+ style: styles.stackContainer,
285
+ children: [(expanded ? stackLines : previewLines).map((line, i) => /* @__PURE__ */ jsx("div", { children: line }, i)), !expanded && hiddenLineCount > 0 && /* @__PURE__ */ jsxs("div", {
286
+ style: styles.expandLine,
287
+ onClick: () => setExpanded(true),
288
+ children: [
289
+ "+ ",
290
+ hiddenLineCount,
291
+ " more lines..."
292
+ ]
293
+ })]
294
+ })] })]
295
+ });
296
+ };
297
+ var ErrorViewer_default = ErrorViewer;
298
+ const ErrorViewerProduction = () => {
299
+ const styles = {
300
+ container: {
301
+ padding: "24px",
302
+ backgroundColor: "#FEF2F2",
303
+ color: "#7F1D1D",
304
+ border: "1px solid #FECACA",
305
+ borderRadius: "16px",
306
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
307
+ fontFamily: "monospace",
308
+ maxWidth: "768px",
309
+ margin: "40px auto",
310
+ textAlign: "center"
311
+ },
312
+ heading: {
313
+ fontSize: "20px",
314
+ fontWeight: "bold",
315
+ marginBottom: "8px"
316
+ },
317
+ name: {
318
+ fontSize: "16px",
319
+ fontWeight: 600,
320
+ marginBottom: "4px"
321
+ },
322
+ message: {
323
+ fontSize: "14px",
324
+ opacity: .85
325
+ }
326
+ };
327
+ return /* @__PURE__ */ jsxs("div", {
328
+ style: styles.container,
329
+ children: [/* @__PURE__ */ jsx("div", {
330
+ style: styles.heading,
331
+ children: "🚨 An error occurred"
332
+ }), /* @__PURE__ */ jsx("div", {
333
+ style: styles.message,
334
+ children: "Something went wrong. Please try again later."
335
+ })]
336
+ });
337
+ };
338
+
339
+ //#endregion
340
+ //#region src/core/contexts/RouterLayerContext.ts
341
+ const RouterLayerContext = createContext(void 0);
342
+
343
+ //#endregion
344
+ //#region src/core/errors/Redirection.ts
345
+ /**
346
+ * Used for Redirection during the page loading.
347
+ *
348
+ * Depends on the context, it can be thrown or just returned.
349
+ */
350
+ var Redirection = class extends Error {
351
+ redirect;
352
+ constructor(redirect) {
353
+ super("Redirection");
354
+ this.redirect = redirect;
355
+ }
356
+ };
357
+
358
+ //#endregion
359
+ //#region src/core/contexts/AlephaContext.ts
360
+ const AlephaContext = createContext(void 0);
361
+
362
+ //#endregion
363
+ //#region src/core/hooks/useAlepha.ts
364
+ /**
365
+ * Main Alepha hook.
366
+ *
367
+ * It provides access to the Alepha instance within a React component.
368
+ *
369
+ * With Alepha, you can access the core functionalities of the framework:
370
+ *
371
+ * - alepha.state() for state management
372
+ * - alepha.inject() for dependency injection
373
+ * - alepha.events.emit() for event handling
374
+ * etc...
375
+ */
376
+ const useAlepha = () => {
377
+ const alepha = useContext(AlephaContext);
378
+ if (!alepha) throw new AlephaError("Hook 'useAlepha()' must be used within an AlephaContext.Provider");
379
+ return alepha;
380
+ };
381
+
382
+ //#endregion
383
+ //#region src/core/hooks/useEvents.ts
384
+ /**
385
+ * Allow subscribing to multiple Alepha events. See {@link Hooks} for available events.
386
+ *
387
+ * useEvents is fully typed to ensure correct event callback signatures.
388
+ *
389
+ * @example
390
+ * ```tsx
391
+ * useEvents(
392
+ * {
393
+ * "react:transition:begin": (ev) => {
394
+ * console.log("Transition began to:", ev.to);
395
+ * },
396
+ * "react:transition:error": {
397
+ * priority: "first",
398
+ * callback: (ev) => {
399
+ * console.error("Transition error:", ev.error);
400
+ * },
401
+ * },
402
+ * },
403
+ * [],
404
+ * );
405
+ * ```
406
+ */
407
+ const useEvents = (opts, deps) => {
408
+ const alepha = useAlepha();
409
+ useEffect(() => {
410
+ if (!alepha.isBrowser()) return;
411
+ const subs = [];
412
+ for (const [name, hook] of Object.entries(opts)) subs.push(alepha.events.on(name, hook));
413
+ return () => {
414
+ for (const clear of subs) clear();
415
+ };
416
+ }, deps);
417
+ };
418
+
419
+ //#endregion
420
+ //#region src/core/hooks/useStore.ts
421
+ function useStore(target, defaultValue) {
422
+ const alepha = useAlepha();
423
+ useMemo(() => {
424
+ if (defaultValue != null && alepha.state.get(target) == null) alepha.state.set(target, defaultValue);
425
+ }, [defaultValue]);
426
+ const [state, setState] = useState(alepha.state.get(target));
427
+ useEffect(() => {
428
+ if (!alepha.isBrowser()) return;
429
+ const key = target instanceof Atom ? target.key : target;
430
+ return alepha.events.on("state:mutate", (ev) => {
431
+ if (ev.key === key) setState(ev.value);
432
+ });
433
+ }, []);
434
+ return [state, (value) => {
435
+ alepha.state.set(target, value);
436
+ }];
437
+ }
438
+
439
+ //#endregion
440
+ //#region src/core/hooks/useRouterState.ts
441
+ const useRouterState = () => {
442
+ const [state] = useStore("alepha.react.router.state");
443
+ if (!state) throw new AlephaError("Missing react router state");
444
+ return state;
445
+ };
446
+
447
+ //#endregion
448
+ //#region src/core/components/ErrorBoundary.tsx
449
+ /**
450
+ * A reusable error boundary for catching rendering errors
451
+ * in any part of the React component tree.
452
+ */
453
+ var ErrorBoundary = class extends React.Component {
454
+ constructor(props) {
455
+ super(props);
456
+ this.state = {};
457
+ }
458
+ /**
459
+ * Update state so the next render shows the fallback UI.
460
+ */
461
+ static getDerivedStateFromError(error) {
462
+ return { error };
463
+ }
464
+ /**
465
+ * Lifecycle method called when an error is caught.
466
+ * You can log the error or perform side effects here.
467
+ */
468
+ componentDidCatch(error, info) {
469
+ if (this.props.onError) this.props.onError(error, info);
470
+ }
471
+ render() {
472
+ if (this.state.error) return this.props.fallback(this.state.error);
473
+ return this.props.children;
474
+ }
475
+ };
476
+ var ErrorBoundary_default = ErrorBoundary;
477
+
478
+ //#endregion
479
+ //#region src/core/components/NestedView.tsx
480
+ /**
481
+ * A component that renders the current view of the nested router layer.
482
+ *
483
+ * To be simple, it renders the `element` of the current child page of a parent page.
484
+ *
485
+ * @example
486
+ * ```tsx
487
+ * import { NestedView } from "@alepha/react";
488
+ *
489
+ * class App {
490
+ * parent = $page({
491
+ * component: () => <NestedView />,
492
+ * });
493
+ *
494
+ * child = $page({
495
+ * parent: this.root,
496
+ * component: () => <div>Child Page</div>,
497
+ * });
498
+ * }
499
+ * ```
500
+ */
501
+ const NestedView = (props) => {
502
+ const index = use(RouterLayerContext)?.index ?? 0;
503
+ const state = useRouterState();
504
+ const [view, setView] = useState(state.layers[index]?.element);
505
+ const [animation, setAnimation] = useState("");
506
+ const animationExitDuration = useRef(0);
507
+ const animationExitNow = useRef(0);
508
+ useEvents({
509
+ "react:transition:begin": async ({ previous, state: state$1 }) => {
510
+ const layer = previous.layers[index];
511
+ if (`${state$1.url.pathname}/`.startsWith(`${layer?.path}/`)) return;
512
+ const animationExit = parseAnimation(layer.route?.animation, state$1, "exit");
513
+ if (animationExit) {
514
+ const duration = animationExit.duration || 200;
515
+ animationExitNow.current = Date.now();
516
+ animationExitDuration.current = duration;
517
+ setAnimation(animationExit.animation);
518
+ } else {
519
+ animationExitNow.current = 0;
520
+ animationExitDuration.current = 0;
521
+ setAnimation("");
522
+ }
523
+ },
524
+ "react:transition:end": async ({ state: state$1 }) => {
525
+ const layer = state$1.layers[index];
526
+ if (animationExitNow.current) {
527
+ const duration = animationExitDuration.current;
528
+ const diff = Date.now() - animationExitNow.current;
529
+ if (diff < duration) await new Promise((resolve) => setTimeout(resolve, duration - diff));
530
+ }
531
+ if (!layer?.cache) {
532
+ setView(layer?.element);
533
+ const animationEnter = parseAnimation(layer?.route?.animation, state$1, "enter");
534
+ if (animationEnter) setAnimation(animationEnter.animation);
535
+ else setAnimation("");
536
+ }
537
+ }
538
+ }, []);
539
+ let element = view ?? props.children ?? null;
540
+ if (animation) element = /* @__PURE__ */ jsx("div", {
541
+ style: {
542
+ display: "flex",
543
+ flex: 1,
544
+ height: "100%",
545
+ width: "100%",
546
+ position: "relative",
547
+ overflow: "hidden"
548
+ },
549
+ children: /* @__PURE__ */ jsx("div", {
550
+ style: {
551
+ height: "100%",
552
+ width: "100%",
553
+ display: "flex",
554
+ animation
555
+ },
556
+ children: element
557
+ })
558
+ });
559
+ if (props.errorBoundary === false) return /* @__PURE__ */ jsx(Fragment, { children: element });
560
+ if (props.errorBoundary) return /* @__PURE__ */ jsx(ErrorBoundary_default, {
561
+ fallback: props.errorBoundary,
562
+ children: element
563
+ });
564
+ return /* @__PURE__ */ jsx(ErrorBoundary_default, {
565
+ fallback: (error) => {
566
+ const result = state.onError(error, state);
567
+ if (result instanceof Redirection) return "Redirection inside ErrorBoundary is not allowed.";
568
+ return result;
569
+ },
570
+ children: element
571
+ });
572
+ };
573
+ var NestedView_default = memo(NestedView);
574
+ function parseAnimation(animationLike, state, type = "enter") {
575
+ if (!animationLike) return;
576
+ const DEFAULT_DURATION = 300;
577
+ const animation = typeof animationLike === "function" ? animationLike(state) : animationLike;
578
+ if (typeof animation === "string") {
579
+ if (type === "exit") return;
580
+ return {
581
+ duration: DEFAULT_DURATION,
582
+ animation: `${DEFAULT_DURATION}ms ${animation}`
583
+ };
584
+ }
585
+ if (typeof animation === "object") {
586
+ const anim = animation[type];
587
+ const duration = typeof anim === "object" ? anim.duration ?? DEFAULT_DURATION : DEFAULT_DURATION;
588
+ const name = typeof anim === "object" ? anim.name : anim;
589
+ if (type === "exit") return {
590
+ duration,
591
+ animation: `${duration}ms ${typeof anim === "object" ? anim.timing ?? "" : ""} ${name}`
592
+ };
593
+ return {
594
+ duration,
595
+ animation: `${duration}ms ${typeof anim === "object" ? anim.timing ?? "" : ""} ${name}`
596
+ };
597
+ }
598
+ }
599
+
600
+ //#endregion
601
+ //#region src/core/providers/ReactPageProvider.ts
602
+ const envSchema$1 = t.object({ REACT_STRICT_MODE: t.boolean({ default: true }) });
603
+ var ReactPageProvider = class {
604
+ log = $logger();
605
+ env = $env(envSchema$1);
606
+ alepha = $inject(Alepha);
607
+ pages = [];
608
+ getPages() {
609
+ return this.pages;
610
+ }
611
+ getConcretePages() {
612
+ const pages = [];
613
+ for (const page of this.pages) {
614
+ if (page.children && page.children.length > 0) continue;
615
+ const fullPath = this.pathname(page.name);
616
+ if (fullPath.includes(":") || fullPath.includes("*")) {
617
+ if (typeof page.static === "object") {
618
+ const entries = page.static.entries;
619
+ if (entries && entries.length > 0) for (const entry of entries) {
620
+ const params = entry.params;
621
+ const path = this.compile(page.path ?? "", params);
622
+ if (!path.includes(":") && !path.includes("*")) pages.push({
623
+ ...page,
624
+ name: params[Object.keys(params)[0]],
625
+ path,
626
+ ...entry
627
+ });
628
+ }
629
+ }
630
+ continue;
631
+ }
632
+ pages.push(page);
633
+ }
634
+ return pages;
635
+ }
636
+ page(name) {
637
+ for (const page of this.pages) if (page.name === name) return page;
638
+ throw new AlephaError(`Page '${name}' not found`);
639
+ }
640
+ pathname(name, options = {}) {
641
+ const page = this.page(name);
642
+ if (!page) throw new Error(`Page ${name} not found`);
643
+ let url = page.path ?? "";
644
+ let parent = page.parent;
645
+ while (parent) {
646
+ url = `${parent.path ?? ""}/${url}`;
647
+ parent = parent.parent;
648
+ }
649
+ url = this.compile(url, options.params ?? {});
650
+ if (options.query) {
651
+ const query = new URLSearchParams(options.query);
652
+ if (query.toString()) url += `?${query.toString()}`;
653
+ }
654
+ return url.replace(/\/\/+/g, "/") || "/";
655
+ }
656
+ url(name, options = {}) {
657
+ return new URL(this.pathname(name, options), options.host ?? `http://localhost`);
658
+ }
659
+ root(state) {
660
+ const root = createElement(AlephaContext.Provider, { value: this.alepha }, createElement(NestedView_default, {}, state.layers[0]?.element));
661
+ if (this.env.REACT_STRICT_MODE) return createElement(StrictMode, {}, root);
662
+ return root;
663
+ }
664
+ convertStringObjectToObject = (schema, value) => {
665
+ if (t.schema.isObject(schema) && typeof value === "object") {
666
+ for (const key in schema.properties) if (t.schema.isObject(schema.properties[key]) && typeof value[key] === "string") try {
667
+ value[key] = this.alepha.codec.decode(schema.properties[key], decodeURIComponent(value[key]));
668
+ } catch (e) {}
669
+ }
670
+ return value;
671
+ };
672
+ /**
673
+ * Create a new RouterState based on a given route and request.
674
+ * This method resolves the layers for the route, applying any query and params schemas defined in the route.
675
+ * It also handles errors and redirects.
676
+ */
677
+ async createLayers(route, state, previous = []) {
678
+ let context = {};
679
+ const stack = [{ route }];
680
+ let parent = route.parent;
681
+ while (parent) {
682
+ stack.unshift({ route: parent });
683
+ parent = parent.parent;
684
+ }
685
+ let forceRefresh = false;
686
+ for (let i = 0; i < stack.length; i++) {
687
+ const it = stack[i];
688
+ const route$1 = it.route;
689
+ const config = {};
690
+ try {
691
+ this.convertStringObjectToObject(route$1.schema?.query, state.query);
692
+ config.query = route$1.schema?.query ? this.alepha.codec.decode(route$1.schema.query, state.query) : {};
693
+ } catch (e) {
694
+ it.error = e;
695
+ break;
696
+ }
697
+ try {
698
+ config.params = route$1.schema?.params ? this.alepha.codec.decode(route$1.schema.params, state.params) : {};
699
+ } catch (e) {
700
+ it.error = e;
701
+ break;
702
+ }
703
+ it.config = { ...config };
704
+ if (previous?.[i] && !forceRefresh && previous[i].name === route$1.name) {
705
+ const url = (str) => str ? str.replace(/\/\/+/g, "/") : "/";
706
+ if (JSON.stringify({
707
+ part: url(previous[i].part),
708
+ params: previous[i].config?.params ?? {}
709
+ }) === JSON.stringify({
710
+ part: url(route$1.path),
711
+ params: config.params ?? {}
712
+ })) {
713
+ it.props = previous[i].props;
714
+ it.error = previous[i].error;
715
+ it.cache = true;
716
+ context = {
717
+ ...context,
718
+ ...it.props
719
+ };
720
+ continue;
721
+ }
722
+ forceRefresh = true;
723
+ }
724
+ if (!route$1.resolve) continue;
725
+ try {
726
+ const args = Object.create(state);
727
+ Object.assign(args, config, context);
728
+ const props = await route$1.resolve?.(args) ?? {};
729
+ it.props = { ...props };
730
+ context = {
731
+ ...context,
732
+ ...props
733
+ };
734
+ } catch (e) {
735
+ if (e instanceof Redirection) return { redirect: e.redirect };
736
+ this.log.error("Page resolver has failed", e);
737
+ it.error = e;
738
+ break;
739
+ }
740
+ }
741
+ let acc = "";
742
+ for (let i = 0; i < stack.length; i++) {
743
+ const it = stack[i];
744
+ const props = it.props ?? {};
745
+ const params = { ...it.config?.params };
746
+ for (const key of Object.keys(params)) params[key] = String(params[key]);
747
+ acc += "/";
748
+ acc += it.route.path ? this.compile(it.route.path, params) : "";
749
+ const path = acc.replace(/\/+/, "/");
750
+ const localErrorHandler = this.getErrorHandler(it.route);
751
+ if (localErrorHandler) {
752
+ const onErrorParent = state.onError;
753
+ state.onError = (error, context$1) => {
754
+ const result = localErrorHandler(error, context$1);
755
+ if (result === void 0) return onErrorParent(error, context$1);
756
+ return result;
757
+ };
758
+ }
759
+ if (!it.error) try {
760
+ const element = await this.createElement(it.route, {
761
+ ...props,
762
+ ...context
763
+ });
764
+ state.layers.push({
765
+ name: it.route.name,
766
+ props,
767
+ part: it.route.path,
768
+ config: it.config,
769
+ element: this.renderView(i + 1, path, element, it.route),
770
+ index: i + 1,
771
+ path,
772
+ route: it.route,
773
+ cache: it.cache
774
+ });
775
+ } catch (e) {
776
+ it.error = e;
777
+ }
778
+ if (it.error) try {
779
+ let element = await state.onError(it.error, state);
780
+ if (element === void 0) throw it.error;
781
+ if (element instanceof Redirection) return { redirect: element.redirect };
782
+ if (element === null) element = this.renderError(it.error);
783
+ state.layers.push({
784
+ props,
785
+ error: it.error,
786
+ name: it.route.name,
787
+ part: it.route.path,
788
+ config: it.config,
789
+ element: this.renderView(i + 1, path, element, it.route),
790
+ index: i + 1,
791
+ path,
792
+ route: it.route
793
+ });
794
+ break;
795
+ } catch (e) {
796
+ if (e instanceof Redirection) return { redirect: e.redirect };
797
+ throw e;
798
+ }
799
+ }
800
+ return { state };
801
+ }
802
+ createRedirectionLayer(redirect) {
803
+ return { redirect };
804
+ }
805
+ getErrorHandler(route) {
806
+ if (route.errorHandler) return route.errorHandler;
807
+ let parent = route.parent;
808
+ while (parent) {
809
+ if (parent.errorHandler) return parent.errorHandler;
810
+ parent = parent.parent;
811
+ }
812
+ }
813
+ async createElement(page, props) {
814
+ if (page.lazy && page.component) this.log.warn(`Page ${page.name} has both lazy and component options, lazy will be used`);
815
+ if (page.lazy) return createElement((await page.lazy()).default, props);
816
+ if (page.component) return createElement(page.component, props);
817
+ }
818
+ renderError(error) {
819
+ return createElement(ErrorViewer_default, {
820
+ error,
821
+ alepha: this.alepha
822
+ });
823
+ }
824
+ renderEmptyView() {
825
+ return createElement(NestedView_default, {});
826
+ }
827
+ href(page, params = {}) {
828
+ const found = this.pages.find((it) => it.name === page.options.name);
829
+ if (!found) throw new Error(`Page ${page.options.name} not found`);
830
+ let url = found.path ?? "";
831
+ let parent = found.parent;
832
+ while (parent) {
833
+ url = `${parent.path ?? ""}/${url}`;
834
+ parent = parent.parent;
835
+ }
836
+ url = this.compile(url, params);
837
+ return url.replace(/\/\/+/g, "/") || "/";
838
+ }
839
+ compile(path, params = {}) {
840
+ for (const [key, value] of Object.entries(params)) path = path.replace(`:${key}`, value);
841
+ return path;
842
+ }
843
+ renderView(index, path, view, page) {
844
+ view ??= this.renderEmptyView();
845
+ const element = page.client ? createElement(ClientOnly_default, typeof page.client === "object" ? page.client : {}, view) : view;
846
+ return createElement(RouterLayerContext.Provider, { value: {
847
+ index,
848
+ path
849
+ } }, element);
850
+ }
851
+ configure = $hook({
852
+ on: "configure",
853
+ handler: () => {
854
+ let hasNotFoundHandler = false;
855
+ const pages = this.alepha.descriptors($page);
856
+ const hasParent = (it) => {
857
+ if (it.options.parent) return true;
858
+ for (const page of pages) if ((page.options.children ? Array.isArray(page.options.children) ? page.options.children : page.options.children() : []).includes(it)) return true;
859
+ };
860
+ for (const page of pages) {
861
+ if (page.options.path === "/*") hasNotFoundHandler = true;
862
+ if (hasParent(page)) continue;
863
+ this.add(this.map(pages, page));
864
+ }
865
+ if (!hasNotFoundHandler && pages.length > 0) this.add({
866
+ path: "/*",
867
+ name: "notFound",
868
+ cache: true,
869
+ component: NotFoundPage,
870
+ onServerResponse: ({ reply }) => {
871
+ reply.status = 404;
872
+ }
873
+ });
874
+ }
875
+ });
876
+ map(pages, target) {
877
+ const children = target.options.children ? Array.isArray(target.options.children) ? target.options.children : target.options.children() : [];
878
+ const getChildrenFromParent = (it) => {
879
+ const children$1 = [];
880
+ for (const page of pages) if (page.options.parent === it) children$1.push(page);
881
+ return children$1;
882
+ };
883
+ children.push(...getChildrenFromParent(target));
884
+ return {
885
+ ...target.options,
886
+ name: target.name,
887
+ parent: void 0,
888
+ children: children.map((it) => this.map(pages, it))
889
+ };
890
+ }
891
+ add(entry) {
892
+ if (this.alepha.isReady()) throw new AlephaError("Router is already initialized");
893
+ entry.name ??= this.nextId();
894
+ const page = entry;
895
+ page.match = this.createMatch(page);
896
+ this.pages.push(page);
897
+ if (page.children) for (const child of page.children) {
898
+ child.parent = page;
899
+ this.add(child);
900
+ }
901
+ }
902
+ createMatch(page) {
903
+ let url = page.path ?? "/";
904
+ let target = page.parent;
905
+ while (target) {
906
+ url = `${target.path ?? ""}/${url}`;
907
+ target = target.parent;
908
+ }
909
+ let path = url.replace(/\/\/+/g, "/");
910
+ if (path.endsWith("/") && path !== "/") path = path.slice(0, -1);
911
+ return path;
912
+ }
913
+ _next = 0;
914
+ nextId() {
915
+ this._next += 1;
916
+ return `P${this._next}`;
917
+ }
918
+ };
919
+ const isPageRoute = (it) => {
920
+ return it && typeof it === "object" && typeof it.path === "string" && typeof it.page === "object";
921
+ };
922
+
923
+ //#endregion
924
+ //#region src/core/providers/ReactBrowserRouterProvider.ts
925
+ var ReactBrowserRouterProvider = class extends RouterProvider {
926
+ log = $logger();
927
+ alepha = $inject(Alepha);
928
+ pageApi = $inject(ReactPageProvider);
929
+ add(entry) {
930
+ this.pageApi.add(entry);
931
+ }
932
+ configure = $hook({
933
+ on: "configure",
934
+ handler: async () => {
935
+ for (const page of this.pageApi.getPages()) if (page.component || page.lazy) this.push({
936
+ path: page.match,
937
+ page
938
+ });
939
+ }
940
+ });
941
+ async transition(url, previous = [], meta = {}) {
942
+ const { pathname, search } = url;
943
+ const state = {
944
+ url,
945
+ query: {},
946
+ params: {},
947
+ layers: [],
948
+ onError: () => null,
949
+ meta
950
+ };
951
+ await this.alepha.events.emit("react:action:begin", { type: "transition" });
952
+ await this.alepha.events.emit("react:transition:begin", {
953
+ previous: this.alepha.state.get("alepha.react.router.state"),
954
+ state
955
+ });
956
+ try {
957
+ const { route, params } = this.match(pathname);
958
+ const query = {};
959
+ if (search) for (const [key, value] of new URLSearchParams(search).entries()) query[key] = String(value);
960
+ state.query = query;
961
+ state.params = params ?? {};
962
+ if (isPageRoute(route)) {
963
+ const { redirect } = await this.pageApi.createLayers(route.page, state, previous);
964
+ if (redirect) return redirect;
965
+ }
966
+ if (state.layers.length === 0) state.layers.push({
967
+ name: "not-found",
968
+ element: createElement(NotFoundPage),
969
+ index: 0,
970
+ path: "/"
971
+ });
972
+ await this.alepha.events.emit("react:action:success", { type: "transition" });
973
+ await this.alepha.events.emit("react:transition:success", { state });
974
+ } catch (e) {
975
+ this.log.error("Transition has failed", e);
976
+ state.layers = [{
977
+ name: "error",
978
+ element: this.pageApi.renderError(e),
979
+ index: 0,
980
+ path: "/"
981
+ }];
982
+ await this.alepha.events.emit("react:action:error", {
983
+ type: "transition",
984
+ error: e
985
+ });
986
+ await this.alepha.events.emit("react:transition:error", {
987
+ error: e,
988
+ state
989
+ });
990
+ }
991
+ if (previous) for (let i = 0; i < previous.length; i++) {
992
+ const layer = previous[i];
993
+ if (state.layers[i]?.name !== layer.name) this.pageApi.page(layer.name)?.onLeave?.();
994
+ }
995
+ this.alepha.state.set("alepha.react.router.state", state);
996
+ await this.alepha.events.emit("react:action:end", { type: "transition" });
997
+ await this.alepha.events.emit("react:transition:end", { state });
998
+ }
999
+ root(state) {
1000
+ return this.pageApi.root(state);
1001
+ }
1002
+ };
1003
+
1004
+ //#endregion
1005
+ //#region src/core/providers/ReactBrowserProvider.ts
1006
+ const envSchema = t.object({ REACT_ROOT_ID: t.text({ default: "root" }) });
1007
+ /**
1008
+ * React browser renderer configuration atom
1009
+ */
1010
+ const reactBrowserOptions = $atom({
1011
+ name: "alepha.react.browser.options",
1012
+ schema: t.object({ scrollRestoration: t.enum(["top", "manual"]) }),
1013
+ default: { scrollRestoration: "top" }
1014
+ });
1015
+ var ReactBrowserProvider = class {
1016
+ env = $env(envSchema);
1017
+ log = $logger();
1018
+ client = $inject(LinkProvider);
1019
+ alepha = $inject(Alepha);
1020
+ router = $inject(ReactBrowserRouterProvider);
1021
+ dateTimeProvider = $inject(DateTimeProvider);
1022
+ options = $use(reactBrowserOptions);
1023
+ getRootElement() {
1024
+ const root = this.document.getElementById(this.env.REACT_ROOT_ID);
1025
+ if (root) return root;
1026
+ const div = this.document.createElement("div");
1027
+ div.id = this.env.REACT_ROOT_ID;
1028
+ this.document.body.prepend(div);
1029
+ return div;
1030
+ }
1031
+ transitioning;
1032
+ get state() {
1033
+ return this.alepha.state.get("alepha.react.router.state");
1034
+ }
1035
+ /**
1036
+ * Accessor for Document DOM API.
1037
+ */
1038
+ get document() {
1039
+ return window.document;
1040
+ }
1041
+ /**
1042
+ * Accessor for History DOM API.
1043
+ */
1044
+ get history() {
1045
+ return window.history;
1046
+ }
1047
+ /**
1048
+ * Accessor for Location DOM API.
1049
+ */
1050
+ get location() {
1051
+ return window.location;
1052
+ }
1053
+ get base() {
1054
+ const base = import.meta.env?.BASE_URL;
1055
+ if (!base || base === "/") return "";
1056
+ return base;
1057
+ }
1058
+ get url() {
1059
+ const url = this.location.pathname + this.location.search;
1060
+ if (this.base) return url.replace(this.base, "");
1061
+ return url;
1062
+ }
1063
+ pushState(path, replace) {
1064
+ const url = this.base + path;
1065
+ if (replace) this.history.replaceState({}, "", url);
1066
+ else this.history.pushState({}, "", url);
1067
+ }
1068
+ async invalidate(props) {
1069
+ const previous = [];
1070
+ this.log.trace("Invalidating layers");
1071
+ if (props) {
1072
+ const [key] = Object.keys(props);
1073
+ const value = props[key];
1074
+ for (const layer of this.state.layers) {
1075
+ if (layer.props?.[key]) {
1076
+ previous.push({
1077
+ ...layer,
1078
+ props: {
1079
+ ...layer.props,
1080
+ [key]: value
1081
+ }
1082
+ });
1083
+ break;
1084
+ }
1085
+ previous.push(layer);
1086
+ }
1087
+ }
1088
+ await this.render({ previous });
1089
+ }
1090
+ async go(url, options = {}) {
1091
+ this.log.trace(`Going to ${url}`, {
1092
+ url,
1093
+ options
1094
+ });
1095
+ await this.render({
1096
+ url,
1097
+ previous: options.force ? [] : this.state.layers,
1098
+ meta: options.meta
1099
+ });
1100
+ if (this.state.url.pathname + this.state.url.search !== url) {
1101
+ this.pushState(this.state.url.pathname + this.state.url.search);
1102
+ return;
1103
+ }
1104
+ this.pushState(url, options.replace);
1105
+ }
1106
+ async render(options = {}) {
1107
+ const previous = options.previous ?? this.state.layers;
1108
+ const url = options.url ?? this.url;
1109
+ const start = this.dateTimeProvider.now();
1110
+ this.transitioning = {
1111
+ to: url,
1112
+ from: this.state?.url.pathname
1113
+ };
1114
+ this.log.debug("Transitioning...", { to: url });
1115
+ const redirect = await this.router.transition(new URL(`http://localhost${url}`), previous, options.meta);
1116
+ if (redirect) {
1117
+ this.log.info("Redirecting to", { redirect });
1118
+ if (redirect.startsWith("http")) window.location.href = redirect;
1119
+ else return await this.render({ url: redirect });
1120
+ }
1121
+ const ms = this.dateTimeProvider.now().diff(start);
1122
+ this.log.info(`Transition OK [${ms}ms]`, this.transitioning);
1123
+ this.transitioning = void 0;
1124
+ }
1125
+ /**
1126
+ * Get embedded layers from the server.
1127
+ */
1128
+ getHydrationState() {
1129
+ try {
1130
+ if ("__ssr" in window && typeof window.__ssr === "object") return window.__ssr;
1131
+ } catch (error) {
1132
+ console.error(error);
1133
+ }
1134
+ }
1135
+ onTransitionEnd = $hook({
1136
+ on: "react:transition:end",
1137
+ handler: () => {
1138
+ if (this.options.scrollRestoration === "top" && typeof window !== "undefined" && !this.alepha.isTest()) {
1139
+ this.log.trace("Restoring scroll position to top");
1140
+ window.scrollTo(0, 0);
1141
+ }
1142
+ }
1143
+ });
1144
+ ready = $hook({
1145
+ on: "ready",
1146
+ handler: async () => {
1147
+ const hydration = this.getHydrationState();
1148
+ const previous = hydration?.layers ?? [];
1149
+ if (hydration) {
1150
+ for (const [key, value] of Object.entries(hydration)) if (key !== "layers") this.alepha.state.set(key, value);
1151
+ }
1152
+ await this.render({ previous });
1153
+ const element = this.router.root(this.state);
1154
+ await this.alepha.events.emit("react:browser:render", {
1155
+ element,
1156
+ root: this.getRootElement(),
1157
+ hydration,
1158
+ state: this.state
1159
+ });
1160
+ window.addEventListener("popstate", () => {
1161
+ if (this.base + this.state.url.pathname === this.location.pathname) return;
1162
+ this.log.debug("Popstate event triggered - rendering new state", { url: this.location.pathname + this.location.search });
1163
+ this.render();
1164
+ });
1165
+ }
1166
+ });
1167
+ };
1168
+
1169
+ //#endregion
1170
+ //#region src/core/providers/ReactBrowserRendererProvider.ts
1171
+ var ReactBrowserRendererProvider = class {
1172
+ log = $logger();
1173
+ root;
1174
+ onBrowserRender = $hook({
1175
+ on: "react:browser:render",
1176
+ handler: async ({ hydration, root, element }) => {
1177
+ if (hydration?.layers) {
1178
+ this.root = hydrateRoot(root, element);
1179
+ this.log.info("Hydrated root element");
1180
+ } else {
1181
+ this.root ??= createRoot(root);
1182
+ this.root.render(element);
1183
+ this.log.info("Created root element");
1184
+ }
1185
+ }
1186
+ });
1187
+ };
1188
+
1189
+ //#endregion
1190
+ //#region src/core/services/ReactRouter.ts
1191
+ var ReactRouter = class {
1192
+ alepha = $inject(Alepha);
1193
+ pageApi = $inject(ReactPageProvider);
1194
+ get state() {
1195
+ return this.alepha.state.get("alepha.react.router.state");
1196
+ }
1197
+ get pages() {
1198
+ return this.pageApi.getPages();
1199
+ }
1200
+ get concretePages() {
1201
+ return this.pageApi.getConcretePages();
1202
+ }
1203
+ get browser() {
1204
+ if (this.alepha.isBrowser()) return this.alepha.inject(ReactBrowserProvider);
1205
+ }
1206
+ isActive(href, options = {}) {
1207
+ const current = this.state.url.pathname;
1208
+ let isActive = current === href || current === `${href}/` || `${current}/` === href;
1209
+ if (options.startWith && !isActive) isActive = current.startsWith(href);
1210
+ return isActive;
1211
+ }
1212
+ path(name, config = {}) {
1213
+ return this.pageApi.pathname(name, {
1214
+ params: {
1215
+ ...this.state.params,
1216
+ ...config.params
1217
+ },
1218
+ query: config.query
1219
+ });
1220
+ }
1221
+ /**
1222
+ * Reload the current page.
1223
+ * This is equivalent to calling `go()` with the current pathname and search.
1224
+ */
1225
+ async reload() {
1226
+ if (!this.browser) return;
1227
+ await this.go(this.location.pathname + this.location.search, {
1228
+ replace: true,
1229
+ force: true
1230
+ });
1231
+ }
1232
+ getURL() {
1233
+ if (!this.browser) return this.state.url;
1234
+ return new URL(this.location.href);
1235
+ }
1236
+ get location() {
1237
+ if (!this.browser) throw new Error("Browser is required");
1238
+ return this.browser.location;
1239
+ }
1240
+ get current() {
1241
+ return this.state;
1242
+ }
1243
+ get pathname() {
1244
+ return this.state.url.pathname;
1245
+ }
1246
+ get query() {
1247
+ const query = {};
1248
+ for (const [key, value] of new URLSearchParams(this.state.url.search).entries()) query[key] = String(value);
1249
+ return query;
1250
+ }
1251
+ async back() {
1252
+ this.browser?.history.back();
1253
+ }
1254
+ async forward() {
1255
+ this.browser?.history.forward();
1256
+ }
1257
+ async invalidate(props) {
1258
+ await this.browser?.invalidate(props);
1259
+ }
1260
+ async go(path, options) {
1261
+ for (const page of this.pages) if (page.name === path) {
1262
+ await this.browser?.go(this.path(path, options), options);
1263
+ return;
1264
+ }
1265
+ await this.browser?.go(path, options);
1266
+ }
1267
+ anchor(path, options = {}) {
1268
+ let href = path;
1269
+ for (const page of this.pages) if (page.name === path) {
1270
+ href = this.path(path, options);
1271
+ break;
1272
+ }
1273
+ return {
1274
+ href: this.base(href),
1275
+ onClick: (ev) => {
1276
+ ev.stopPropagation();
1277
+ ev.preventDefault();
1278
+ this.go(href, options).catch(console.error);
1279
+ }
1280
+ };
1281
+ }
1282
+ base(path) {
1283
+ const base = import.meta.env?.BASE_URL;
1284
+ if (!base || base === "/") return path;
1285
+ return base + path;
1286
+ }
1287
+ /**
1288
+ * Set query params.
1289
+ *
1290
+ * @param record
1291
+ * @param options
1292
+ */
1293
+ setQueryParams(record, options = {}) {
1294
+ const func = typeof record === "function" ? record : () => record;
1295
+ const search = new URLSearchParams(func(this.query)).toString();
1296
+ const state = search ? `${this.pathname}?${search}` : this.pathname;
1297
+ if (options.push) window.history.pushState({}, "", state);
1298
+ else window.history.replaceState({}, "", state);
1299
+ }
1300
+ };
1301
+
1302
+ //#endregion
1303
+ //#region src/core/hooks/useInject.ts
1304
+ /**
1305
+ * Hook to inject a service instance.
1306
+ * It's a wrapper of `useAlepha().inject(service)` with a memoization.
1307
+ */
1308
+ const useInject = (service) => {
1309
+ const alepha = useAlepha();
1310
+ return useMemo(() => alepha.inject(service), []);
1311
+ };
1312
+
1313
+ //#endregion
1314
+ //#region src/core/index.browser.ts
1315
+ const AlephaReact = $module({
1316
+ name: "alepha.react",
1317
+ descriptors: [$page],
1318
+ services: [
1319
+ ReactPageProvider,
1320
+ ReactBrowserRouterProvider,
1321
+ ReactBrowserProvider,
1322
+ ReactRouter,
1323
+ ReactBrowserRendererProvider,
1324
+ ReactPageService
1325
+ ],
1326
+ register: (alepha) => alepha.with(AlephaDateTime).with(AlephaServer).with(AlephaServerLinks).with(ReactPageProvider).with(ReactBrowserProvider).with(ReactBrowserRouterProvider).with(ReactBrowserRendererProvider).with(ReactRouter)
1327
+ });
1328
+
1329
+ //#endregion
1330
+ //#region src/head/providers/HeadProvider.ts
1331
+ var HeadProvider = class {
1332
+ global;
1333
+ getGlobalHead() {
1334
+ if (typeof this.global === "function") return this.global();
1335
+ return this.global;
1336
+ }
1337
+ fillHead(state) {
1338
+ state.head = {
1339
+ ...state.head,
1340
+ ...this.getGlobalHead()
1341
+ };
1342
+ for (const layer of state.layers) if (layer.route?.head && !layer.error) this.fillHeadByPage(layer.route, state, layer.props ?? {});
1343
+ }
1344
+ fillHeadByPage(page, state, props) {
1345
+ if (!page.head) return;
1346
+ state.head ??= {};
1347
+ const head = typeof page.head === "function" ? page.head(props, state.head) : page.head;
1348
+ if (head.title) {
1349
+ state.head ??= {};
1350
+ if (state.head.titleSeparator) state.head.title = `${head.title}${state.head.titleSeparator}${state.head.title}`;
1351
+ else state.head.title = head.title;
1352
+ state.head.titleSeparator = head.titleSeparator;
1353
+ }
1354
+ if (head.htmlAttributes) state.head.htmlAttributes = {
1355
+ ...state.head.htmlAttributes,
1356
+ ...head.htmlAttributes
1357
+ };
1358
+ if (head.bodyAttributes) state.head.bodyAttributes = {
1359
+ ...state.head.bodyAttributes,
1360
+ ...head.bodyAttributes
1361
+ };
1362
+ if (head.meta) state.head.meta = [...state.head.meta ?? [], ...head.meta ?? []];
1363
+ }
1364
+ };
1365
+
1366
+ //#endregion
1367
+ //#region src/head/descriptors/$head.ts
1368
+ /**
1369
+ * Set global `<head>` options for the application.
1370
+ */
1371
+ const $head = (options) => {
1372
+ return createDescriptor(HeadDescriptor, options);
1373
+ };
1374
+ var HeadDescriptor = class extends Descriptor {
1375
+ provider = $inject(HeadProvider);
1376
+ onInit() {
1377
+ this.provider.global = this.options;
1378
+ }
1379
+ };
1380
+ $head[KIND] = HeadDescriptor;
1381
+
1382
+ //#endregion
1383
+ //#region src/head/providers/BrowserHeadProvider.ts
1384
+ var BrowserHeadProvider = class {
1385
+ headProvider = $inject(HeadProvider);
1386
+ get document() {
1387
+ return window.document;
1388
+ }
1389
+ onBrowserRender = $hook({
1390
+ on: "react:browser:render",
1391
+ handler: async ({ state }) => {
1392
+ this.headProvider.fillHead(state);
1393
+ if (state.head) this.renderHead(this.document, state.head);
1394
+ }
1395
+ });
1396
+ onTransitionEnd = $hook({
1397
+ on: "react:transition:end",
1398
+ handler: async ({ state }) => {
1399
+ this.headProvider.fillHead(state);
1400
+ if (state.head) this.renderHead(this.document, state.head);
1401
+ }
1402
+ });
1403
+ getHead(document) {
1404
+ return {
1405
+ get title() {
1406
+ return document.title;
1407
+ },
1408
+ get htmlAttributes() {
1409
+ const attrs = {};
1410
+ for (const attr of document.documentElement.attributes) attrs[attr.name] = attr.value;
1411
+ return attrs;
1412
+ },
1413
+ get bodyAttributes() {
1414
+ const attrs = {};
1415
+ for (const attr of document.body.attributes) attrs[attr.name] = attr.value;
1416
+ return attrs;
1417
+ },
1418
+ get meta() {
1419
+ const metas = [];
1420
+ for (const meta of document.head.querySelectorAll("meta[name]")) {
1421
+ const name = meta.getAttribute("name");
1422
+ const content = meta.getAttribute("content");
1423
+ if (name && content) metas.push({
1424
+ name,
1425
+ content
1426
+ });
1427
+ }
1428
+ return metas;
1429
+ }
1430
+ };
1431
+ }
1432
+ renderHead(document, head) {
1433
+ if (head.title) document.title = head.title;
1434
+ if (head.bodyAttributes) for (const [key, value] of Object.entries(head.bodyAttributes)) if (value) document.body.setAttribute(key, value);
1435
+ else document.body.removeAttribute(key);
1436
+ if (head.htmlAttributes) for (const [key, value] of Object.entries(head.htmlAttributes)) if (value) document.documentElement.setAttribute(key, value);
1437
+ else document.documentElement.removeAttribute(key);
1438
+ if (head.meta) for (const it of head.meta) {
1439
+ const { name, content } = it;
1440
+ const meta = document.querySelector(`meta[name="${name}"]`);
1441
+ if (meta) meta.setAttribute("content", content);
1442
+ else {
1443
+ const newMeta = document.createElement("meta");
1444
+ newMeta.setAttribute("name", name);
1445
+ newMeta.setAttribute("content", content);
1446
+ document.head.appendChild(newMeta);
1447
+ }
1448
+ }
1449
+ }
1450
+ };
1451
+
1452
+ //#endregion
1453
+ //#region src/head/hooks/useHead.ts
1454
+ /**
1455
+ * ```tsx
1456
+ * const App = () => {
1457
+ * const [head, setHead] = useHead({
1458
+ * // will set the document title on the first render
1459
+ * title: "My App",
1460
+ * });
1461
+ *
1462
+ * return (
1463
+ * // This will update the document title when the button is clicked
1464
+ * <button onClick={() => setHead({ title: "Change Title" })}>
1465
+ * Change Title {head.title}
1466
+ * </button>
1467
+ * );
1468
+ * }
1469
+ * ```
1470
+ */
1471
+ const useHead = (options) => {
1472
+ const alepha = useInject(Alepha);
1473
+ const current = useMemo(() => {
1474
+ if (!alepha.isBrowser()) return {};
1475
+ return alepha.inject(BrowserHeadProvider).getHead(window.document);
1476
+ }, []);
1477
+ const setHead = useCallback((head) => {
1478
+ if (!alepha.isBrowser()) return;
1479
+ alepha.inject(BrowserHeadProvider).renderHead(window.document, typeof head === "function" ? head(current) : head || {});
1480
+ }, []);
1481
+ useEffect(() => {
1482
+ if (options) setHead(options);
1483
+ }, []);
1484
+ return [current, setHead];
1485
+ };
1486
+
1487
+ //#endregion
1488
+ //#region src/head/index.browser.ts
1489
+ /**
1490
+ * Alepha React Head Module
1491
+ *
1492
+ * @see {@link BrowserHeadProvider}
1493
+ * @module alepha.react.head
1494
+ */
1495
+ const AlephaReactHead = $module({
1496
+ name: "alepha.react.head",
1497
+ descriptors: [$head],
1498
+ services: [AlephaReact, BrowserHeadProvider]
1499
+ });
1500
+
1501
+ //#endregion
1502
+ export { $head, AlephaReactHead, BrowserHeadProvider, HeadDescriptor, useHead };
1503
+ //# sourceMappingURL=index.browser.js.map