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