@modern-js/runtime 2.6.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +2 -2
  3. package/dist/cjs/cli/index.js +4 -3
  4. package/dist/cjs/common.js +6 -0
  5. package/dist/cjs/core/{app-config.js → appConfig.js} +3 -3
  6. package/dist/cjs/core/compatible.js +4 -4
  7. package/dist/cjs/core/index.js +6 -6
  8. package/dist/cjs/core/loader/useLoader.js +2 -2
  9. package/dist/cjs/core/types.js +15 -0
  10. package/dist/cjs/router/runtime/DeferredDataScripts.js +165 -0
  11. package/dist/cjs/router/runtime/index.js +116 -3
  12. package/dist/cjs/router/runtime/plugin.js +14 -1
  13. package/dist/cjs/router/runtime/plugin.node.js +12 -52
  14. package/dist/cjs/router/runtime/utils.js +68 -69
  15. package/dist/cjs/{runtime-context.js → runtimeContext.js} +3 -3
  16. package/dist/cjs/ssr/cli/index.js +3 -2
  17. package/dist/cjs/ssr/index.node.js +1 -0
  18. package/dist/cjs/ssr/serverRender/renderToStream/buildTemplate.after.js +2 -14
  19. package/dist/cjs/ssr/serverRender/renderToStream/bulidTemplate.before.js +5 -1
  20. package/dist/cjs/ssr/serverRender/renderToStream/renderToPipe.js +22 -7
  21. package/dist/cjs/ssr/serverRender/renderToStream/template.js +2 -1
  22. package/dist/cjs/ssr/serverRender/renderToString/entry.js +19 -8
  23. package/dist/cjs/state/runtime/index.js +2 -8
  24. package/dist/esm/cli/index.js +4 -3
  25. package/dist/esm/common.js +3 -1
  26. package/dist/esm/core/compatible.js +1 -1
  27. package/dist/esm/core/index.js +2 -2
  28. package/dist/esm/core/loader/useLoader.js +1 -1
  29. package/dist/esm/core/types.js +1 -0
  30. package/dist/esm/router/runtime/DeferredDataScripts.js +166 -0
  31. package/dist/esm/router/runtime/index.js +3 -2
  32. package/dist/esm/router/runtime/plugin.js +11 -3
  33. package/dist/esm/router/runtime/plugin.node.js +11 -68
  34. package/dist/esm/router/runtime/utils.js +138 -81
  35. package/dist/esm/ssr/cli/index.js +4 -3
  36. package/dist/esm/ssr/index.node.js +1 -0
  37. package/dist/esm/ssr/serverRender/renderToStream/buildTemplate.after.js +2 -4
  38. package/dist/esm/ssr/serverRender/renderToStream/bulidTemplate.before.js +1 -1
  39. package/dist/esm/ssr/serverRender/renderToStream/renderToPipe.js +19 -8
  40. package/dist/esm/ssr/serverRender/renderToStream/template.js +2 -1
  41. package/dist/esm/ssr/serverRender/renderToString/entry.js +15 -7
  42. package/dist/esm/state/runtime/index.js +1 -2
  43. package/dist/esm-node/cli/index.js +4 -3
  44. package/dist/esm-node/common.js +4 -0
  45. package/dist/esm-node/core/compatible.js +1 -1
  46. package/dist/esm-node/core/index.js +2 -2
  47. package/dist/esm-node/core/loader/useLoader.js +1 -1
  48. package/dist/esm-node/core/types.js +0 -0
  49. package/dist/esm-node/router/runtime/DeferredDataScripts.js +148 -0
  50. package/dist/esm-node/router/runtime/index.js +113 -2
  51. package/dist/esm-node/router/runtime/plugin.js +15 -2
  52. package/dist/esm-node/router/runtime/plugin.node.js +12 -55
  53. package/dist/esm-node/router/runtime/utils.js +59 -69
  54. package/dist/esm-node/ssr/cli/index.js +4 -3
  55. package/dist/esm-node/ssr/index.node.js +1 -0
  56. package/dist/esm-node/ssr/serverRender/renderToStream/buildTemplate.after.js +2 -4
  57. package/dist/esm-node/ssr/serverRender/renderToStream/bulidTemplate.before.js +5 -1
  58. package/dist/esm-node/ssr/serverRender/renderToStream/renderToPipe.js +22 -7
  59. package/dist/esm-node/ssr/serverRender/renderToStream/template.js +2 -1
  60. package/dist/esm-node/ssr/serverRender/renderToString/entry.js +19 -8
  61. package/dist/esm-node/state/runtime/index.js +1 -4
  62. package/dist/types/common.d.ts +3 -1
  63. package/dist/types/core/compatible.d.ts +1 -1
  64. package/dist/types/core/index.d.ts +4 -3
  65. package/dist/types/core/loader/index.d.ts +1 -2
  66. package/dist/types/core/loader/useLoader.d.ts +1 -15
  67. package/dist/types/core/plugin.d.ts +15 -15
  68. package/dist/types/core/types.d.ts +22 -0
  69. package/dist/types/index.d.ts +1 -1
  70. package/dist/types/router/runtime/DeferredDataScripts.d.ts +8 -0
  71. package/dist/types/router/runtime/index.d.ts +4 -2
  72. package/dist/types/router/runtime/utils.d.ts +23 -4
  73. package/dist/types/{runtime-context.d.ts → runtimeContext.d.ts} +2 -0
  74. package/dist/types/ssr/serverRender/renderToStream/buildTemplate.after.d.ts +2 -0
  75. package/dist/types/state/runtime/index.d.ts +0 -1
  76. package/package.json +15 -18
  77. package/types/router.d.ts +1 -1
  78. /package/dist/esm/core/{app-config.js → appConfig.js} +0 -0
  79. /package/dist/esm/{runtime-context.js → runtimeContext.js} +0 -0
  80. /package/dist/esm-node/core/{app-config.js → appConfig.js} +0 -0
  81. /package/dist/esm-node/{runtime-context.js → runtimeContext.js} +0 -0
  82. /package/dist/types/core/{app-config.d.ts → appConfig.d.ts} +0 -0
