@shuvi/platform-web 1.0.0-rc.2 → 1.0.0-rc.5

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 (87) hide show
  1. package/esm/shared/appTypes.d.ts +2 -2
  2. package/esm/shared/renderTypes.d.ts +2 -2
  3. package/esm/shuvi-app/app/client.d.ts +2 -0
  4. package/esm/shuvi-app/app/client.js +12 -11
  5. package/esm/shuvi-app/app/server.js +4 -5
  6. package/esm/shuvi-app/dev/eventsource.d.ts +1 -0
  7. package/esm/shuvi-app/dev/eventsource.js +60 -0
  8. package/esm/shuvi-app/dev/hotDevClient.d.ts +33 -0
  9. package/esm/shuvi-app/dev/hotDevClient.js +348 -0
  10. package/esm/shuvi-app/dev/index.d.ts +3 -0
  11. package/esm/shuvi-app/dev/index.js +27 -0
  12. package/esm/shuvi-app/dev/websocket.d.ts +17 -0
  13. package/esm/shuvi-app/dev/websocket.js +61 -0
  14. package/esm/shuvi-app/entry/client/app.d.ts +2 -1
  15. package/esm/shuvi-app/entry/client/app.js +2 -2
  16. package/esm/shuvi-app/entry/client/run.dev.js +4 -4
  17. package/esm/shuvi-app/entry/server/index.d.ts +5 -4
  18. package/esm/shuvi-app/entry/server/index.js +5 -4
  19. package/esm/shuvi-app/react/AppContainer.d.ts +2 -3
  20. package/esm/shuvi-app/react/AppContainer.jsx +3 -4
  21. package/esm/shuvi-app/react/getRoutes.d.ts +2 -2
  22. package/esm/shuvi-app/react/getRoutes.js +6 -7
  23. package/esm/shuvi-app/react/redox-react/RedoxWrapper.d.ts +2 -2
  24. package/esm/shuvi-app/react/redox-react/RedoxWrapper.jsx +3 -3
  25. package/esm/shuvi-app/react/redox-react/runtime.d.ts +7 -1
  26. package/esm/shuvi-app/react/redox-react/runtime.js +3 -1
  27. package/esm/shuvi-app/react/store.d.ts +5 -0
  28. package/esm/shuvi-app/react/store.js +3 -0
  29. package/esm/shuvi-app/react/types.d.ts +0 -7
  30. package/esm/shuvi-app/react/useLoaderData.js +11 -20
  31. package/esm/shuvi-app/react/view/ReactView.client.jsx +4 -4
  32. package/esm/shuvi-app/react/view/ReactView.server.jsx +4 -10
  33. package/esm/shuvi-app/shuvi-runtime-index.js +1 -1
  34. package/lib/node/features/filesystem-routes/index.d.ts +1 -1
  35. package/lib/node/features/filesystem-routes/index.js +17 -7
  36. package/lib/node/features/filesystem-routes/page/routes.d.ts +2 -2
  37. package/lib/node/features/filesystem-routes/page/routes.js +29 -11
  38. package/lib/node/features/html-render/index.d.ts +3 -18
  39. package/lib/node/features/html-render/index.js +87 -16
  40. package/lib/node/features/{main → html-render/lib}/buildHtml.d.ts +0 -0
  41. package/lib/node/features/{main → html-render/lib}/buildHtml.js +0 -0
  42. package/lib/node/features/html-render/lib/generateFilesByRoutId.d.ts +2 -2
  43. package/lib/node/features/html-render/lib/generateFilesByRoutId.js +3 -3
  44. package/lib/node/features/{main → html-render/lib}/generateResource.d.ts +0 -0
  45. package/lib/node/features/{main → html-render/lib}/generateResource.js +0 -0
  46. package/lib/node/features/html-render/lib/index.d.ts +0 -1
  47. package/lib/node/features/html-render/lib/index.js +1 -3
  48. package/lib/node/features/html-render/lib/renderToHTML.js +4 -47
  49. package/lib/node/features/html-render/lib/renderer/base.d.ts +4 -4
  50. package/lib/node/features/html-render/lib/renderer/index.d.ts +5 -4
  51. package/lib/node/features/html-render/lib/renderer/index.js +69 -6
  52. package/lib/node/features/html-render/lib/renderer/spa.d.ts +2 -2
  53. package/lib/node/features/html-render/lib/renderer/spa.js +2 -4
  54. package/lib/node/features/html-render/lib/renderer/ssr.d.ts +2 -2
  55. package/lib/node/features/html-render/lib/renderer/ssr.js +2 -2
  56. package/lib/node/features/html-render/lib/renderer/types.d.ts +6 -4
  57. package/lib/node/features/index.d.ts +3 -31
  58. package/lib/node/features/index.js +6 -7
  59. package/lib/node/features/model/index.d.ts +1 -1
  60. package/lib/node/features/model/runtime.d.ts +0 -5
  61. package/lib/node/features/model/runtime.js +11 -17
  62. package/lib/node/features/model/server.js +2 -3
  63. package/lib/node/features/model/shuvi-app.d.ts +1 -1
  64. package/lib/node/features/on-demand-compile-page/index.d.ts +15 -13
  65. package/lib/node/features/on-demand-compile-page/index.js +4 -1
  66. package/lib/node/features/on-demand-compile-page/onDemandRouteManager.js +2 -4
  67. package/lib/node/index.js +1 -3
  68. package/lib/node/shuvi-runtime-server.d.ts +18 -0
  69. package/lib/node/shuvi-runtime-server.js +2 -0
  70. package/lib/node/shuvi-type-extensions-node.d.ts +2 -6
  71. package/lib/node/targets/react/bundler/index.d.ts +1 -1
  72. package/lib/node/targets/react/bundler/index.js +5 -0
  73. package/lib/node/targets/react/index.d.ts +2 -2
  74. package/lib/node/targets/react/redox-react/index.d.ts +1 -1
  75. package/lib/shared/appTypes.d.ts +2 -2
  76. package/lib/shared/renderTypes.d.ts +2 -2
  77. package/package.json +17 -12
  78. package/shuvi-env.d.ts +10 -0
  79. package/shuvi-image.d.ts +54 -0
  80. package/shuvi-type-extensions-node.js +1 -0
  81. package/shuvi-type-extensions-runtime.d.ts +2 -2
  82. package/esm/shuvi-app/dev/webpackHotDevClient.d.ts +0 -5
  83. package/esm/shuvi-app/dev/webpackHotDevClient.js +0 -34
  84. package/esm/shuvi-app/shuvi-runtime-server.d.ts +0 -6
  85. package/esm/shuvi-app/shuvi-runtime-server.js +0 -1
  86. package/lib/node/features/main/index.d.ts +0 -3
  87. package/lib/node/features/main/index.js +0 -82
