@alepha/react 0.13.0 → 0.13.2

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