@shuvi/platform-web 1.0.0-rc.3 → 1.0.0-rc.4

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 (63) hide show
  1. package/esm/shared/appTypes.d.ts +2 -2
  2. package/esm/shuvi-app/app/client.d.ts +2 -0
  3. package/esm/shuvi-app/app/client.js +2 -1
  4. package/esm/shuvi-app/dev/eventsource.d.ts +1 -0
  5. package/esm/shuvi-app/dev/eventsource.js +60 -0
  6. package/esm/shuvi-app/dev/hotDevClient.d.ts +33 -0
  7. package/esm/shuvi-app/dev/hotDevClient.js +348 -0
  8. package/esm/shuvi-app/dev/index.d.ts +3 -0
  9. package/esm/shuvi-app/dev/index.js +27 -0
  10. package/esm/shuvi-app/dev/websocket.d.ts +17 -0
  11. package/esm/shuvi-app/dev/websocket.js +61 -0
  12. package/esm/shuvi-app/entry/client/app.d.ts +2 -1
  13. package/esm/shuvi-app/entry/client/app.js +2 -2
  14. package/esm/shuvi-app/entry/client/run.dev.js +4 -4
  15. package/esm/shuvi-app/entry/server/index.d.ts +5 -4
  16. package/esm/shuvi-app/entry/server/index.js +5 -4
  17. package/esm/shuvi-app/react/getRoutes.d.ts +2 -2
  18. package/esm/shuvi-app/react/getRoutes.js +6 -7
  19. package/esm/shuvi-app/react/redox-react/runtime.d.ts +7 -1
  20. package/esm/shuvi-app/react/redox-react/runtime.js +3 -1
  21. package/esm/shuvi-app/shuvi-runtime-index.js +1 -1
  22. package/lib/node/features/filesystem-routes/index.d.ts +1 -1
  23. package/lib/node/features/filesystem-routes/index.js +17 -7
  24. package/lib/node/features/filesystem-routes/page/routes.d.ts +2 -2
  25. package/lib/node/features/filesystem-routes/page/routes.js +29 -11
  26. package/lib/node/features/html-render/index.d.ts +3 -18
  27. package/lib/node/features/html-render/index.js +87 -16
  28. package/lib/node/features/{main → html-render/lib}/buildHtml.d.ts +0 -0
  29. package/lib/node/features/{main → html-render/lib}/buildHtml.js +0 -0
  30. package/lib/node/features/html-render/lib/generateFilesByRoutId.d.ts +2 -2
  31. package/lib/node/features/html-render/lib/generateFilesByRoutId.js +3 -3
  32. package/lib/node/features/{main → html-render/lib}/generateResource.d.ts +0 -0
  33. package/lib/node/features/{main → html-render/lib}/generateResource.js +0 -0
  34. package/lib/node/features/index.d.ts +3 -31
  35. package/lib/node/features/index.js +9 -8
  36. package/lib/node/features/model/index.d.ts +1 -1
  37. package/lib/node/features/model/runtime.d.ts +0 -5
  38. package/lib/node/features/model/runtime.js +11 -17
  39. package/lib/node/features/model/server.js +2 -3
  40. package/lib/node/features/model/shuvi-app.d.ts +1 -1
  41. package/lib/node/features/on-demand-compile-page/index.d.ts +15 -13
  42. package/lib/node/features/on-demand-compile-page/index.js +4 -1
  43. package/lib/node/features/on-demand-compile-page/onDemandRouteManager.js +2 -4
  44. package/lib/node/features/webpack-watch-wait-for-file-builder/index.d.ts +16 -0
  45. package/lib/node/features/webpack-watch-wait-for-file-builder/index.js +25 -0
  46. package/lib/node/features/webpack-watch-wait-for-file-builder/webpack-watch-wait-for-file-builder-plugin.d.ts +12 -0
  47. package/lib/node/features/webpack-watch-wait-for-file-builder/webpack-watch-wait-for-file-builder-plugin.js +32 -0
  48. package/lib/node/index.js +1 -3
  49. package/lib/node/shuvi-type-extensions-node.d.ts +2 -0
  50. package/lib/node/targets/react/bundler/index.d.ts +1 -1
  51. package/lib/node/targets/react/bundler/index.js +5 -0
  52. package/lib/node/targets/react/index.d.ts +2 -2
  53. package/lib/node/targets/react/redox-react/index.d.ts +1 -1
  54. package/lib/shared/appTypes.d.ts +2 -2
  55. package/package.json +17 -12
  56. package/shuvi-env.d.ts +10 -0
  57. package/shuvi-image.d.ts +54 -0
  58. package/shuvi-type-extensions-node.js +1 -0
  59. package/shuvi-type-extensions-runtime.d.ts +2 -2
  60. package/esm/shuvi-app/dev/webpackHotDevClient.d.ts +0 -5
  61. package/esm/shuvi-app/dev/webpackHotDevClient.js +0 -34
  62. package/lib/node/features/main/index.d.ts +0 -3
  63. 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,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;
@@ -9,12 +9,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { getRoutes } from '@shuvi/app/core/platform';
11
11
  import { runPreload, runLoaders, getRouteMatchesWithInvalidLoader, getLoaderManager, isRedirect, isResponse } from '@shuvi/platform-shared/shared';
