@modern-js/plugin-ssg 2.0.0-beta.0 → 2.0.0-beta.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/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @modern-js/plugin-ssg
2
2
 
3
+ ## 2.0.0-beta.1
4
+
5
+ ### Major Changes
6
+
7
+ - dda38c9: chore: v2
8
+
9
+ ### Patch Changes
10
+
11
+ - cc971eabfc: refactor: move server plugin load logic in `@modern-js/core`
12
+ refactor:移除在 `@modern-js/core` 中的 server 插件加载逻辑
13
+ - 8b8e1bb571: feat: support nested routes
14
+ feat: 支持嵌套路由
15
+ - Updated dependencies [92f0ead]
16
+ - Updated dependencies [edd1cfb1af]
17
+ - Updated dependencies [cc971eabfc]
18
+ - Updated dependencies [5b9049f]
19
+ - Updated dependencies [92004d1]
20
+ - Updated dependencies [b8bbe036c7]
21
+ - Updated dependencies [d5a31df781]
22
+ - Updated dependencies [dda38c9]
23
+ - Updated dependencies [3bbea92b2a]
24
+ - Updated dependencies [abf3421]
25
+ - Updated dependencies [543be9558e]
26
+ - Updated dependencies [14b712d]
27
+ - @modern-js/utils@2.0.0-beta.1
28
+
3
29
  ## 2.0.0-beta.0
4
30
 
5
31
  ### Major Changes
@@ -1,9 +1,6 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
4
  import path from 'path';
8
5
  import { logger, PLUGIN_SCHEMAS } from '@modern-js/utils';
9
6
  import { generatePath } from 'react-router-dom';
