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