12
- import application from '@shuvi/platform-shared/shuvi-app/application';
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) {
@@ -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;
@@ -0,0 +1,61 @@
1
+ let source;
2
+ const eventCallbacks = [];
3
+ let lastActivity = Date.now();
4
+ let initDataBeforeWsOnline = [];
5
+ function getSocketProtocol(protocol) {
6
+ return protocol === 'http:' ? 'ws' : 'wss';
7
+ }
8
+ export function addMessageListener(cb) {
9
+ eventCallbacks.push(cb);
10
+ }
11
+ export function sendMessage(data) {
12
+ if (!source || source.readyState !== source.OPEN) {
13
+ initDataBeforeWsOnline.push(data);
14
+ return;
15
+ }
16
+ return source.send(data);
17
+ }
18
+ export function connectHMR(options) {
19
+ if (!options.timeout) {
20
+ options.timeout = 5000;
21
+ }
22
+ init();
23
+ let timer = setInterval(function () {
24
+ if (Date.now() - lastActivity > options.timeout) {
25
+ handleDisconnect();
26
+ }
27
+ }, options.timeout / 2);
28
+ function init() {
29
+ if (source)
30
+ source.close();
31
+ let { protocol, hostname, port } = options.location;
32
+ protocol = getSocketProtocol(protocol);
33
+ let url = `${protocol}://${hostname}:${port}`;
34
+ source = new WebSocket(`${url}${options.path}`);
35
+ source.onopen = handleOnline;
36
+ source.onerror = handleDisconnect;
37
+ source.onmessage = handleMessage;
38
+ }
39
+ function handleOnline() {
40
+ if (initDataBeforeWsOnline.length !== 0) {
41
+ initDataBeforeWsOnline.forEach(data => {
42
+ sendMessage(data);
43
+ });
44
+ initDataBeforeWsOnline = [];
45
+ }
46
+ if (options.log)
47
+ console.log('[HMR] connected');
48
+ lastActivity = Date.now();
49
+ }
50
+ function handleMessage(event) {
51
+ lastActivity = Date.now();
52
+ eventCallbacks.forEach(cb => {
53
+ cb(event);
54
+ });
55
+ }
56
+ function handleDisconnect() {
57
+ clearInterval(timer);
58
+ source.close();
59
+ setTimeout(init, options.timeout);
60
+ }
61
+ }
@@ -1,2 +1,3 @@
1
+ declare const app: import("../../app/client").Application;
1
2
  declare const run: () => Promise<void>;
2
- export { run };
3
+ export { run, app };
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { CLIENT_CONTAINER_ID } from '@shuvi/shared/lib/constants';
11
11
  // renderer must be imported before application
12
- // we need to init init renderer before import AppComponent
12
+ // we need to init renderer before import AppComponent
13
13
  import { view, getRoutes, app as PlatformAppComponent } from '@shuvi/app/core/platform';
14
14
  import routes from '@shuvi/app/files/routes';
15
15
  import { getAppData } from '@shuvi/platform-shared/shared/helper/getAppData';
@@ -32,7 +32,7 @@ const run = () => __awaiter(void 0, void 0, void 0, function* () {
32
32
  yield app.init();
33
33
  render();
34
34
  });
35
- export { run };
35
+ export { run, app };
36
36
  if (module.hot) {
37
37
  const handleHotUpdate = () => __awaiter(void 0, void 0, void 0, function* () {
38
38
  const rerender = () => __awaiter(void 0, void 0, void 0, function* () {
@@ -9,11 +9,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  /// <reference lib="dom" />
11
11
  import { DEV_STYLE_HIDE_FOUC, DEV_STYLE_PREPARE } from '@shuvi/shared/lib/constants';
12
- import initWebpackHMR from '../../dev/webpackHotDevClient';
13
- import { run } from './app';
12
+ import { initHMRAndDevClient } from '../../dev';
13
+ import { run, app } from './app';
14
14
  function init() {
15
15
  return __awaiter(this, void 0, void 0, function* () {
16
- initWebpackHMR();
16
+ initHMRAndDevClient(app);
17
17
  // reduce FOUC caused by style-loader
18
18
  const styleReady = new Promise(resolve => {
19
19
  (window.requestAnimationFrame || setTimeout)(() => __awaiter(this, void 0, void 0, function* () {
@@ -27,4 +27,4 @@ function init() {
27
27
  yield styleReady;
28
28
  });
29
29
  }
30
- init().then(run);
30
+ init().then(() => run());
@@ -1,6 +1,7 @@
1
- import * as application from '../../app/server';
2
- import * as server from '@shuvi/app/user/server';
1
+ import { default as pageRoutes } from '@shuvi/app/files/routes';
3
2
  import { default as apiRoutes } from '@shuvi/app/files/apiRoutes';
4
3
  import { default as middlewareRoutes } from '@shuvi/app/files/middlewareRoutes';
5
- export { server, application, apiRoutes, middlewareRoutes };
6
- export { view } from '@shuvi/app/core/platform';
4
+ import { view } from '@shuvi/app/core/platform';
5
+ import * as server from '@shuvi/app/user/server';
6
+ import * as application from '../../app/server';
7
+ export { pageRoutes, apiRoutes, middlewareRoutes, server, view, application };
@@ -1,7 +1,8 @@
1
1
  // This is the shuvi server-side main module exports collection
2
- import * as application from '../../app/server';
3
- import * as server from '@shuvi/app/user/server';
2
+ import { default as pageRoutes } from '@shuvi/app/files/routes';
4
3
  import { default as apiRoutes } from '@shuvi/app/files/apiRoutes';
5
4
  import { default as middlewareRoutes } from '@shuvi/app/files/middlewareRoutes';
6
- export { server, application, apiRoutes, middlewareRoutes };
7
- export { view } from '@shuvi/app/core/platform';
5
+ import { view } from '@shuvi/app/core/platform';
6
+ import * as server from '@shuvi/app/user/server';
7
+ import * as application from '../../app/server';
8
+ export { pageRoutes, apiRoutes, middlewareRoutes, server, view, application };