@@ -21,7 +18,6 @@ export default (() => ({
21
18
  validateSchema() {
22
19
  return PLUGIN_SCHEMAS['@modern-js/plugin-ssg'];
23
20
  },
24
-
25
21
  modifyFileSystemRoutes({
26
22
  entrypoint,
27
23
  routes
@@ -36,7 +32,6 @@ export default (() => ({
36
32
  routes
37
33
  };
38
34
  },
39
-
40
35
  async afterBuild() {
41
36
  const resolvedConfig = api.useResolvedConfigContext();
42
37
  const appContext = api.useAppContext();
@@ -52,30 +47,28 @@ export default (() => ({
52
47
  ssg,
53
48
  path: outputPath
54
49
  } = output;
55
- const ssgOptions = Array.isArray(ssg) ? ssg.pop() : ssg; // no ssg configuration, skip ssg render.
56
-
50
+ const ssgOptions = Array.isArray(ssg) ? ssg.pop() : ssg;
51
+ // no ssg configuration, skip ssg render.
57
52
  if (!ssgOptions) {
58
53
  return;
59
54
  }
60
-
61
55
  const buildDir = path.join(appDirectory, outputPath);
62
- const routes = readJSONSpec(buildDir); // filter all routes not web
56
+ const routes = readJSONSpec(buildDir);
63
57
 
58
+ // filter all routes not web
64
59
  const pageRoutes = routes.filter(route => !route.isApi);
65
- const apiRoutes = routes.filter(route => route.isApi); // if no web page route, skip ssg render
60
+ const apiRoutes = routes.filter(route => route.isApi);
66
61
 
62
+ // if no web page route, skip ssg render
67
63
  if (pageRoutes.length === 0) {
68
64
  return;
69
65
  }
70
-
71
66
  const intermediateOptions = standardOptions(ssgOptions, entrypoints, pageRoutes, server);
72
-
73
67
  if (!intermediateOptions) {
74
68
  return;
75
69
  }
76
-
77
- const ssgRoutes = []; // each route will try to match the configuration
78
-
70
+ const ssgRoutes = [];
71
+ // each route will try to match the configuration
79
72
  pageRoutes.forEach(pageRoute => {
80
73
  const {
81
74
  entryName,
@@ -83,14 +76,13 @@ export default (() => ({
83
76
  } = pageRoute;
84
77
  const agreedRoutes = agreedRouteMap[entryName];
85
78
  let entryOptions = intermediateOptions[entryName] || intermediateOptions[pageRoute.urlPath];
86
-
87
79
  if (!agreedRoutes) {
88
80
  // default behavior for non-agreed route
89
81
  if (!entryOptions) {
90
82
  return;
91
- } // only add entry route if entryOptions is true
92
-
83
+ }
93
84
 
85
+ // only add entry route if entryOptions is true
94
86
  if (entryOptions === true) {
95
87
  ssgRoutes.push(_objectSpread(_objectSpread({}, pageRoute), {}, {
96
88
  output: entryPath
@@ -112,7 +104,6 @@ export default (() => ({
112
104
  if (!entryOptions) {
113
105
  return;
114
106
  }
115
-
116
107
  if (entryOptions === true) {
117
108
  entryOptions = {
118
109
  preventDefault: [],
@@ -120,13 +111,12 @@ export default (() => ({
120
111
  headers: {}
121
112
  };
122
113
  }
123
-
124
114
  const {
125
115
  preventDefault = [],
126
116
  routes: userRoutes = [],
127
117
  headers
128
- } = entryOptions; // if the user sets the routes, then only add them
129
-
118
+ } = entryOptions;
119
+ // if the user sets the routes, then only add them
130
120
  if (userRoutes.length > 0) {
131
121
  userRoutes.forEach(route => {
132
122
  if (typeof route === 'string') {
@@ -151,36 +141,34 @@ export default (() => ({
151
141
  }
152
142
  }
153
143
  });
154
-
155
144
  if (ssgRoutes.length === 0) {
156
145
  return;
157
- } // currently SSG and SSR cannot be turned on at the same time、same route
158
-
146
+ }
159
147
 
148
+ // currently SSG and SSR cannot be turned on at the same time、same route
160
149
  ssgRoutes.forEach(ssgRoute => {
161
150
  if (ssgRoute.isSSR) {
162
151
  const isOriginRoute = pageRoutes.some(pageRoute => pageRoute.urlPath === ssgRoute.urlPath && pageRoute.entryName === ssgRoute.entryName);
163
-
164
152
  if (isOriginRoute) {
165
153
  throw new Error(`ssg can not using with ssr,url - ${ssgRoute.urlPath}, entry - ${ssgRoute.entryName} `);
166
154
  }
167
-
168
155
  logger.warn(`new ssg route ${ssgRoute.urlPath} is using ssr now,maybe from parent route ${ssgRoute.entryName},close ssr`);
169
156
  }
170
-
171
157
  ssgRoute.isSSR = false;
172
158
  ssgRoute.output = formatOutput(ssgRoute.output);
173
159
  });
174
- const htmlAry = await createServer(api, ssgRoutes, pageRoutes, apiRoutes, resolvedConfig, appDirectory); // write to dist file
160
+ const htmlAry = await createServer(api, ssgRoutes, pageRoutes, apiRoutes, resolvedConfig, appDirectory);
175
161
 
176
- writeHtmlFile(htmlAry, ssgRoutes, buildDir); // format route info, side effect
162
+ // write to dist file
163
+ writeHtmlFile(htmlAry, ssgRoutes, buildDir);
177
164
 
178
- replaceRoute(ssgRoutes, pageRoutes); // write routes to spec file
165
+ // format route info, side effect
166
+ replaceRoute(ssgRoutes, pageRoutes);
179
167
 
168
+ // write routes to spec file
180
169
  writeJSONSpec(buildDir, pageRoutes.concat(apiRoutes));
181
170
  logger.info('ssg Compiled successfully');
182
171
  }
183
-
184
172
  };
185
173
  }
186
174
  }));
@@ -1,9 +1,6 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
4
  import path from 'path';
8
5
  import normalize from 'normalize-path';
9
6
  export function makeRender(ssgRoutes, render, port) {
@@ -20,7 +17,6 @@ export function makeRoute(baseRoute, route, headers = {}) {
20
17
  urlPath,
21
18
  entryPath
22
19
  } = baseRoute;
23
-
24
20
  if (typeof route === 'string') {
25
21
  return _objectSpread(_objectSpread({}, baseRoute), {}, {
26
22
  urlPath: normalize(`${urlPath}${route}`) || '/',
@@ -4,11 +4,9 @@ export function writeHtmlFile(htmlAry, ssgRoutes, baseDir) {
4
4
  htmlAry.forEach((html, index) => {
5
5
  const ssgRoute = ssgRoutes[index];
6
6
  const filepath = path.join(baseDir, ssgRoute.output);
7
-
8
7
  if (!fs.existsSync(path.dirname(filepath))) {
9
8
  fs.ensureDirSync(path.dirname(filepath));
10
9
  }
11
-
12
10
  fs.writeFileSync(filepath, html);
13
11
  });
14
12
  }
@@ -1,25 +1,17 @@
1
1
  const _excluded = ["output", "headers"];
2
-
3
2
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
4
-
5
3
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
6
-
7
4
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8
-
9
5
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
10
-
11
6
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
12
-
13
7
  import normalize from 'normalize-path';
14
8
  export function exist(route, pageRoutes) {
15
9
  return pageRoutes.slice().findIndex(pageRoute => {
16
10
  const urlEqual = normalize(pageRoute.urlPath) === normalize(route.urlPath);
17
11
  const entryEqual = pageRoute.entryName === route.entryName;
18
-
19
12
  if (urlEqual && entryEqual) {
20
13
  return true;
21
14
  }
22
-
23
15
  return false;
24
16
  });
25
17
  }
@@ -27,20 +19,19 @@ export function replaceRoute(ssgRoutes, pageRoutes) {
27
19
  // remove redundant fields and replace rendered entryPath
28
20
  const cleanSsgRoutes = ssgRoutes.map(ssgRoute => {
29
21
  const {
30
- output,
31
- headers
32
- } = ssgRoute,
33
- cleanSsgRoute = _objectWithoutProperties(ssgRoute, _excluded);
34
-
22
+ output,
23
+ headers
24
+ } = ssgRoute,
25
+ cleanSsgRoute = _objectWithoutProperties(ssgRoute, _excluded);
35
26
  return Object.assign(cleanSsgRoute, output ? {
36
27
  entryPath: output
37
28
  } : {});
38
- }); // all routes that need to be added and replaced
29
+ });
39
30
 
31
+ // all routes that need to be added and replaced
40
32
  const freshRoutes = [];
41
33
  cleanSsgRoutes.forEach(ssgRoute => {
42
34
  const index = exist(ssgRoute, pageRoutes);
43
-
44
35
  if (index < 0) {
45
36
  // new route
46
37
  freshRoutes.push(_objectSpread({}, ssgRoute));
@@ -1,9 +1,6 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
4
  import path from 'path';
8
5
  import { ROUTE_SPEC_FILE, fs, isSingleEntry, SERVER_BUNDLE_DIRECTORY } from '@modern-js/utils';
9
6
  export function formatOutput(filename) {
@@ -12,23 +9,18 @@ export function formatOutput(filename) {
12
9
  }
13
10
  export function formatPath(str) {
14
11
  let addr = str;
15
-
16
12
  if (!addr || typeof addr !== 'string') {
17
13
  return addr;
18
14
  }
19
-
20
15
  if (addr.startsWith('.')) {
21
16
  addr = addr.slice(1);
22
17
  }
23
-
24
18
  if (!addr.startsWith('/')) {
25
19
  addr = `/${addr}`;
26
20
  }
27
-
28
21
  if (addr.endsWith('/') && addr !== '/') {
29
22
  addr = addr.slice(0, addr.length - 1);
30
23
  }
31
-
32
24
  return addr;
33
25
  }
34
26
  export function isDynamicUrl(url) {
@@ -36,51 +28,44 @@ export function isDynamicUrl(url) {
36
28
  }
37
29
  export function getUrlPrefix(route, baseUrl) {
38
30
  let base = '';
39
-
40
31
  if (Array.isArray(baseUrl)) {
41
32
  const filters = baseUrl.filter(url => route.urlPath.includes(url));
42
-
43
33
  if (filters.length > 1) {
44
- const matched = filters.sort((a, b) => a.length - b.length)[0]; // this should never happened
34
+ const matched = filters.sort((a, b) => a.length - b.length)[0];
45
35
 
36
+ // this should never happened
46
37
  if (!matched) {
47
38
  throw new Error('');
48
39
  }
49
-
50
40
  base = matched;
51
41
  }
52
42
  } else {
53
43
  base = baseUrl;
54
44
  }
55
-
56
45
  base = base === '/' ? '' : base;
57
46
  const entryName = route.entryName === 'main' ? '' : route.entryName;
58
47
  const prefix = `${base}/${entryName}`;
59
48
  return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
60
- } // if no output, return default path for aggred-route(relative),
61
- // or throw error for control-route
49
+ }
62
50
 
51
+ // if no output, return default path for aggred-route(relative),
52
+ // or throw error for control-route
63
53
  export function getOutput(route, base, agreed) {
64
54
  const {
65
55
  output
66
56
  } = route;
67
-
68
57
  if (output) {
69
58
  return output;
70
59
  }
71
-
72
60
  if (agreed) {
73
61
  const urlWithoutBase = route.urlPath.replace(base, '');
74
62
  return urlWithoutBase.startsWith('/') ? urlWithoutBase.slice(1) : urlWithoutBase;
75
63
  }
76
-
77
64
  throw new Error(`routing must provide output when calling createPage(), check ${route.urlPath}`);
78
65
  }
79
66
  export const readJSONSpec = dir => {
80
67
  const routeJSONPath = path.join(dir, ROUTE_SPEC_FILE);
81
-
82
68
  const routeJSON = require(routeJSONPath);
83
-
84
69
  const {
85
70
  routes
86
71
  } = routeJSON;
@@ -99,7 +84,6 @@ export const standardOptions = (ssgOptions, entrypoints, routes, server) => {
99
84
  if (ssgOptions === false) {
100
85
  return false;
101
86
  }
102
-
103
87
  if (ssgOptions === true) {
104
88
  return entrypoints.reduce((opt, entry) => {
105
89
  opt[entry.entryName] = ssgOptions;
@@ -107,7 +91,6 @@ export const standardOptions = (ssgOptions, entrypoints, routes, server) => {
107
91
  }, {});
108
92
  } else if (typeof ssgOptions === 'object') {
109
93
  const isSingle = isSingleEntry(entrypoints);
110
-
111
94
  if (isSingle && typeof ssgOptions.main === 'undefined') {
112
95
  return {
113
96
  main: ssgOptions
@@ -117,12 +100,11 @@ export const standardOptions = (ssgOptions, entrypoints, routes, server) => {
117
100
  }
118
101
  } else if (typeof ssgOptions === 'function') {
119
102
  const intermediateOptions = {};
120
-
121
103
  for (const entrypoint of entrypoints) {
122
104
  const {
123
105
  entryName
124
- } = entrypoint; // TODO: may be async function
125
-
106
+ } = entrypoint;
107
+ // TODO: may be async function
126
108
  if (Array.isArray(server === null || server === void 0 ? void 0 : server.baseUrl)) {
127
109
  for (const url of server.baseUrl) {
128
110
  const matchUrl = entryName === 'main' ? url : `${url}/${entryName}`;
@@ -137,33 +119,30 @@ export const standardOptions = (ssgOptions, entrypoints, routes, server) => {
137
119
  });
138
120
  }
139
121
  }
140
-
141
122
  return intermediateOptions;
142
123
  }
143
-
144
124
  return false;
145
125
  };
146
126
  export const openRouteSSR = (routes, entries = []) => routes.map(ssgRoute => _objectSpread(_objectSpread({}, ssgRoute), {}, {
147
127
  isSSR: entries.includes(ssgRoute.entryName),
148
128
  bundle: `${SERVER_BUNDLE_DIRECTORY}/${ssgRoute.entryName}.js`
149
- })); // TODO: 过滤带有 server loader 的路由
129
+ }));
150
130
 
131
+ // TODO: 过滤带有 server loader 的路由
151
132
  export const flattenRoutes = routes => {
152
133
  const parents = [];
153
134
  const newRoutes = [];
154
-
155
135
  const traverseRoute = route => {
156
136
  const parent = parents[parents.length - 1];
157
137
  let path = parent ? `${parent.path}/${route.path || ''}`.replace(/\/+/g, '/') : route.path || ''; // If the route is an index route, the route has no path property
138
+ path = path.replace(/\/$/, '');
158
139
 
159
- path = path.replace(/\/$/, ''); // If the route path is / and is not the root route, it should not be used as an ssg route
160
-
140
+ // If the route path is / and is not the root route, it should not be used as an ssg route
161
141
  if (route._component && (path !== '/' || path === '/' && !parent)) {
162
142
  newRoutes.push(_objectSpread(_objectSpread({}, route), {}, {
163
143
  path
164
144
  }));
165
145
  }
166
-
167
146
  if (route.children) {
168
147
  parents.push(_objectSpread(_objectSpread({}, route), {}, {
169
148
  path
@@ -172,7 +151,6 @@ export const flattenRoutes = routes => {
172
151
  parents.pop();
173
152
  }
174
153
  };
175
-
176
154
  routes.forEach(traverseRoute);
177
155
  return newRoutes;
178
156
  };
@@ -32,7 +32,6 @@ export const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, app
32
32
  htmlAry.push(html);
33
33
  htmlChunks.length = 0;
34
34
  }
35
-
36
35
  if (htmlAry.length === ssgRoutes.length) {
37
36
  cp.send(CLOSE_SIGN);
38
37
  resolve(htmlAry);
@@ -40,7 +39,6 @@ export const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, app
40
39
  });
41
40
  cp.stderr.on('data', chunk => {
42
41
  const str = chunk.toString();
43
-
44
42
  if (str.includes('Error')) {
45
43
  logger.error(str);
46
44
  reject(new Error('ssg render failed'));
@@ -51,7 +49,6 @@ export const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, app
51
49
  });
52
50
  cp.stdout.on('data', chunk => {
53
51
  const str = chunk.toString();
54
-
55
52
  if (str.includes('Error')) {
56
53
  logger.error(str);
57
54
  reject(new Error('ssg render failed'));
@@ -1,9 +1,6 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
4
  import EventEmitter from 'events';
8
5
  import { Readable } from 'stream';
9
6
  import httpMocks from 'node-mocks-http';
@@ -20,10 +17,8 @@ export const compile = requestHandler => (options, extend = {}) => new Promise((
20
17
  if (typeof prop === 'symbol' && !obj[prop]) {
21
18
  return null;
22
19
  }
23
-
24
20
  return obj[prop];
25
21
  }
26
-
27
22
  });
28
23
  res.on('finish', () => {
29
24
  if (res.statusCode !== 200) {
@@ -33,7 +28,6 @@ export const compile = requestHandler => (options, extend = {}) => new Promise((
33
28
  }
34
29
  });
35
30
  res.on('error', e => reject(e));
36
-
37
31
  try {
38
32
  requestHandler(req, proxyRes);
39
33
  } catch (e) {
@@ -8,7 +8,6 @@ process.on('message', async chunk => {
8
8
  // eslint-disable-next-line no-process-exit
9
9
  process.exit();
10
10
  }
11
-
12
11
  const context = JSON.parse(chunk);
13
12
  const {
14
13
  routes,
@@ -18,12 +17,12 @@ process.on('message', async chunk => {
18
17
  plugins
19
18
  } = context;
20
19
  let modernServer = null;
21
-
22
20
  try {
23
21
  const {
24
22
  server: serverOptions
25
- } = options; // start server in default port
23
+ } = options;
26
24
 
25
+ // start server in default port
27
26
  const defaultPort = Number(process.env.PORT) || serverOptions.port;
28
27
  portfinder.basePort = defaultPort;
29
28
  const port = await portfinder.getPortPromise();
@@ -33,21 +32,22 @@ process.on('message', async chunk => {
33
32
  routes,
34
33
  staticGenerate: true,
35
34
  internalPlugins: plugins
36
- }); // listen just for bff request in ssr page
35
+ });
37
36
 
37
+ // listen just for bff request in ssr page
38
38
  modernServer.listen(port, async err => {
39
39
  if (err) {
40
40
  throw err;
41
41
  }
42
-
43
42
  if (!modernServer) {
44
43
  return;
45
- } // get server handler, render to ssr
46
-
44
+ }
47
45
 
46
+ // get server handler, render to ssr
48
47
  const render = createRender(modernServer.getRequestHandler());
49
- const renderPromiseAry = makeRender(renderRoutes, render, port); // eslint-disable-next-line promise/no-promise-in-callback
48
+ const renderPromiseAry = makeRender(renderRoutes, render, port);
50
49
 
50
+ // eslint-disable-next-line promise/no-promise-in-callback
51
51
  const htmlAry = await Promise.all(renderPromiseAry);
52
52
  htmlAry.forEach(html => {
53
53
  process.send(html);
@@ -57,7 +57,6 @@ process.on('message', async chunk => {
57
57
  });
58
58
  } catch (e) {
59
59
  var _modernServer;
60
-
61
60
  (_modernServer = modernServer) === null || _modernServer === void 0 ? void 0 : _modernServer.close();
62
61
  throw e;
63
62
  }
@@ -4,31 +4,18 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
-
8
7
  var _path = _interopRequireDefault(require("path"));
9
-
10
8
  var _utils = require("@modern-js/utils");
11
-
12
9
  var _reactRouterDom = require("react-router-dom");
13
-
14
10
  var _util = require("./libs/util");
15
-
16
11
  var _server = require("./server");
17
-
18
12
  var _output = require("./libs/output");
19
-
20
13
  var _replace = require("./libs/replace");
21
-
22
14
  var _make = require("./libs/make");
23
-
24
15
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25
-
26
16
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
27
-
28
17
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
29
-
30
18
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
31
-
32
19
  var _default = () => ({
33
20
  name: '@modern-js/plugin-ssg',
34
21
  pre: ['@modern-js/plugin-server', '@modern-js/plugin-bff'],
@@ -38,7 +25,6 @@ var _default = () => ({
38
25
  validateSchema() {
39
26
  return _utils.PLUGIN_SCHEMAS['@modern-js/plugin-ssg'];
40
27
  },
41
-
42
28
  modifyFileSystemRoutes({
43
29
  entrypoint,
44
30
  routes
@@ -53,7 +39,6 @@ var _default = () => ({
53
39
  routes
54
40
  };
55
41
  },
56
-
57
42
  async afterBuild() {
58
43
  const resolvedConfig = api.useResolvedConfigContext();
59
44
  const appContext = api.useAppContext();
@@ -69,31 +54,28 @@ var _default = () => ({
69
54
  ssg,
70
55
  path: outputPath
71
56
  } = output;
72
- const ssgOptions = Array.isArray(ssg) ? ssg.pop() : ssg; // no ssg configuration, skip ssg render.
73
-
57
+ const ssgOptions = Array.isArray(ssg) ? ssg.pop() : ssg;
58
+ // no ssg configuration, skip ssg render.
74
59
  if (!ssgOptions) {
75
60
  return;
76
61
  }
77
-
78
62
  const buildDir = _path.default.join(appDirectory, outputPath);
63
+ const routes = (0, _util.readJSONSpec)(buildDir);
79
64
 
80
- const routes = (0, _util.readJSONSpec)(buildDir); // filter all routes not web
81
-
65
+ // filter all routes not web
82
66
  const pageRoutes = routes.filter(route => !route.isApi);
83
- const apiRoutes = routes.filter(route => route.isApi); // if no web page route, skip ssg render
67
+ const apiRoutes = routes.filter(route => route.isApi);
84
68
 
69
+ // if no web page route, skip ssg render
85
70
  if (pageRoutes.length === 0) {
86
71
  return;
87
72
  }
88
-
89
73
  const intermediateOptions = (0, _util.standardOptions)(ssgOptions, entrypoints, pageRoutes, server);
90
-
91
74
  if (!intermediateOptions) {
92
75
  return;
93
76
  }
94
-
95
- const ssgRoutes = []; // each route will try to match the configuration
96
-
77
+ const ssgRoutes = [];
78
+ // each route will try to match the configuration
97
79
  pageRoutes.forEach(pageRoute => {
98
80
  const {
99
81
  entryName,
@@ -101,14 +83,13 @@ var _default = () => ({
101
83
  } = pageRoute;
102
84
  const agreedRoutes = agreedRouteMap[entryName];
103
85
  let entryOptions = intermediateOptions[entryName] || intermediateOptions[pageRoute.urlPath];
104
-
105
86
  if (!agreedRoutes) {
106
87
  // default behavior for non-agreed route
107
88
  if (!entryOptions) {
108
89
  return;
109
- } // only add entry route if entryOptions is true
110
-
90
+ }
111
91
 
92
+ // only add entry route if entryOptions is true
112
93
  if (entryOptions === true) {
113
94
  ssgRoutes.push(_objectSpread(_objectSpread({}, pageRoute), {}, {
114
95
  output: entryPath
@@ -130,7 +111,6 @@ var _default = () => ({
130
111
  if (!entryOptions) {
131
112
  return;
132
113
  }
133
-
134
114
  if (entryOptions === true) {
135
115
  entryOptions = {
136
116
  preventDefault: [],
@@ -138,13 +118,12 @@ var _default = () => ({
138
118
  headers: {}
139
119
  };
140
120
  }
141
-
142
121
  const {
143
122
  preventDefault = [],
144
123
  routes: userRoutes = [],
145
124
  headers
146
- } = entryOptions; // if the user sets the routes, then only add them
147
-
125
+ } = entryOptions;
126
+ // if the user sets the routes, then only add them
148
127
  if (userRoutes.length > 0) {
149
128
  userRoutes.forEach(route => {
150
129
  if (typeof route === 'string') {
@@ -169,39 +148,35 @@ var _default = () => ({
169
148
  }
170
149
  }
171
150
  });
172
-
173
151
  if (ssgRoutes.length === 0) {
174
152
  return;
175
- } // currently SSG and SSR cannot be turned on at the same time、same route
176
-
153
+ }
177
154
 
155
+ // currently SSG and SSR cannot be turned on at the same time、same route
178
156
  ssgRoutes.forEach(ssgRoute => {
179
157
  if (ssgRoute.isSSR) {
180
158
  const isOriginRoute = pageRoutes.some(pageRoute => pageRoute.urlPath === ssgRoute.urlPath && pageRoute.entryName === ssgRoute.entryName);
181
-
182
159
  if (isOriginRoute) {
183
160
  throw new Error(`ssg can not using with ssr,url - ${ssgRoute.urlPath}, entry - ${ssgRoute.entryName} `);
184
161
  }
185
-
186
162
  _utils.logger.warn(`new ssg route ${ssgRoute.urlPath} is using ssr now,maybe from parent route ${ssgRoute.entryName},close ssr`);
187
163
  }
188
-
189
164
  ssgRoute.isSSR = false;
190
165
  ssgRoute.output = (0, _util.formatOutput)(ssgRoute.output);
191
166
  });
192
- const htmlAry = await (0, _server.createServer)(api, ssgRoutes, pageRoutes, apiRoutes, resolvedConfig, appDirectory); // write to dist file
167
+ const htmlAry = await (0, _server.createServer)(api, ssgRoutes, pageRoutes, apiRoutes, resolvedConfig, appDirectory);
193
168
 
194
- (0, _output.writeHtmlFile)(htmlAry, ssgRoutes, buildDir); // format route info, side effect
169
+ // write to dist file
170
+ (0, _output.writeHtmlFile)(htmlAry, ssgRoutes, buildDir);
195
171
 
196
- (0, _replace.replaceRoute)(ssgRoutes, pageRoutes); // write routes to spec file
172
+ // format route info, side effect
173
+ (0, _replace.replaceRoute)(ssgRoutes, pageRoutes);
197
174
 
175
+ // write routes to spec file
198
176
  (0, _util.writeJSONSpec)(buildDir, pageRoutes.concat(apiRoutes));
199
-
200
177
  _utils.logger.info('ssg Compiled successfully');
201
178
  }
202
-
203
179
  };
204
180
  }
205
181
  });
206
-
207
182
  exports.default = _default;
@@ -5,19 +5,12 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.makeRender = makeRender;
7
7
  exports.makeRoute = makeRoute;
8
-
9
8
  var _path = _interopRequireDefault(require("path"));
10
-
11
9
  var _normalizePath = _interopRequireDefault(require("normalize-path"));
12
-
13
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
-
15
11
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
16
-
17
12
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
18
-
19
13
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
20
-
21
14
  function makeRender(ssgRoutes, render, port) {
22
15
  return ssgRoutes.map(ssgRoute => render({
23
16
  url: ssgRoute.urlPath,
@@ -27,13 +20,11 @@ function makeRender(ssgRoutes, render, port) {
27
20
  connection: {}
28
21
  }));
29
22
  }
30
-
31
23
  function makeRoute(baseRoute, route, headers = {}) {
32
24
  const {
33
25
  urlPath,
34
26
  entryPath
35
27
  } = baseRoute;
36
-
37
28
  if (typeof route === 'string') {
38
29
  return _objectSpread(_objectSpread({}, baseRoute), {}, {
39
30
  urlPath: (0, _normalizePath.default)(`${urlPath}${route}`) || '/',
@@ -4,23 +4,16 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.writeHtmlFile = writeHtmlFile;
7
-
8
7
  var _path = _interopRequireDefault(require("path"));
9
-
10
8
  var _utils = require("@modern-js/utils");
11
-
12
9
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
-
14
10
  function writeHtmlFile(htmlAry, ssgRoutes, baseDir) {
15
11
  htmlAry.forEach((html, index) => {
16
12
  const ssgRoute = ssgRoutes[index];
17
-
18
13
  const filepath = _path.default.join(baseDir, ssgRoute.output);
19
-
20
14
  if (!_utils.fs.existsSync(_path.default.dirname(filepath))) {
21
15
  _utils.fs.ensureDirSync(_path.default.dirname(filepath));
22
16
  }
23
-
24
17
  _utils.fs.writeFileSync(filepath, html);
25
18
  });
26
19
  }
@@ -5,54 +5,41 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.exist = exist;
7
7
  exports.replaceRoute = replaceRoute;
8
-
9
8
  var _normalizePath = _interopRequireDefault(require("normalize-path"));
10
-
11
9
  const _excluded = ["output", "headers"];
12
-
13
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
-
15
11
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
16
-
17
12
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
18
-
19
13
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
20
-
21
14
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
22
-
23
15
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
24
-
25
16
  function exist(route, pageRoutes) {
26
17
  return pageRoutes.slice().findIndex(pageRoute => {
27
18
  const urlEqual = (0, _normalizePath.default)(pageRoute.urlPath) === (0, _normalizePath.default)(route.urlPath);
28
19
  const entryEqual = pageRoute.entryName === route.entryName;
29
-
30
20
  if (urlEqual && entryEqual) {
31
21
  return true;
32
22
  }
33
-
34
23
  return false;
35
24
  });
36
25
  }
37
-
38
26
  function replaceRoute(ssgRoutes, pageRoutes) {
39
27
  // remove redundant fields and replace rendered entryPath
40
28
  const cleanSsgRoutes = ssgRoutes.map(ssgRoute => {
41
29
  const {
42
- output,
43
- headers
44
- } = ssgRoute,
45
- cleanSsgRoute = _objectWithoutProperties(ssgRoute, _excluded);
46
-
30
+ output,
31
+ headers
32
+ } = ssgRoute,
33
+ cleanSsgRoute = _objectWithoutProperties(ssgRoute, _excluded);
47
34
  return Object.assign(cleanSsgRoute, output ? {
48
35
  entryPath: output
49
36
  } : {});
50
- }); // all routes that need to be added and replaced
37
+ });
51
38
 
39
+ // all routes that need to be added and replaced
52
40
  const freshRoutes = [];
53
41
  cleanSsgRoutes.forEach(ssgRoute => {
54
42
  const index = exist(ssgRoute, pageRoutes);
55
-
56
43
  if (index < 0) {
57
44
  // new route
58
45
  freshRoutes.push(_objectSpread({}, ssgRoute));
@@ -10,128 +10,96 @@ exports.getOutput = getOutput;
10
10
  exports.getUrlPrefix = getUrlPrefix;
11
11
  exports.isDynamicUrl = isDynamicUrl;
12
12
  exports.writeJSONSpec = exports.standardOptions = exports.replaceWithAlias = exports.readJSONSpec = exports.openRouteSSR = void 0;
13
-
14
13
  var _path = _interopRequireDefault(require("path"));
15
-
16
14
  var _utils = require("@modern-js/utils");
17
-
18
15
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
-
20
16
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
21
-
22
17
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
23
-
24
18
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
25
-
26
19
  function formatOutput(filename) {
27
20
  const outputPath = _path.default.extname(filename) ? filename : `${filename}/index.html`;
28
21
  return outputPath;
29
22
  }
30
-
31
23
  function formatPath(str) {
32
24
  let addr = str;
33
-
34
25
  if (!addr || typeof addr !== 'string') {
35
26
  return addr;
36
27
  }
37
-
38
28
  if (addr.startsWith('.')) {
39
29
  addr = addr.slice(1);
40
30
  }
41
-
42
31
  if (!addr.startsWith('/')) {
43
32
  addr = `/${addr}`;
44
33
  }
45
-
46
34
  if (addr.endsWith('/') && addr !== '/') {
47
35
  addr = addr.slice(0, addr.length - 1);
48
36
  }
49
-
50
37
  return addr;
51
38
  }
52
-
53
39
  function isDynamicUrl(url) {
54
40
  return url.includes(':');
55
41
  }
56
-
57
42
  function getUrlPrefix(route, baseUrl) {
58
43
  let base = '';
59
-
60
44
  if (Array.isArray(baseUrl)) {
61
45
  const filters = baseUrl.filter(url => route.urlPath.includes(url));
62
-
63
46
  if (filters.length > 1) {
64
- const matched = filters.sort((a, b) => a.length - b.length)[0]; // this should never happened
47
+ const matched = filters.sort((a, b) => a.length - b.length)[0];
65
48
 
49
+ // this should never happened
66
50
  if (!matched) {
67
51
  throw new Error('');
68
52
  }
69
-
70
53
  base = matched;
71
54
  }
72
55
  } else {
73
56
  base = baseUrl;
74
57
  }
75
-
76
58
  base = base === '/' ? '' : base;
77
59
  const entryName = route.entryName === 'main' ? '' : route.entryName;
78
60
  const prefix = `${base}/${entryName}`;
79
61
  return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
80
- } // if no output, return default path for aggred-route(relative),
81
- // or throw error for control-route
82
-
62
+ }
83
63
 
64
+ // if no output, return default path for aggred-route(relative),
65
+ // or throw error for control-route
84
66
  function getOutput(route, base, agreed) {
85
67
  const {
86
68
  output
87
69
  } = route;
88
-
89
70
  if (output) {
90
71
  return output;
91
72
  }
92
-
93
73
  if (agreed) {
94
74
  const urlWithoutBase = route.urlPath.replace(base, '');
95
75
  return urlWithoutBase.startsWith('/') ? urlWithoutBase.slice(1) : urlWithoutBase;
96
76
  }
97
-
98
77
  throw new Error(`routing must provide output when calling createPage(), check ${route.urlPath}`);
99
78
  }
100
-
101
79
  const readJSONSpec = dir => {
102
80
  const routeJSONPath = _path.default.join(dir, _utils.ROUTE_SPEC_FILE);
103
-
104
81
  const routeJSON = require(routeJSONPath);
105
-
106
82
  const {
107
83
  routes
108
84
  } = routeJSON;
109
85
  return routes;
110
86
  };
111
-
112
87
  exports.readJSONSpec = readJSONSpec;
113
-
114
88
  const writeJSONSpec = (dir, routes) => {
115
89
  const routeJSONPath = _path.default.join(dir, _utils.ROUTE_SPEC_FILE);
116
-
117
90
  _utils.fs.writeJSONSync(routeJSONPath, {
118
91
  routes
119
92
  }, {
120
93
  spaces: 2
121
94
  });
122
95
  };
123
-
124
96
  exports.writeJSONSpec = writeJSONSpec;
125
-
126
97
  const replaceWithAlias = (base, filePath, alias) => _path.default.posix.join(alias, _path.default.posix.relative(base, filePath));
127
-
128
98
  exports.replaceWithAlias = replaceWithAlias;
129
-
130
99
  const standardOptions = (ssgOptions, entrypoints, routes, server) => {
131
100
  if (ssgOptions === false) {
132
101
  return false;
133
102
  }
134
-
135
103
  if (ssgOptions === true) {
136
104
  return entrypoints.reduce((opt, entry) => {
137
105
  opt[entry.entryName] = ssgOptions;
@@ -139,7 +107,6 @@ const standardOptions = (ssgOptions, entrypoints, routes, server) => {
139
107
  }, {});
140
108
  } else if (typeof ssgOptions === 'object') {
141
109
  const isSingle = (0, _utils.isSingleEntry)(entrypoints);
142
-
143
110
  if (isSingle && typeof ssgOptions.main === 'undefined') {
144
111
  return {
145
112
  main: ssgOptions
@@ -149,12 +116,11 @@ const standardOptions = (ssgOptions, entrypoints, routes, server) => {
149
116
  }
150
117
  } else if (typeof ssgOptions === 'function') {
151
118
  const intermediateOptions = {};
152
-
153
119
  for (const entrypoint of entrypoints) {
154
120
  const {
155
121
  entryName
156
- } = entrypoint; // TODO: may be async function
157
-
122
+ } = entrypoint;
123
+ // TODO: may be async function
158
124
  if (Array.isArray(server === null || server === void 0 ? void 0 : server.baseUrl)) {
159
125
  for (const url of server.baseUrl) {
160
126
  const matchUrl = entryName === 'main' ? url : `${url}/${entryName}`;
@@ -169,39 +135,32 @@ const standardOptions = (ssgOptions, entrypoints, routes, server) => {
169
135
  });
170
136
  }
171
137
  }
172
-
173
138
  return intermediateOptions;
174
139
  }
175
-
176
140
  return false;
177
141
  };
178
-
179
142
  exports.standardOptions = standardOptions;
180
-
181
143
  const openRouteSSR = (routes, entries = []) => routes.map(ssgRoute => _objectSpread(_objectSpread({}, ssgRoute), {}, {
182
144
  isSSR: entries.includes(ssgRoute.entryName),
183
145
  bundle: `${_utils.SERVER_BUNDLE_DIRECTORY}/${ssgRoute.entryName}.js`
184
- })); // TODO: 过滤带有 server loader 的路由
185
-
146
+ }));
186
147
 
148
+ // TODO: 过滤带有 server loader 的路由
187
149
  exports.openRouteSSR = openRouteSSR;
188
-
189
150
  const flattenRoutes = routes => {
190
151
  const parents = [];
191
152
  const newRoutes = [];
192
-
193
153
  const traverseRoute = route => {
194
154
  const parent = parents[parents.length - 1];
195
155
  let path = parent ? `${parent.path}/${route.path || ''}`.replace(/\/+/g, '/') : route.path || ''; // If the route is an index route, the route has no path property
156
+ path = path.replace(/\/$/, '');
196
157
 
197
- path = path.replace(/\/$/, ''); // If the route path is / and is not the root route, it should not be used as an ssg route
198
-
158
+ // If the route path is / and is not the root route, it should not be used as an ssg route
199
159
  if (route._component && (path !== '/' || path === '/' && !parent)) {
200
160
  newRoutes.push(_objectSpread(_objectSpread({}, route), {}, {
201
161
  path
202
162
  }));
203
163
  }
204
-
205
164
  if (route.children) {
206
165
  parents.push(_objectSpread(_objectSpread({}, route), {}, {
207
166
  path
@@ -210,9 +169,7 @@ const flattenRoutes = routes => {
210
169
  parents.pop();
211
170
  }
212
171
  };
213
-
214
172
  routes.forEach(traverseRoute);
215
173
  return newRoutes;
216
174
  };
217
-
218
175
  exports.flattenRoutes = flattenRoutes;
@@ -4,31 +4,22 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.createServer = void 0;
7
-
8
7
  var _child_process = _interopRequireDefault(require("child_process"));
9
-
10
8
  var _path = _interopRequireDefault(require("path"));
11
-
12
9
  var _utils = require("@modern-js/utils");
13
-
14
10
  var _util = require("../libs/util");
15
-
16
11
  var _consts = require("./consts");
17
-
18
12
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
-
20
13
  const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, appDirectory) => new Promise((resolve, reject) => {
21
14
  // this side of the shallow copy of a route for subsequent render processing, to prevent the modification of the current field
22
15
  // manually enable the server-side rendering configuration for all routes that require SSG
23
16
  const entries = ssgRoutes.map(route => route.entryName);
24
17
  const backup = (0, _util.openRouteSSR)(pageRoutes, entries);
25
18
  const total = backup.concat(apiRoutes);
26
-
27
19
  const cp = _child_process.default.fork(_path.default.join(__dirname, 'process'), {
28
20
  cwd: appDirectory,
29
21
  silent: true
30
22
  });
31
-
32
23
  const appContext = api.useAppContext();
33
24
  const plugins = appContext.serverInternalPlugins;
34
25
  cp.send(JSON.stringify({
@@ -48,7 +39,6 @@ const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, appDirecto
48
39
  htmlAry.push(html);
49
40
  htmlChunks.length = 0;
50
41
  }
51
-
52
42
  if (htmlAry.length === ssgRoutes.length) {
53
43
  cp.send(_consts.CLOSE_SIGN);
54
44
  resolve(htmlAry);
@@ -56,10 +46,8 @@ const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, appDirecto
56
46
  });
57
47
  cp.stderr.on('data', chunk => {
58
48
  const str = chunk.toString();
59
-
60
49
  if (str.includes('Error')) {
61
50
  _utils.logger.error(str);
62
-
63
51
  reject(new Error('ssg render failed'));
64
52
  cp.kill('SIGKILL');
65
53
  } else {
@@ -68,10 +56,8 @@ const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, appDirecto
68
56
  });
69
57
  cp.stdout.on('data', chunk => {
70
58
  const str = chunk.toString();
71
-
72
59
  if (str.includes('Error')) {
73
60
  _utils.logger.error(str);
74
-
75
61
  reject(new Error('ssg render failed'));
76
62
  cp.kill('SIGKILL');
77
63
  } else {
@@ -79,5 +65,4 @@ const createServer = (api, ssgRoutes, pageRoutes, apiRoutes, options, appDirecto
79
65
  }
80
66
  });
81
67
  });
82
-
83
68
  exports.createServer = createServer;
@@ -4,40 +4,28 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.compile = void 0;
7
-
8
7
  var _events = _interopRequireDefault(require("events"));
9
-
10
8
  var _stream = require("stream");
11
-
12
9
  var _nodeMocksHttp = _interopRequireDefault(require("node-mocks-http"));
13
-
14
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
-
16
11
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
17
-
18
12
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
19
-
20
13
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
21
-
22
14
  const compile = requestHandler => (options, extend = {}) => new Promise((resolve, reject) => {
23
15
  const req = _nodeMocksHttp.default.createRequest(_objectSpread(_objectSpread({}, options), {}, {
24
16
  eventEmitter: _stream.Readable
25
17
  }));
26
-
27
18
  const res = _nodeMocksHttp.default.createResponse({
28
19
  eventEmitter: _events.default
29
20
  });
30
-
31
21
  Object.assign(req, extend);
32
22
  const proxyRes = new Proxy(res, {
33
23
  get(obj, prop) {
34
24
  if (typeof prop === 'symbol' && !obj[prop]) {
35
25
  return null;
36
26
  }
37
-
38
27
  return obj[prop];
39
28
  }
40
-
41
29
  });
42
30
  res.on('finish', () => {
43
31
  if (res.statusCode !== 200) {
@@ -47,12 +35,10 @@ const compile = requestHandler => (options, extend = {}) => new Promise((resolve
47
35
  }
48
36
  });
49
37
  res.on('error', e => reject(e));
50
-
51
38
  try {
52
39
  requestHandler(req, proxyRes);
53
40
  } catch (e) {
54
41
  reject(e);
55
42
  }
56
43
  });
57
-
58
44
  exports.compile = compile;
@@ -1,23 +1,16 @@
1
1
  "use strict";
2
2
 
3
3
  var _prodServer = _interopRequireDefault(require("@modern-js/prod-server"));
4
-
5
4
  var _portfinder = _interopRequireDefault(require("portfinder"));
6
-
7
5
  var _make = require("../libs/make");
8
-
9
6
  var _prerender = require("./prerender");
10
-
11
7
  var _consts = require("./consts");
12
-
13
8
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
-
15
9
  process.on('message', async chunk => {
16
10
  if (chunk === _consts.CLOSE_SIGN) {
17
11
  // eslint-disable-next-line no-process-exit
18
12
  process.exit();
19
13
  }
20
-
21
14
  const context = JSON.parse(chunk);
22
15
  const {
23
16
  routes,
@@ -27,12 +20,12 @@ process.on('message', async chunk => {
27
20
  plugins
28
21
  } = context;
29
22
  let modernServer = null;
30
-
31
23
  try {
32
24
  const {
33
25
  server: serverOptions
34
- } = options; // start server in default port
26
+ } = options;
35
27
 
28
+ // start server in default port
36
29
  const defaultPort = Number(process.env.PORT) || serverOptions.port;
37
30
  _portfinder.default.basePort = defaultPort;
38
31
  const port = await _portfinder.default.getPortPromise();
@@ -42,21 +35,22 @@ process.on('message', async chunk => {
42
35
  routes,
43
36
  staticGenerate: true,
44
37
  internalPlugins: plugins
45
- }); // listen just for bff request in ssr page
38
+ });
46
39
 
40
+ // listen just for bff request in ssr page
47
41
  modernServer.listen(port, async err => {
48
42
  if (err) {
49
43
  throw err;
50
44
  }
51
-
52
45
  if (!modernServer) {
53
46
  return;
54
- } // get server handler, render to ssr
55
-
47
+ }
56
48
 
49
+ // get server handler, render to ssr
57
50
  const render = (0, _prerender.compile)(modernServer.getRequestHandler());
58
- const renderPromiseAry = (0, _make.makeRender)(renderRoutes, render, port); // eslint-disable-next-line promise/no-promise-in-callback
51
+ const renderPromiseAry = (0, _make.makeRender)(renderRoutes, render, port);
59
52
 
53
+ // eslint-disable-next-line promise/no-promise-in-callback
60
54
  const htmlAry = await Promise.all(renderPromiseAry);
61
55
  htmlAry.forEach(html => {
62
56
  process.send(html);
@@ -66,7 +60,6 @@ process.on('message', async chunk => {
66
60
  });
67
61
  } catch (e) {
68
62
  var _modernServer;
69
-
70
63
  (_modernServer = modernServer) === null || _modernServer === void 0 ? void 0 : _modernServer.close();
71
64
  throw e;
72
65
  }
@@ -1,5 +1,3 @@
1
1
  import type { CliPlugin } from '@modern-js/core';
2
-
3
2
  declare const _default: () => CliPlugin;
4
-
5
3
  export default _default;
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "2.0.0-beta.0",
14
+ "version": "2.0.0-beta.1",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -55,10 +55,10 @@
55
55
  },
56
56
  "dependencies": {
57
57
  "@babel/runtime": "^7.18.0",
58
- "@modern-js/utils": "2.0.0-beta.0",
59
58
  "node-mocks-http": "^1.10.1",
60
59
  "normalize-path": "^3.0.0",
61
- "portfinder": "^1.0.28"
60
+ "portfinder": "^1.0.28",
61
+ "@modern-js/utils": "2.0.0-beta.1"
62
62
  },
63
63
  "peerDependencies": {
64
64
  "react-router-dom": ">=5.1.2"
@@ -69,17 +69,17 @@
69
69
  }
70
70
  },
71
71
  "devDependencies": {
72
- "@modern-js/types": "2.0.0-beta.0",
73
- "@modern-js/prod-server": "2.0.0-beta.0",
74
72
  "@types/jest": "^27",
75
73
  "@types/node": "^14",
76
- "@modern-js/core": "2.0.0-beta.0",
77
- "@scripts/build": "2.0.0-beta.0",
78
- "@scripts/jest-config": "2.0.0-beta.0",
79
74
  "react-router-dom": "^6.4.2",
80
75
  "react": "^18",
81
76
  "typescript": "^4",
82
- "jest": "^27"
77
+ "jest": "^27",
78
+ "@modern-js/types": "2.0.0-beta.1",
79
+ "@modern-js/prod-server": "2.0.0-beta.1",
80
+ "@modern-js/core": "2.0.0-beta.1",
81
+ "@scripts/build": "2.0.0-beta.1",
82
+ "@scripts/jest-config": "2.0.0-beta.1"
83
83
  },
84
84
  "sideEffects": false,
85
85
  "modernConfig": {