@@ -1,4 +1,4 @@
1
- import { IRequest, IRawPageRouteRecord, IAppData, IAppState } from '@shuvi/platform-shared/shared';
1
+ import { IRequest, IPageRouteRecord, IAppData, IAppState } from '@shuvi/platform-shared/shared';
2
2
  import { Application } from '@shuvi/platform-shared/shuvi-app/application';
3
3
  export interface CreateAppServer {
4
4
  (options: {
@@ -8,7 +8,7 @@ export interface CreateAppServer {
8
8
  }
9
9
  export interface CreateAppClient {
10
10
  (options: {
11
- routes: IRawPageRouteRecord[];
11
+ routes: IPageRouteRecord[];
12
12
  appComponent: any;
13
13
  appData: IAppData<any, IAppState>;
14
14
  }): Application;
@@ -1,10 +1,10 @@
1
1
  import { IManifest } from '@shuvi/toolpack/lib/webpack/types';
2
2
  import { Response, IApplication, IRequest, IAppData } from '@shuvi/platform-shared/shared';
3
- export declare type IRenderDocumentOptions = {
3
+ export declare type IRenderViewOptions = {
4
4
  app: IApplication;
5
5
  req?: IRequest;
6
6
  };
7
- export interface IRenderOptions extends IRenderDocumentOptions {
7
+ export interface IRenderOptions extends IRenderViewOptions {
8
8
  }
9
9
  export interface IView<RenderOption extends IRenderOptions = any, RenderResult = void> {
10
10
  renderApp(options: RenderOption): RenderResult;
@@ -1,2 +1,4 @@
1
+ import { Application } from '@shuvi/platform-shared/shuvi-app/application';
1
2
  import { CreateAppClient } from '../../shared';
3
+ export { Application };
2
4
  export declare const createApp: CreateAppClient;
@@ -8,19 +8,20 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { getRoutes } from '@shuvi/app/core/platform';
11
- import { runPreload, runLoaders, getRouteMatchesWithInvalidLoader, getLoaderManager, isRedirect, isResponse } from '@shuvi/platform-shared/shared';
12
- import application from '@shuvi/platform-shared/shuvi-app/application';
11
+ import { runPreload, runLoaders, getRouteMatchesWithInvalidLoader, isRedirect, isResponse } from '@shuvi/platform-shared/shared';
12
+ import application, { Application } from '@shuvi/platform-shared/shuvi-app/application';
13
13
  import { createRouter, createBrowserHistory, createHashHistory } from '@shuvi/router';
14
14
  import pageLoaders from '@shuvi/app/files/page-loaders';
15
15
  import { historyMode } from '@shuvi/app/files/routerConfig';
16
16
  import { SHUVI_ERROR } from '@shuvi/shared/lib/constants';
17
17
  let app;
18
+ export { Application };
18
19
  export const createApp = ({ routes, appData, appComponent }) => {
19
20
  // app is a singleton in client side
20
21
  if (app) {
21
22
  return app;
22
23
  }
23
- const { loadersData = {}, appState, ssr } = appData;
24
+ const { appState, ssr } = appData;
24
25
  let history;
25
26
  if (historyMode === 'hash') {
26
27
  history = createHashHistory();
@@ -37,14 +38,14 @@ export const createApp = ({ routes, appData, appComponent }) => {
37
38
  AppComponent: appComponent,
38
39
  router
39
40
  });
41
+ const loadersData = app.getLoadersData();
40
42
  const hasHydrateData = Object.keys(loadersData).length > 0;
41
- const loaderManager = getLoaderManager();
42
43
  let shouldHydrate = ssr && hasHydrateData;
43
- let hasServerError = app.error.hasError;
44
+ let hasServerError = !!app.error;
44
45
  router.beforeResolve((to, from, next) => __awaiter(void 0, void 0, void 0, function* () {
45
46
  if (shouldHydrate) {
46
47
  shouldHydrate = false;
47
- loaderManager.setDatas(loadersData);
48
+ app.setLoadersData(loadersData);
48
49
  return next();
49
50
  }
50
51
  if (hasServerError) {
@@ -52,7 +53,7 @@ export const createApp = ({ routes, appData, appComponent }) => {
52
53
  return next();
53
54
  }
54
55
  if (!to.matches.length) {
55
- app.error.error(SHUVI_ERROR.PAGE_NOT_FOUND);
56
+ app.setError(SHUVI_ERROR.PAGE_NOT_FOUND);
56
57
  next();
57
58
  return;
58
59
  }
@@ -95,7 +96,7 @@ export const createApp = ({ routes, appData, appComponent }) => {
95
96
  tryResolve();
96
97
  });
97
98
  });
98
- loaderManager.setDatas(loaderDatas);
99
+ app.setLoadersData(loaderDatas);
99
100
  }
100
101
  catch (error) {
101
102
  if (isRedirect(error)) {
@@ -103,14 +104,14 @@ export const createApp = ({ routes, appData, appComponent }) => {
103
104
  return;
104
105
  }
105
106
  if (isResponse(error) && error.status >= 400 && error.status < 600) {
106
- app.error.error({
107
+ app.setError({
107
108
  code: error.status,
108
109
  message: error.data
109
110
  });
110
111
  next();
111
112
  return;
112
113
  }
113
- app.error.error({
114
+ app.setError({
114
115
  code: SHUVI_ERROR.APP_ERROR.code,
115
116
  message: error.message || isPreloadError ? 'Preload Error' : 'Loader Error'
116
117
  });
@@ -118,7 +119,7 @@ export const createApp = ({ routes, appData, appComponent }) => {
118
119
  return;
119
120
  }
120
121
  next(() => {
121
- app.error.clear();
122
+ app.clearError();
122
123
  });
123
124
  }));
124
125
  return app;
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import routes from '@shuvi/app/files/routes';
11
11
  import { getRoutes, app as AppComponent } from '@shuvi/app/core/platform';
12
- import { runLoaders, getRouteMatchesWithInvalidLoader, isResponse, isRedirect, getLoaderManager } from '@shuvi/platform-shared/shared';
12
+ import { runLoaders, getRouteMatchesWithInvalidLoader, isResponse, isRedirect } from '@shuvi/platform-shared/shared';
13
13
  import pageLoaders from '@shuvi/app/files/page-loaders';
14
14
  import application from '@shuvi/platform-shared/shuvi-app/application';
15
15
  import { createRouter, createMemoryHistory } from '@shuvi/router';
@@ -24,7 +24,6 @@ export const createApp = options => {
24
24
  routes: getRoutes(routes)
25
25
  });
26
26
  let app;
27
- const loaderManager = getLoaderManager();
28
27
  if (ssr) {
29
28
  router.beforeResolve((to, from, next) => __awaiter(void 0, void 0, void 0, function* () {
30
29
  const matches = getRouteMatchesWithInvalidLoader(to, from, pageLoaders);
@@ -35,7 +34,7 @@ export const createApp = options => {
35
34
  query: to.query,
36
35
  getAppContext: () => app.context
37
36
  });
38
- loaderManager.setDatas(loaderResult);
37
+ app.setLoadersData(loaderResult);
39
38
  }
40
39
  catch (error) {
41
40
  if (isRedirect(error)) {
@@ -43,14 +42,14 @@ export const createApp = options => {
43
42
  return;
44
43
  }
45
44
  if (isResponse(error) && error.status >= 400 && error.status < 600) {
46
- app.error.error({
45
+ app.setError({
47
46
  code: error.status,
48
47
  message: error.data
49
48
  });
50
49
  next();
51
50
  return;
52
51
  }
53
- app.error.error({
52
+ app.setError({
54
53
  message: error.message || 'Loader Error'
55
54
  });
56
55
  next();
@@ -0,0 +1 @@
1
+ export function getEventSourceWrapper(options: any): any;
@@ -0,0 +1,60 @@
1
+ const eventCallbacks = [];
2
+ function EventSourceWrapper(options) {
3
+ var source;
4
+ var lastActivity = new Date();
5
+ var listeners = [];
6
+ if (!options.timeout) {
7
+ options.timeout = 20 * 1000;
8
+ }
9
+ init();
10
+ var timer = setInterval(function () {
11
+ if (new Date() - lastActivity > options.timeout) {
12
+ handleDisconnect();
13
+ }
14
+ }, options.timeout / 2);
15
+ function init() {
16
+ source = new window.EventSource(options.path);
17
+ source.onopen = handleOnline;
18
+ source.onerror = handleDisconnect;
19
+ source.onmessage = handleMessage;
20
+ }
21
+ function handleOnline() {
22
+ if (options.log)
23
+ console.log('[HMR] connected');
24
+ lastActivity = new Date();
25
+ }
26
+ function handleMessage(event) {
27
+ lastActivity = new Date();
28
+ for (var i = 0; i < listeners.length; i++) {
29
+ listeners[i](event);
30
+ }
31
+ if (event.data.indexOf('action') !== -1) {
32
+ eventCallbacks.forEach(cb => cb(event));
33
+ }
34
+ }
35
+ function handleDisconnect() {
36
+ clearInterval(timer);
37
+ source.close();
38
+ setTimeout(init, options.timeout);
39
+ }
40
+ return {
41
+ onclose: () => {
42
+ clearTimeout(timer);
43
+ source.close();
44
+ },
45
+ addMessageListener: function (fn) {
46
+ listeners.push(fn);
47
+ }
48
+ };
49
+ }
50
+ export function getEventSourceWrapper(options) {
51
+ if (!window.__whmEventSourceWrapper) {
52
+ window.__whmEventSourceWrapper = {};
53
+ }
54
+ if (!window.__whmEventSourceWrapper[options.path]) {
55
+ // cache the wrapper for other entries loaded on
56
+ // the same page with the same options.path
57
+ window.__whmEventSourceWrapper[options.path] = EventSourceWrapper(options);
58
+ }
59
+ return window.__whmEventSourceWrapper[options.path];
60
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ MIT License
3
+
4
+ Copyright (c) 2013-present, Facebook, Inc.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ */
24
+ export declare type HotDevClient = {
25
+ sendMessage: (data: any) => void;
26
+ subscribeToHmrEvent: (handler: any) => void;
27
+ reportRuntimeError: (err: any) => void;
28
+ };
29
+ export default function connect(options: {
30
+ launchEditorEndpoint: string;
31
+ path: string;
32
+ location: Location;
33
+ }): HotDevClient;
@@ -0,0 +1,348 @@
1
+ /* eslint-disable camelcase */
2
+ /**
3
+ MIT License
4
+
5
+ Copyright (c) 2013-present, Facebook, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+ */
25
+ // This file is based on https://github.com/facebook/create-react-app/blob/v1.1.4/packages/react-dev-utils/webpackHotDevClient.js
26
+ // It's been edited to rely on webpack-hot-middleware.
27
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
28
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
29
+ return new (P || (P = Promise))(function (resolve, reject) {
30
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
31
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
32
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
33
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
34
+ });
35
+ };
36
+ // @ts-nocheck
37
+ import * as ErrorOverlay from 'react-error-overlay';
38
+ import stripAnsi from 'strip-ansi';
39
+ import formatWebpackMessages from '@shuvi/toolpack/lib/utils/formatWebpackMessages';
40
+ import { DEV_SOCKET_TIMEOUT_MS } from '@shuvi/shared/esm/constants';
41
+ import { connectHMR, addMessageListener, sendMessage } from './websocket';
42
+ // This alternative WebpackDevServer combines the functionality of:
43
+ // https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
44
+ // https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
45
+ // It only supports their simplest configuration (hot updates on same server).
46
+ // It makes some opinionated choices on top, like adding a syntax error overlay
47
+ // that looks similar to our console output. The error overlay is inspired by:
48
+ // https://github.com/glenjamin/webpack-hot-middleware
49
+ // This is a modified version of create-react-app's webpackHotDevClient.js
50
+ // It implements webpack-hot-middleware's EventSource events instead of webpack-dev-server's websocket.
51
+ // https://github.com/facebook/create-react-app/blob/25184c4e91ebabd16fe1cde3d8630830e4a36a01/packages/react-dev-utils/webpackHotDevClient.js
52
+ let hadRuntimeError = false;
53
+ let customHmrEventHandler;
54
+ export default function connect(options) {
55
+ // Open stack traces in an editor.
56
+ ErrorOverlay.setEditorHandler(function editorHandler({ fileName, lineNumber, colNumber }) {
57
+ // Resolve invalid paths coming from react-error-overlay
58
+ const resolvedFilename = fileName.replace(/^webpack:\/\/[^/]+/ /* webpack://namaspcae/resourcepath */, '');
59
+ fetch(options.launchEditorEndpoint +
60
+ '?fileName=' +
61
+ window.encodeURIComponent(resolvedFilename) +
62
+ '&lineNumber=' +
63
+ window.encodeURIComponent(lineNumber || 1) +
64
+ '&colNumber=' +
65
+ window.encodeURIComponent(colNumber || 1));
66
+ });
67
+ // We need to keep track of if there has been a runtime error.
68
+ // Essentially, we cannot guarantee application state was not corrupted by the
69
+ // runtime error. To prevent confusing behavior, we forcibly reload the entire
70
+ // application. This is handled below when we are notified of a compile (code
71
+ // change).
72
+ // See https://github.com/facebook/create-react-app/issues/3096
73
+ ErrorOverlay.startReportingRuntimeErrors({
74
+ onError: function () {
75
+ hadRuntimeError = true;
76
+ }
77
+ });
78
+ if (module.hot && typeof module.hot.dispose === 'function') {
79
+ module.hot.dispose(function () {
80
+ // TODO: why do we need this?
81
+ ErrorOverlay.stopReportingRuntimeErrors();
82
+ });
83
+ }
84
+ connectHMR(Object.assign(Object.assign({}, options), { log: true }));
85
+ addMessageListener(event => {
86
+ // This is the heartbeat event
87
+ const obj = JSON.parse(event.data);
88
+ if (obj.action === 'pong') {
89
+ return;
90
+ }
91
+ try {
92
+ processMessage(event);
93
+ }
94
+ catch (ex) {
95
+ console.warn('Invalid HMR message: ' + event.data + '\n' + ex);
96
+ }
97
+ });
98
+ setInterval(() => {
99
+ sendMessage(JSON.stringify({ event: 'ping' }));
100
+ }, DEV_SOCKET_TIMEOUT_MS / 2);
101
+ return {
102
+ sendMessage(data) {
103
+ sendMessage(data);
104
+ },
105
+ subscribeToHmrEvent(handler) {
106
+ customHmrEventHandler = handler;
107
+ },
108
+ reportRuntimeError(err) {
109
+ ErrorOverlay.reportRuntimeError(err);
110
+ }
111
+ };
112
+ }
113
+ // Remember some state related to hot module replacement.
114
+ var isFirstCompilation = true;
115
+ var mostRecentCompilationHash = null;
116
+ var hasCompileErrors = false;
117
+ function clearOutdatedErrors() {
118
+ // Clean up outdated compile errors, if any.
119
+ if (typeof console !== 'undefined' && typeof console.clear === 'function') {
120
+ if (hasCompileErrors) {
121
+ console.clear();
122
+ }
123
+ }
124
+ }
125
+ let startLatency = undefined;
126
+ function onFastRefresh() {
127
+ tryDismissErrorOverlay();
128
+ if (startLatency) {
129
+ const endLatency = Date.now();
130
+ const latency = endLatency - startLatency;
131
+ console.log(`[Fast Refresh] done in ${latency}ms`);
132
+ }
133
+ }
134
+ // Successful compilation.
135
+ function handleSuccess() {
136
+ clearOutdatedErrors();
137
+ const isHotUpdate = !isFirstCompilation;
138
+ isFirstCompilation = false;
139
+ hasCompileErrors = false;
140
+ // Attempt to apply hot updates or reload.
141
+ if (isHotUpdate) {
142
+ tryApplyUpdates(function onHotUpdateSuccess() {
143
+ // Only dismiss it when we're sure it's a hot update.
144
+ // Otherwise it would flicker right before the reload.
145
+ onFastRefresh();
146
+ });
147
+ }
148
+ }
149
+ // Compilation with warnings (e.g. ESLint).
150
+ function handleWarnings(warnings) {
151
+ clearOutdatedErrors();
152
+ var isHotUpdate = !isFirstCompilation;
153
+ isFirstCompilation = false;
154
+ hasCompileErrors = false;
155
+ // Print warnings to the console.
156
+ const formatted = formatWebpackMessages({
157
+ warnings: warnings,
158
+ errors: []
159
+ });
160
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
161
+ for (let i = 0; i < formatted.warnings.length; i++) {
162
+ if (i === 5) {
163
+ console.warn('There were more warnings in other files.\n' +
164
+ 'You can find a complete log in the terminal.');
165
+ break;
166
+ }
167
+ console.warn(stripAnsi(formatted.warnings[i]));
168
+ }
169
+ }
170
+ // Attempt to apply hot updates or reload.
171
+ if (isHotUpdate) {
172
+ tryApplyUpdates(function onSuccessfulHotUpdate() {
173
+ // Only dismiss it when we're sure it's a hot update.
174
+ // Otherwise it would flicker right before the reload.
175
+ tryDismissErrorOverlay();
176
+ onFastRefresh();
177
+ });
178
+ }
179
+ }
180
+ // Compilation with errors (e.g. syntax error or missing modules).
181
+ function handleErrors(errors) {
182
+ clearOutdatedErrors();
183
+ isFirstCompilation = false;
184
+ hasCompileErrors = true;
185
+ // "Massage" webpack messages.
186
+ var formatted = formatWebpackMessages({
187
+ errors: errors,
188
+ warnings: []
189
+ });
190
+ // Only show the first error.
191
+ ErrorOverlay.reportBuildError(formatted.errors[0]);
192
+ // Also log them to the console.
193
+ if (typeof console !== 'undefined' && typeof console.error === 'function') {
194
+ for (var i = 0; i < formatted.errors.length; i++) {
195
+ console.error(stripAnsi(formatted.errors[i]));
196
+ }
197
+ }
198
+ }
199
+ function tryDismissErrorOverlay() {
200
+ if (!hasCompileErrors) {
201
+ ErrorOverlay.dismissBuildError();
202
+ }
203
+ }
204
+ // There is a newer version of the code available.
205
+ function handleAvailableHash(hash) {
206
+ // Update last known compilation hash.
207
+ mostRecentCompilationHash = hash;
208
+ }
209
+ // Handle messages from the server.
210
+ function processMessage(e) {
211
+ const obj = JSON.parse(e.data);
212
+ switch (obj.action) {
213
+ case 'building': {
214
+ startLatency = Date.now();
215
+ console.log('[Fast Refresh] bundle ' +
216
+ (obj.name ? "'" + obj.name + "' " : '') +
217
+ 'rebuilding');
218
+ break;
219
+ }
220
+ case 'built':
221
+ case 'sync': {
222
+ if (obj.hash) {
223
+ handleAvailableHash(obj.hash);
224
+ }
225
+ const { errors, warnings } = obj;
226
+ const hasErrors = Boolean(errors && errors.length);
227
+ if (hasErrors) {
228
+ return handleErrors(errors);
229
+ }
230
+ const hasWarnings = Boolean(warnings && warnings.length);
231
+ if (hasWarnings) {
232
+ return handleWarnings(warnings);
233
+ }
234
+ return handleSuccess();
235
+ }
236
+ case 'warnings':
237
+ handleWarnings(obj.data);
238
+ break;
239
+ case 'errors':
240
+ handleErrors(obj.data);
241
+ break;
242
+ default: {
243
+ if (customHmrEventHandler) {
244
+ customHmrEventHandler(obj);
245
+ break;
246
+ }
247
+ break;
248
+ }
249
+ }
250
+ }
251
+ // Is there a newer version of this code available?
252
+ function isUpdateAvailable() {
253
+ /* globals __webpack_hash__ */
254
+ // __webpack_hash__ is the hash of the current compilation.
255
+ // It's a global variable injected by Webpack.
256
+ return mostRecentCompilationHash !== __webpack_hash__;
257
+ }
258
+ // Webpack disallows updates in other states.
259
+ function canApplyUpdates() {
260
+ return module.hot.status() === 'idle';
261
+ }
262
+ function waitForReady() {
263
+ return new Promise((resolve, reject) => {
264
+ if (module.hot.status() !== 'prepare') {
265
+ reject();
266
+ }
267
+ const handler = status => {
268
+ module.hot.removeStatusHandler(handler);
269
+ if (status === 'ready') {
270
+ resolve();
271
+ }
272
+ if (status === 'abort' || status === 'fail') {
273
+ reject();
274
+ }
275
+ };
276
+ module.hot.addStatusHandler(handler);
277
+ });
278
+ }
279
+ // Attempt to update code on the fly, fall back to a hard reload.
280
+ function tryApplyUpdates(onHotUpdateSuccess) {
281
+ return __awaiter(this, void 0, void 0, function* () {
282
+ if (!module.hot) {
283
+ // HotModuleReplacementPlugin is not in Webpack configuration.
284
+ console.error('HotModuleReplacementPlugin is not in Webpack configuration.');
285
+ window.location.reload();
286
+ return;
287
+ }
288
+ if (!isUpdateAvailable() || !canApplyUpdates()) {
289
+ ErrorOverlay.dismissBuildError();
290
+ // HMR failed, need to refresh
291
+ const hmrStatus = module.hot.status();
292
+ if (hmrStatus === 'abort' || hmrStatus === 'fail') {
293
+ window.location.reload();
294
+ }
295
+ return;
296
+ }
297
+ function handleApplyUpdates(err, updatedModules) {
298
+ const needForcedReload = err || hadRuntimeError;
299
+ if (needForcedReload) {
300
+ if (hadRuntimeError) {
301
+ hadRuntimeError = false;
302
+ window.location.reload();
303
+ }
304
+ else {
305
+ ErrorOverlay.reportRuntimeError(err);
306
+ hadRuntimeError = true;
307
+ }
308
+ }
309
+ if (typeof onHotUpdateSuccess === 'function') {
310
+ // Maybe we want to do something.
311
+ onHotUpdateSuccess();
312
+ }
313
+ if (isUpdateAvailable()) {
314
+ // While we were updating, there was a new update! Do it again.
315
+ tryApplyUpdates(onHotUpdateSuccess);
316
+ }
317
+ }
318
+ try {
319
+ // https://webpack.js.org/api/hot-module-replacement/#check
320
+ let updatedModules = yield module.hot.check(/* autoApply */ false);
321
+ if (!updatedModules) {
322
+ return;
323
+ }
324
+ // if there is another updating, delay the update
325
+ // multiple hotupdate occurs during import() will cause hmr error
326
+ // so we delay the adjacent hotupdates
327
+ // import() == loade module script ----> require(module)
328
+ // |
329
+ // |
330
+ // if applyUpdate happens here, require will cause a error
331
+ if (isUpdateAvailable()) {
332
+ yield new Promise(resolve => {
333
+ setTimeout(resolve, 50);
334
+ });
335
+ }
336
+ if (updatedModules) {
337
+ if (module.hot.status() !== 'ready') {
338
+ yield waitForReady();
339
+ }
340
+ updatedModules = yield module.hot.apply();
341
+ }
342
+ handleApplyUpdates(null, updatedModules);
343
+ }
344
+ catch (err) {
345
+ handleApplyUpdates(err, null);
346
+ }
347
+ });
348
+ }
@@ -0,0 +1,3 @@
1
+ import { Application } from '@shuvi/platform-shared/shuvi-app/application';
2
+ import { HotDevClient } from './hotDevClient';
3
+ export declare const initHMRAndDevClient: (app: Application) => HotDevClient;
@@ -0,0 +1,27 @@
1
+ import { DEV_SOCKET_TIMEOUT_MS, DEV_HOT_MIDDLEWARE_PATH, DEV_HOT_LAUNCH_EDITOR_ENDPOINT } from '@shuvi/shared/esm/constants';
2
+ import connect from './hotDevClient';
3
+ let devClient;
4
+ export const initHMRAndDevClient = (app) => {
5
+ if (devClient) {
6
+ return devClient;
7
+ }
8
+ devClient = connect({
9
+ launchEditorEndpoint: DEV_HOT_LAUNCH_EDITOR_ENDPOINT,
10
+ path: DEV_HOT_MIDDLEWARE_PATH,
11
+ location
12
+ });
13
+ setInterval(() => {
14
+ devClient.sendMessage(JSON.stringify({
15
+ event: 'updatePageStatus',
16
+ currentRoutes: app.router.current.matches.map(({ route: { __componentRawRequest__ } }) => __componentRawRequest__),
17
+ page: location.pathname
18
+ }));
19
+ }, DEV_SOCKET_TIMEOUT_MS / 2);
20
+ devClient.subscribeToHmrEvent((event) => {
21
+ // if (obj.action === "reloadPage") {
22
+ // return window.location.reload();
23
+ // }
24
+ // throw new Error("Unexpected action " + obj.action);
25
+ });
26
+ return devClient;
27
+ };
@@ -0,0 +1,17 @@
1
+ export declare function addMessageListener(cb: (event: any) => void): void;
2
+ export declare function sendMessage(data: any): any;
3
+ export declare type HotDevClient = {
4
+ sendMessage: (data: any) => void;
5
+ subscribeToHmrEvent?: (handler: any) => void;
6
+ reportRuntimeError?: (err: any) => void;
7
+ };
8
+ export declare function connectHMR(options: {
9
+ path: string;
10
+ timeout: number;
11
+ log?: boolean;
12
+ location: {
13
+ protocol: string;
14
+ hostname: string;
15
+ port?: string;
16
+ };
17
+ }): void;