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