@@ -59,13 +59,16 @@ function _objectSpreadProps(target, source) {
59
59
  }
60
60
  import { Transform } from "stream";
61
61
  import { RenderLevel } from "../types";
62
+ import { ESCAPED_SHELL_STREAM_END_MARK } from "../../../common";
62
63
  import { getTemplates } from "./template";
64
+ var ShellChunkStatus = /* @__PURE__ */ function(ShellChunkStatus2) {
65
+ ShellChunkStatus2[ShellChunkStatus2["IDLE"] = 0] = "IDLE";
66
+ ShellChunkStatus2[ShellChunkStatus2["START"] = 1] = "START";
67
+ ShellChunkStatus2[ShellChunkStatus2["FINIESH"] = 2] = "FINIESH";
68
+ return ShellChunkStatus2;
69
+ }(ShellChunkStatus || {});
63
70
  function renderToPipe(rootElement, context, options) {
64
- var joinChunk = function joinChunk() {
65
- var before = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "", chunk = arguments.length > 1 ? arguments[1] : void 0, after = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "";
66
- return "".concat(before).concat(chunk.toString()).concat(after);
67
- };
68
- var isShellStream = true;
71
+ var shellChunkStatus = 0 /* IDLE */ ;
69
72
  var ssrContext = context.ssrContext;
70
73
  var forUserPipe = function(stream) {
71
74
  return new Promise(function(resolve) {
@@ -81,9 +84,17 @@ function renderToPipe(rootElement, context, options) {
81
84
  var injectableTransform = new Transform({
82
85
  transform: function transform(chunk, _encoding, callback) {
83
86
  try {
84
- if (isShellStream) {
85
- this.push(joinChunk(shellBefore, chunk, shellAfter));
86
- isShellStream = false;
87
+ if (shellChunkStatus !== 2 /* FINIESH */ ) {
88
+ var concatedChunk = chunk.toString();
89
+ if (shellChunkStatus === 0 /* IDLE */ ) {
90
+ concatedChunk = "".concat(shellBefore).concat(concatedChunk);
91
+ shellChunkStatus = 1 /* START */ ;
92
+ }
93
+ if (shellChunkStatus === 1 /* START */ && concatedChunk.endsWith(ESCAPED_SHELL_STREAM_END_MARK)) {
94
+ concatedChunk = concatedChunk.replace(ESCAPED_SHELL_STREAM_END_MARK, shellAfter);
95
+ shellChunkStatus = 2 /* FINIESH */ ;
96
+ }
97
+ this.push(concatedChunk);
87
98
  } else {
88
99
  this.push(chunk);
89
100
  }
@@ -48,11 +48,12 @@ import { buildShellAfterTemplate } from "./buildTemplate.after";
48
48
  import { buildShellBeforeTemplate } from "./bulidTemplate.before";
49
49
  var HTML_SEPARATOR = "<!--<?- html ?>-->";
50
50
  var getTemplates = function(context, renderLevel) {
51
- var ssrContext = context.ssrContext;
51
+ var ssrContext = context.ssrContext, routerContext = context.routerContext;
52
52
  var _ref = _slicedToArray(ssrContext.template.split(HTML_SEPARATOR) || [], 2), tmp = _ref[0], beforeAppTemplate = tmp === void 0 ? "" : tmp, tmp1 = _ref[1], afterAppHtmlTemplate = tmp1 === void 0 ? "" : tmp1;
53
53
  var builtBeforeTemplate = buildShellBeforeTemplate(beforeAppTemplate, context);
54
54
  var builtAfterTemplate = buildShellAfterTemplate(afterAppHtmlTemplate, {
55
55
  ssrContext: ssrContext,
56
+ routerContext: routerContext,
56
57
  renderLevel: renderLevel
57
58
  });
58
59
  return {
@@ -171,8 +171,9 @@ var __generator = this && this.__generator || function(thisArg, body) {
171
171
  };
172
172
  import React from "react";
173
173
  import ReactDomServer from "react-dom/server";
174
- import serialize from "serialize-javascript";
174
+ import { serializeJson } from "@modern-js/utils/serialize";
175
175
  import ReactHelmet from "react-helmet";
176
+ import { serializeErrors } from "../../../router/runtime/utils";
176
177
  import helmetReplace from "../helmet";
177
178
  import { RenderLevel } from "../types";
178
179
  import { time } from "../time";
@@ -236,7 +237,7 @@ var Entry = /*#__PURE__*/ function() {
236
237
  value: function renderToHtml(context) {
237
238
  var _this = this;
238
239
  return _asyncToGenerator(function() {
239
- var _ssrContext_redirection, _ssrContext_redirection1, _ssrContext_redirection2, ssrContext, prefetchData, html, templateData, SSRData, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, fragment, helmetData;
240
+ var _ssrContext_redirection, _ssrContext_redirection1, _ssrContext_redirection2, ssrContext, prefetchData, routerContext, routerData, html, templateData, SSRData, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, fragment, helmetData;
240
241
  return __generator(this, function(_state) {
241
242
  switch(_state.label){
242
243
  case 0:
@@ -268,9 +269,14 @@ var Entry = /*#__PURE__*/ function() {
268
269
  ""
269
270
  ];
270
271
  }
272
+ routerContext = context.routerContext;
273
+ routerData = routerContext ? {
274
+ loaderData: routerContext.loaderData,
275
+ errors: serializeErrors(routerContext.errors)
276
+ } : void 0;
271
277
  html = "";
272
278
  templateData = buildTemplateData(ssrContext, prefetchData, _this.result.renderLevel);
273
- SSRData = _this.getSSRDataScript(templateData);
279
+ SSRData = _this.getSSRDataScript(templateData, routerData);
274
280
  _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
275
281
  try {
276
282
  for(_iterator = _this.fragments[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
@@ -395,11 +401,13 @@ var Entry = /*#__PURE__*/ function() {
395
401
  },
396
402
  {
397
403
  key: "getSSRDataScript",
398
- value: function getSSRDataScript(templateData) {
404
+ value: function getSSRDataScript(templateData, routerData) {
405
+ var ssrDataScripts = "<script>window._SSR_DATA = ".concat(serializeJson(templateData), "</script>");
406
+ if (routerData) {
407
+ ssrDataScripts += "\n<script>window._ROUTER_DATA = ".concat(serializeJson(routerData), "</script>");
408
+ }
399
409
  return {
400
- SSRDataScript: "\n <script>window._SSR_DATA = ".concat(serialize(templateData, {
401
- isJSON: true
402
- }), "</script>\n ")
410
+ SSRDataScript: ssrDataScripts
403
411
  };
404
412
  }
405
413
  }
@@ -1,5 +1,4 @@
1
1
  export * from "@modern-js-reduck/react";
2
- import { model, createStore } from "@modern-js-reduck/store";
3
2
  import { default as default2 } from "./plugin";
4
3
  export * from "./plugin";
5
- export { createStore, default2 as default, model };
4
+ export { default2 as default };
@@ -7,13 +7,14 @@ import Document from "../document/cli";
7
7
  var cli_default = () => ({
8
8
  name: "@modern-js/runtime",
9
9
  post: [
10
- "@modern-js/plugin-router",
11
10
  "@modern-js/plugin-ssr",
12
- "@modern-js/plugin-document",
13
11
  "@modern-js/plugin-state",
12
+ "@modern-js/plugin-router",
13
+ "@modern-js/plugin-document",
14
14
  "@modern-js/plugin-design-token"
15
15
  ],
16
- usePlugins: [PluginState(), PluginSSR(), PluginRouter(), Document()],
16
+ // the order of runtime plugins is affected by runtime hooks, mainly `init` and `hoc` hooks
17
+ usePlugins: [PluginSSR(), PluginState(), PluginRouter(), Document()],
17
18
  setup: (api) => {
18
19
  return {
19
20
  config() {
@@ -1,4 +1,8 @@
1
1
  const isBrowser = () => typeof window !== "undefined" && window.name !== "nodejs";
2
+ const JSX_SHELL_STREAM_END_MARK = "<!--<?- SHELL_STREAM_END ?>-->";
3
+ const ESCAPED_SHELL_STREAM_END_MARK = "&lt;!--&lt;?- SHELL_STREAM_END ?&gt;--&gt;";
2
4
  export {
5
+ ESCAPED_SHELL_STREAM_END_MARK,
6
+ JSX_SHELL_STREAM_END_MARK,
3
7
  isBrowser
4
8
  };
@@ -4,7 +4,7 @@ import hoistNonReactStatics from "hoist-non-react-statics";
4
4
  import { ROUTE_MANIFEST } from "@modern-js/utils/constants";
5
5
  import {
6
6
  RuntimeReactContext
7
- } from "../runtime-context";
7
+ } from "../runtimeContext";
8
8
  import { runtime } from "./plugin";
9
9
  import { createLoaderManager } from "./loader/loaderManager";
10
10
  const IS_REACT18 = process.env.IS_REACT18 === "true";
@@ -1,7 +1,7 @@
1
1
  import { createPlugin, createRuntime, runtime, registerInit } from "./plugin";
2
- import { defineConfig, getConfig } from "./app-config";
2
+ import { defineConfig, getConfig } from "./appConfig";
3
3
  export * from "./compatible";
4
- import { RuntimeReactContext, ServerRouterContext } from "../runtime-context";
4
+ import { RuntimeReactContext, ServerRouterContext } from "../runtimeContext";
5
5
  export * from "./loader";
6
6
  export * from "@modern-js/plugin";
7
7
  export {
@@ -7,7 +7,7 @@ import {
7
7
  useEffect
8
8
  } from "react";
9
9
  import invariant from "invariant";
10
- import { RuntimeReactContext } from "../../runtime-context";
10
+ import { RuntimeReactContext } from "../../runtimeContext";
11
11
  import { LoaderStatus } from "./loaderManager";
12
12
  const useLoader = (loaderFn, options = { params: void 0 }) => {
13
13
  const context = useContext(RuntimeReactContext);
File without changes
@@ -0,0 +1,148 @@
1
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
+ import { Suspense, useEffect, useRef, useMemo, useContext } from "react";
3
+ import {
4
+ Await,
5
+ UNSAFE_DataRouterContext as DataRouterContext,
6
+ useAsyncError
7
+ } from "react-router-dom";
8
+ import { serializeJson } from "@modern-js/utils/serialize";
9
+ import { JSX_SHELL_STREAM_END_MARK } from "../../common";
10
+ import { serializeErrors } from "./utils";
11
+ const setupFnStr = `function s(r,e){_ROUTER_DATA.r=_ROUTER_DATA.r||{},_ROUTER_DATA.r[r]=_ROUTER_DATA.r[r]||{};return new Promise((function(A,R){_ROUTER_DATA.r[r][e]={resolve:A,reject:R}}))};`;
12
+ const resolveFnStr = `function r(e,r,o,A){A?_ROUTER_DATA.r[e][r].reject(A):_ROUTER_DATA.r[e][r].resolve(o)};`;
13
+ const preResolvedFnStr = `function p(e,r){return void 0!==r?Promise.reject(new Error(r.message)):Promise.resovle(e)};`;
14
+ const DeferredDataScripts = () => {
15
+ const context = useContext(DataRouterContext);
16
+ const { staticContext } = context || {};
17
+ const hydratedRef = useRef(false);
18
+ useEffect(() => {
19
+ hydratedRef.current = true;
20
+ }, []);
21
+ const deferredScripts = useMemo(() => {
22
+ if (!staticContext) {
23
+ return null;
24
+ }
25
+ const activeDeferreds = staticContext.activeDeferreds || [];
26
+ const _ROUTER_DATA = {
27
+ loaderData: staticContext.loaderData,
28
+ errors: serializeErrors(staticContext.errors)
29
+ };
30
+ let initialScripts = [
31
+ `_ROUTER_DATA = ${serializeJson(_ROUTER_DATA)};`,
32
+ `_ROUTER_DATA.s = ${setupFnStr}`,
33
+ `_ROUTER_DATA.r = ${resolveFnStr}`,
34
+ `_ROUTER_DATA.p = ${preResolvedFnStr}`
35
+ ].join("\n");
36
+ const deferredDataScripts = [];
37
+ initialScripts += Object.entries(activeDeferreds).map(([routeId, deferredData]) => {
38
+ const pendingKeys = new Set(deferredData.pendingKeys);
39
+ const { deferredKeys } = deferredData;
40
+ const deferredKeyPromiseStr = deferredKeys.map((key) => {
41
+ if (pendingKeys.has(key)) {
42
+ deferredDataScripts.push(
43
+ /* @__PURE__ */ jsx(
44
+ DeferredDataScript,
45
+ {
46
+ data: deferredData.data[key],
47
+ dataKey: key,
48
+ routeId
49
+ },
50
+ `${routeId} | ${key}`
51
+ )
52
+ );
53
+ return `${JSON.stringify(key)}: _ROUTER_DATA.s(${JSON.stringify(
54
+ routeId
55
+ )},${JSON.stringify(key)}) `;
56
+ } else {
57
+ const trackedPromise = deferredData.data[key];
58
+ if (typeof trackedPromise._error !== "undefined") {
59
+ const error = {
60
+ message: trackedPromise._error.message,
61
+ stack: process.env.NODE_ENV !== "production" ? trackedPromise._error.stack : void 0
62
+ };
63
+ return `${JSON.stringify(
64
+ key
65
+ )}: _ROUTER_DATA.p(${void 0}, ${serializeJson(error)})`;
66
+ } else {
67
+ if (typeof trackedPromise._data === "undefined") {
68
+ throw new Error(
69
+ `The deferred data for ${key} was not resolved, did you forget to return data from a deferred promise`
70
+ );
71
+ }
72
+ return `${JSON.stringify(key)}: _ROUTER_DATA.p(${serializeJson(
73
+ trackedPromise._data
74
+ )})`;
75
+ }
76
+ }
77
+ }).join(",\n");
78
+ return `Object.assign(_ROUTER_DATA.loaderData[${JSON.stringify(
79
+ routeId
80
+ )}], {${deferredKeyPromiseStr}});`;
81
+ }).join("\n");
82
+ return [initialScripts, deferredDataScripts];
83
+ }, []);
84
+ if (!deferredScripts) {
85
+ return null;
86
+ }
87
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
88
+ !hydratedRef.current && /* @__PURE__ */ jsx(
89
+ "script",
90
+ {
91
+ async: true,
92
+ suppressHydrationWarning: true,
93
+ dangerouslySetInnerHTML: { __html: deferredScripts[0] }
94
+ }
95
+ ),
96
+ !hydratedRef.current && deferredScripts[1],
97
+ JSX_SHELL_STREAM_END_MARK
98
+ ] });
99
+ };
100
+ const DeferredDataScript = ({
101
+ data,
102
+ routeId,
103
+ dataKey
104
+ }) => {
105
+ return /* @__PURE__ */ jsx(Suspense, { children: typeof document === "undefined" && data && dataKey && routeId ? /* @__PURE__ */ jsx(
106
+ Await,
107
+ {
108
+ resolve: data,
109
+ errorElement: /* @__PURE__ */ jsx(ErrorDeferredDataScript, { routeId, dataKey }),
110
+ children: (data2) => /* @__PURE__ */ jsx(
111
+ "script",
112
+ {
113
+ async: true,
114
+ suppressHydrationWarning: true,
115
+ dangerouslySetInnerHTML: {
116
+ __html: `_ROUTER_DATA.r(${JSON.stringify(
117
+ routeId
118
+ )}, ${JSON.stringify(dataKey)}, ${serializeJson(data2)});`
119
+ }
120
+ }
121
+ )
122
+ }
123
+ ) : null });
124
+ };
125
+ const ErrorDeferredDataScript = ({
126
+ routeId,
127
+ dataKey
128
+ }) => {
129
+ const error = useAsyncError();
130
+ return /* @__PURE__ */ jsx(
131
+ "script",
132
+ {
133
+ suppressHydrationWarning: true,
134
+ dangerouslySetInnerHTML: {
135
+ __html: `_ROUTER_DATA.r(${JSON.stringify(routeId)}, ${JSON.stringify(
136
+ dataKey
137
+ )}, ${void 0}, ${serializeJson({
138
+ message: error.message,
139
+ stack: error.stack
140
+ })});`
141
+ }
142
+ }
143
+ );
144
+ };
145
+ var DeferredDataScripts_default = DeferredDataScripts;
146
+ export {
147
+ DeferredDataScripts_default as default
148
+ };
@@ -1,9 +1,120 @@
1
1
  import { routerPlugin } from "./plugin";
2
2
  var runtime_default = routerPlugin;
3
3
  import { modifyRoutes } from "./plugin";
4
- export * from "react-router-dom";
5
4
  export * from "./withRouter";
5
+ import {
6
+ createBrowserRouter,
7
+ createHashRouter,
8
+ createMemoryRouter,
9
+ RouterProvider,
10
+ BrowserRouter,
11
+ HashRouter,
12
+ MemoryRouter,
13
+ Router,
14
+ Await,
15
+ Form,
16
+ Link,
17
+ NavLink,
18
+ Navigate,
19
+ Outlet,
20
+ Route,
21
+ Routes,
22
+ ScrollRestoration,
23
+ useActionData,
24
+ useAsyncError,
25
+ useAsyncValue,
26
+ useBeforeUnload,
27
+ useFetcher,
28
+ useFetchers,
29
+ useFormAction,
30
+ useHref,
31
+ useInRouterContext,
32
+ useLinkClickHandler,
33
+ useLoaderData,
34
+ useLocation,
35
+ useMatch,
36
+ useMatches,
37
+ useNavigate,
38
+ useNavigation,
39
+ useNavigationType,
40
+ useOutlet,
41
+ useOutletContext,
42
+ useParams,
43
+ useResolvedPath,
44
+ useRevalidator,
45
+ useRouteError,
46
+ useRouteLoaderData,
47
+ useRoutes,
48
+ useSearchParams,
49
+ useSubmit,
50
+ createRoutesFromChildren,
51
+ createRoutesFromElements,
52
+ createSearchParams,
53
+ generatePath,
54
+ isRouteErrorResponse,
55
+ matchPath,
56
+ matchRoutes,
57
+ renderMatches,
58
+ resolvePath
59
+ } from "react-router-dom";
60
+ import { defer, json, redirect } from "@modern-js/utils/remix-router";
6
61
  export {
62
+ Await,
63
+ BrowserRouter,
64
+ Form,
65
+ HashRouter,
66
+ Link,
67
+ MemoryRouter,
68
+ NavLink,
69
+ Navigate,
70
+ Outlet,
71
+ Route,
72
+ Router,
73
+ RouterProvider,
74
+ Routes,
75
+ ScrollRestoration,
76
+ createBrowserRouter,
77
+ createHashRouter,
78
+ createMemoryRouter,
79
+ createRoutesFromChildren,
80
+ createRoutesFromElements,
81
+ createSearchParams,
7
82
  runtime_default as default,
8
- modifyRoutes
83
+ defer,
84
+ generatePath,
85
+ isRouteErrorResponse,
86
+ json,
87
+ matchPath,
88
+ matchRoutes,
89
+ modifyRoutes,
90
+ redirect,
91
+ renderMatches,
92
+ resolvePath,
93
+ useActionData,
94
+ useAsyncError,
95
+ useAsyncValue,
96
+ useBeforeUnload,
97
+ useFetcher,
98
+ useFetchers,
99
+ useFormAction,
100
+ useHref,
101
+ useInRouterContext,
102
+ useLinkClickHandler,
103
+ useLoaderData,
104
+ useLocation,
105
+ useMatch,
106
+ useMatches,
107
+ useNavigate,
108
+ useNavigation,
109
+ useNavigationType,
110
+ useOutlet,
111
+ useOutletContext,
112
+ useParams,
113
+ useResolvedPath,
114
+ useRevalidator,
115
+ useRouteError,
116
+ useRouteLoaderData,
117
+ useRoutes,
118
+ useSearchParams,
119
+ useSubmit
9
120
  };
@@ -8,7 +8,7 @@ import {
8
8
  useLocation
9
9
  } from "react-router-dom";
10
10
  import hoistNonReactStatics from "hoist-non-react-statics";
11
- import { renderRoutes, urlJoin } from "./utils";
11
+ import { deserializeErrors, renderRoutes, urlJoin } from "./utils";
12
12
  let finalRouteConfig = {
13
13
  routes: []
14
14
  };
@@ -55,7 +55,20 @@ const routerPlugin = ({
55
55
  const routes = createRoutes ? createRoutes() : createRoutesFromElements(renderRoutes(finalRouteConfig));
56
56
  const baseUrl = ((_a = window._SERVER_DATA) == null ? void 0 : _a.router.baseUrl) || select(location.pathname);
57
57
  const _basename = baseUrl === "/" ? urlJoin(baseUrl, basename) : baseUrl;
58
- const router = supportHtml5History ? createBrowserRouter(routes, { basename: _basename }) : createHashRouter(routes, { basename: _basename });
58
+ let hydrationData = window._ROUTER_DATA;
59
+ if (hydrationData == null ? void 0 : hydrationData.errors) {
60
+ hydrationData = {
61
+ ...hydrationData,
62
+ errors: deserializeErrors(hydrationData.errors)
63
+ };
64
+ }
65
+ const router = supportHtml5History ? createBrowserRouter(routes, {
66
+ basename: _basename,
67
+ hydrationData
68
+ }) : createHashRouter(routes, {
69
+ basename: _basename,
70
+ hydrationData
71
+ });
59
72
  return /* @__PURE__ */ jsx(App, { ...props, children: /* @__PURE__ */ jsx(RouterProvider, { router }) });
60
73
  };
61
74
  };
@@ -1,10 +1,6 @@
1
- import { jsx, jsxs } from "react/jsx-runtime";
1
+ import { jsx } from "react/jsx-runtime";
2
2
  import { useContext } from "react";
3
- import serialize from "serialize-javascript";
4
- import {
5
- createStaticHandler,
6
- isRouteErrorResponse
7
- } from "@remix-run/router";
3
+ import { createStaticHandler } from "@modern-js/utils/remix-router";
8
4
  import {
9
5
  createStaticRouter,
10
6
  StaticRouterProvider
@@ -41,26 +37,6 @@ function createFetchHeaders(requestHeaders) {
41
37
  }
42
38
  return headers;
43
39
  }
44
- function serializeErrors(errors) {
45
- if (!errors) {
46
- return null;
47
- }
48
- const entries = Object.entries(errors);
49
- const serialized = {};
50
- for (const [key, val] of entries) {
51
- if (isRouteErrorResponse(val)) {
52
- serialized[key] = { ...val, __type: "RouteErrorResponse" };
53
- } else if (val instanceof Error) {
54
- serialized[key] = {
55
- message: val.message,
56
- __type: "Error"
57
- };
58
- } else {
59
- serialized[key] = val;
60
- }
61
- }
62
- return serialized;
63
- }
64
40
  const routerPlugin = ({
65
41
  basename = "",
66
42
  routesConfig,
@@ -74,10 +50,10 @@ const routerPlugin = ({
74
50
  if (!routesConfig && !createRoutes) {
75
51
  return next({ context });
76
52
  }
77
- const { request } = context.ssrContext;
53
+ const { request, mode: ssrMode } = context.ssrContext;
78
54
  const baseUrl = request.baseUrl;
79
55
  const _basename = baseUrl === "/" ? urlJoin(baseUrl, basename) : baseUrl;
80
- const routes = createRoutes ? createRoutes() : createRoutesFromElements(renderRoutes(routesConfig));
56
+ const routes = createRoutes ? createRoutes() : createRoutesFromElements(renderRoutes(routesConfig, ssrMode));
81
57
  const { query } = createStaticHandler(routes, {
82
58
  basename: _basename
83
59
  });
@@ -100,33 +76,14 @@ const routerPlugin = ({
100
76
  const getRouteApp = () => {
101
77
  return (props) => {
102
78
  const { router, routerContext } = useContext(RuntimeReactContext);
103
- const data = {
104
- loaderData: routerContext.loaderData,
105
- actionData: routerContext.actionData,
106
- errors: serializeErrors(routerContext.errors)
107
- };
108
- const hydrateScript = `window.__staticRouterHydrationData = ${serialize(
109
- data,
110
- { isJSON: true }
111
- )};`;
112
- return /* @__PURE__ */ jsxs(App, { ...props, children: [
113
- /* @__PURE__ */ jsx(
114
- StaticRouterProvider,
115
- {
116
- router,
117
- context: routerContext,
118
- hydrate: false
119
- }
120
- ),
121
- /* @__PURE__ */ jsx(
122
- "script",
123
- {
124
- suppressHydrationWarning: true,
125
- id: "the-nonce",
126
- dangerouslySetInnerHTML: { __html: hydrateScript }
127
- }
128
- )
129
- ] });
79
+ return /* @__PURE__ */ jsx(App, { ...props, children: /* @__PURE__ */ jsx(
80
+ StaticRouterProvider,
81
+ {
82
+ router,
83
+ context: routerContext,
84
+ hydrate: false
85
+ }
86
+ ) });
130
87
  };
131
88
  };
132
89
  const RouteApp = getRouteApp();