@s-ui/bundler 8.0.0-beta.12 → 8.0.0-beta.16

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.
@@ -16,10 +16,9 @@ const installNeededDependencies = async () => {
16
16
  return getSpawnPromise('npm', [
17
17
  'install',
18
18
  '--no-save',
19
- '--no-optional',
20
19
  '--no-audit',
21
20
  '--no-fund',
22
- 'webpack-bundle-analyzer@4.3.0 duplicate-package-checker-webpack-plugin@3.0.0'
21
+ 'webpack-bundle-analyzer@4.5.0 duplicate-package-checker-webpack-plugin@3.0.0'
23
22
  ]).then(() => {
24
23
  logUpdate.done('Installed needed dependencies')
25
24
  getSpawnPromise('./node_modules/.bin/sui-bundler', ['analyzer']).then(
@@ -11,10 +11,7 @@ const WebpackDevServer = require('webpack-dev-server')
11
11
 
12
12
  const clearConsole = require('../utils/clearConsole')
13
13
  const checkRequiredFiles = require('../utils/checkRequiredFiles')
14
- const {
15
- choosePort,
16
- prepareUrls
17
- } = require('react-dev-utils/WebpackDevServerUtils')
14
+ const {choosePort, prepareUrls} = require('../utils/WebpackDevServerUtils.js')
18
15
 
19
16
  const webpackConfig = require('../webpack.config.dev')
20
17
 
@@ -83,7 +80,7 @@ const start = async ({
83
80
  }
84
81
 
85
82
  const protocol = HTTPS === 'true' ? 'https' : 'http'
86
- const port = await choosePort(HOST, DEFAULT_PORT)
83
+ const port = await choosePort(DEFAULT_PORT)
87
84
  const urls = prepareUrls(protocol, HOST, port)
88
85
  const nextConfig = linkLoaderConfigBuilder({
89
86
  config,
@@ -1,7 +1,7 @@
1
1
  // @ts-check
2
2
 
3
- const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware')
4
- const ignoredFiles = require('react-dev-utils/ignoredFiles')
3
+ const noopServiceWorkerMiddleware = require('../utils/noopServiceWorkerMiddleware.js')
4
+ const ignoredFiles = require('../utils/ignoredFiles.js')
5
5
 
6
6
  const {HOST, HTTPS} = process.env
7
7
  const protocol = HTTPS === 'true' ? 'https' : 'http'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@s-ui/bundler",
3
- "version": "8.0.0-beta.12",
3
+ "version": "8.0.0-beta.16",
4
4
  "description": "Config-free bundler for ES6 React apps.",
5
5
  "bin": {
6
6
  "sui-bundler": "./bin/sui-bundler.js"
@@ -24,25 +24,28 @@
24
24
  "@babel/core": "7.16.0",
25
25
  "@s-ui/helpers": "1",
26
26
  "@s-ui/sass-loader": "1",
27
+ "address": "1.1.2",
27
28
  "autoprefixer": "10.4.0",
28
29
  "babel-loader": "8.2.3",
29
30
  "babel-preset-sui": "3",
30
31
  "commander": "8.3.0",
31
32
  "css-loader": "6.5.1",
32
33
  "css-minimizer-webpack-plugin": "3.2.0",
33
- "esbuild-loader": "2.16.0",
34
+ "esbuild-loader": "2.17.0",
35
+ "escape-string-regexp": "5.0.0",
34
36
  "fast-glob": "3.2.7",
37
+ "find-free-ports": "3.0.0",
35
38
  "html-webpack-plugin": "5.5.0",
36
39
  "mini-css-extract-plugin": "2.4.5",
37
- "process": "0.11.10",
38
- "postcss": "8.4.3",
40
+ "postcss": "8.4.5",
39
41
  "postcss-loader": "6.2.1",
40
- "react-dev-utils": "11.0.4",
42
+ "process": "0.11.10",
41
43
  "rimraf": "3.0.2",
42
- "sass": "1.43.5",
44
+ "sass": "1.45.0",
43
45
  "speed-measure-webpack-plugin": "1.5.0",
46
+ "strip-ansi": "6.0.1",
44
47
  "style-loader": "3.3.1",
45
- "webpack": "5.64.4",
48
+ "webpack": "5.65.0",
46
49
  "webpack-dev-server": "4.6.0",
47
50
  "webpack-manifest-plugin": "4.0.2",
48
51
  "webpack-node-externals": "3.0.0"
@@ -0,0 +1,354 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * Copyright (c) 2015-present, Facebook, Inc.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ */
9
+ 'use strict'
10
+
11
+ const address = require('address')
12
+ const fs = require('fs')
13
+ const path = require('path')
14
+ const url = require('url')
15
+
16
+ const {findFreePorts, isFreePort} = require('find-free-ports')
17
+
18
+ const clearConsole = require('./clearConsole')
19
+ const formatWebpackMessages = require('./formatWebpackMessages')
20
+ const getProcessForPort = require('./getProcessForPort')
21
+
22
+ const {bold, cyan, green, yellow, red} = require('@s-ui/helpers/colors')
23
+
24
+ const isInteractive = process.stdout.isTTY
25
+
26
+ function prepareUrls(protocol, host, port, pathname = '/') {
27
+ const formatUrl = hostname =>
28
+ url.format({
29
+ protocol,
30
+ hostname,
31
+ port,
32
+ pathname
33
+ })
34
+
35
+ const prettyPrintUrl = hostname =>
36
+ url.format({
37
+ protocol,
38
+ hostname,
39
+ port: bold(port),
40
+ pathname
41
+ })
42
+
43
+ const isUnspecifiedHost = host === '0.0.0.0' || host === '::'
44
+ let prettyHost, lanUrlForConfig, lanUrlForTerminal
45
+
46
+ if (isUnspecifiedHost) {
47
+ prettyHost = 'localhost'
48
+ try {
49
+ // This can only return an IPv4 address
50
+ lanUrlForConfig = address.ip()
51
+ if (lanUrlForConfig) {
52
+ // Check if the address is a private ip
53
+ // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
54
+ if (
55
+ /^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(
56
+ lanUrlForConfig
57
+ )
58
+ ) {
59
+ // Address is private, format it for later use
60
+ lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig)
61
+ } else {
62
+ // Address is not private, so we will discard it
63
+ lanUrlForConfig = undefined
64
+ }
65
+ }
66
+ } catch (_e) {
67
+ // ignored
68
+ }
69
+ } else {
70
+ prettyHost = host
71
+ }
72
+
73
+ const localUrlForTerminal = prettyPrintUrl(prettyHost)
74
+ const localUrlForBrowser = formatUrl(prettyHost)
75
+ return {
76
+ lanUrlForConfig,
77
+ lanUrlForTerminal,
78
+ localUrlForTerminal,
79
+ localUrlForBrowser
80
+ }
81
+ }
82
+
83
+ function printInstructions(appName, urls, useYarn) {
84
+ console.log()
85
+ console.log(`You can now view ${bold(appName)} in the browser.`)
86
+ console.log()
87
+
88
+ if (urls.lanUrlForTerminal) {
89
+ console.log(` ${bold('Local:')} ${urls.localUrlForTerminal}`)
90
+ console.log(` ${bold('On Your Network:')} ${urls.lanUrlForTerminal}`)
91
+ } else {
92
+ console.log(` ${urls.localUrlForTerminal}`)
93
+ }
94
+
95
+ console.log()
96
+ console.log('Note that the development build is not optimized.')
97
+ console.log(
98
+ `To create a production build, use ` +
99
+ `${cyan(`${useYarn ? 'yarn' : 'npm run'} build`)}.`
100
+ )
101
+ console.log()
102
+ }
103
+
104
+ function createCompiler({
105
+ appName,
106
+ config,
107
+ urls,
108
+ useYarn,
109
+ useTypeScript,
110
+ webpack
111
+ }) {
112
+ // "Compiler" is a low-level interface to webpack.
113
+ // It lets us listen to some events and provide our own custom messages.
114
+ let compiler
115
+ try {
116
+ compiler = webpack(config)
117
+ } catch (err) {
118
+ console.log(red('Failed to compile.'))
119
+ console.log()
120
+ console.log(err.message || err)
121
+ console.log()
122
+ process.exit(1)
123
+ }
124
+
125
+ // "invalid" event fires when you have changed a file, and webpack is
126
+ // recompiling a bundle. WebpackDevServer takes care to pause serving the
127
+ // bundle, so if you refresh, it'll wait instead of serving the old one.
128
+ // "invalid" is short for "bundle invalidated", it doesn't imply any errors.
129
+ compiler.hooks.invalid.tap('invalid', () => {
130
+ if (isInteractive) {
131
+ clearConsole()
132
+ }
133
+ console.log('Compiling...')
134
+ })
135
+
136
+ let isFirstCompile = true
137
+
138
+ // "done" event fires when webpack has finished recompiling the bundle.
139
+ // Whether or not you have warnings or errors, you will get this event.
140
+ compiler.hooks.done.tap('done', async stats => {
141
+ if (isInteractive) clearConsole()
142
+
143
+ // We have switched off the default webpack output in WebpackDevServer
144
+ // options so we are going to "massage" the warnings and errors and present
145
+ // them in a readable focused way.
146
+ // We only construct the warnings and errors for speed:
147
+ // https://github.com/facebook/create-react-app/issues/4492#issuecomment-421959548
148
+ const statsData = stats.toJson({
149
+ all: false,
150
+ warnings: true,
151
+ errors: true
152
+ })
153
+
154
+ const messages = formatWebpackMessages(statsData)
155
+ const isSuccessful = !messages.errors.length && !messages.warnings.length
156
+ if (isSuccessful) {
157
+ console.log(green('Compiled successfully!'))
158
+ }
159
+
160
+ if (isSuccessful && (isInteractive || isFirstCompile)) {
161
+ printInstructions(appName, urls, useYarn)
162
+ }
163
+
164
+ isFirstCompile = false
165
+
166
+ // If errors exist, only show errors.
167
+ if (messages.errors.length) {
168
+ // Only keep the first error. Others are often indicative
169
+ // of the same problem, but confuse the reader with noise.
170
+ if (messages.errors.length > 1) {
171
+ messages.errors.length = 1
172
+ }
173
+ console.log(red('Failed to compile.\n'))
174
+ console.log(messages.errors.join('\n\n'))
175
+ return
176
+ }
177
+
178
+ // Show warnings if no errors were found.
179
+ if (messages.warnings.length) {
180
+ console.log(yellow('Compiled with warnings.\n'))
181
+ console.log(messages.warnings.join('\n\n'))
182
+
183
+ // Teach some ESLint tricks.
184
+ console.log(
185
+ `\nSearch for the ${yellow(
186
+ 'keywords'
187
+ )} to learn more about each warning.`
188
+ )
189
+ }
190
+ })
191
+
192
+ return compiler
193
+ }
194
+
195
+ function resolveLoopback(proxy) {
196
+ const o = url.parse(proxy)
197
+ o.host = undefined
198
+ if (o.hostname !== 'localhost') {
199
+ return proxy
200
+ }
201
+ // Unfortunately, many languages (unlike node) do not yet support IPv6.
202
+ // This means even though localhost resolves to ::1, the application
203
+ // must fall back to IPv4 (on 127.0.0.1).
204
+ // We can re-enable this in a few years.
205
+ /* try {
206
+ o.hostname = address.ipv6() ? '::1' : '127.0.0.1';
207
+ } catch (_ignored) {
208
+ o.hostname = '127.0.0.1';
209
+ } */
210
+
211
+ try {
212
+ // Check if we're on a network; if we are, chances are we can resolve
213
+ // localhost. Otherwise, we can just be safe and assume localhost is
214
+ // IPv4 for maximum compatibility.
215
+ if (!address.ip()) {
216
+ o.hostname = '127.0.0.1'
217
+ }
218
+ } catch (_ignored) {
219
+ o.hostname = '127.0.0.1'
220
+ }
221
+ return url.format(o)
222
+ }
223
+
224
+ // We need to provide a custom onError function for httpProxyMiddleware.
225
+ // It allows us to log custom error messages on the console.
226
+ function onProxyError(proxy) {
227
+ return (err, req, res) => {
228
+ const host = req.headers && req.headers.host
229
+ const error = `Proxy error: Could not proxy request ${req.url} from ${host} to ${proxy} (${err.code})`
230
+ console.log(error)
231
+
232
+ console.log(
233
+ 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
234
+ cyan(err.code) +
235
+ ').'
236
+ )
237
+
238
+ // And immediately send the proper error response to the client.
239
+ // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
240
+ if (res.writeHead && !res.headersSent) {
241
+ res.writeHead(500)
242
+ }
243
+
244
+ res.end(error)
245
+ }
246
+ }
247
+
248
+ function prepareProxy(proxy, appPublicFolder, servedPathname) {
249
+ // `proxy` lets you specify alternate servers for specific requests.
250
+ if (!proxy) return undefined
251
+
252
+ if (typeof proxy !== 'string') {
253
+ console.log(
254
+ red('When specified, "proxy" in package.json must be a string.')
255
+ )
256
+ console.log(red('Instead, the type of "proxy" was "' + typeof proxy + '".'))
257
+ console.log(
258
+ red('Either remove "proxy" from package.json, or make it a string.')
259
+ )
260
+ process.exit(1)
261
+ }
262
+
263
+ // If proxy is specified, let it handle any request except for
264
+ // files in the public folder and requests to the WebpackDevServer socket endpoint.
265
+ // https://github.com/facebook/create-react-app/issues/6720
266
+ const sockPath = process.env.WDS_SOCKET_PATH || '/ws'
267
+ const isDefaultSockHost = !process.env.WDS_SOCKET_HOST
268
+ function mayProxy(pathname) {
269
+ const maybePublicPath = path.resolve(
270
+ appPublicFolder,
271
+ pathname.replace(new RegExp('^' + servedPathname), '')
272
+ )
273
+ const isPublicFileRequest = fs.existsSync(maybePublicPath)
274
+ // used by webpackHotDevClient
275
+ const isWdsEndpointRequest =
276
+ isDefaultSockHost && pathname.startsWith(sockPath)
277
+ return !(isPublicFileRequest || isWdsEndpointRequest)
278
+ }
279
+
280
+ if (!/^http(s)?:\/\//.test(proxy)) {
281
+ console.log(
282
+ red(
283
+ 'When "proxy" is specified in package.json it must start with either http:// or https://'
284
+ )
285
+ )
286
+ process.exit(1)
287
+ }
288
+
289
+ const target = proxy
290
+
291
+ return [
292
+ {
293
+ target,
294
+ logLevel: 'silent',
295
+ // For single page apps, we generally want to fallback to /index.html.
296
+ // However we also want to respect `proxy` for API calls.
297
+ // So if `proxy` is specified as a string, we need to decide which fallback to use.
298
+ // We use a heuristic: We want to proxy all the requests that are not meant
299
+ // for static assets and as all the requests for static assets will be using
300
+ // `GET` method, we can proxy all non-`GET` requests.
301
+ // For `GET` requests, if request `accept`s text/html, we pick /index.html.
302
+ // Modern browsers include text/html into `accept` header when navigating.
303
+ // However API calls like `fetch()` won’t generally accept text/html.
304
+ // If this heuristic doesn’t work well for you, use `src/setupProxy.js`.
305
+ context: function(pathname, req) {
306
+ return (
307
+ req.method !== 'GET' ||
308
+ (mayProxy(pathname) &&
309
+ req.headers.accept &&
310
+ req.headers.accept.indexOf('text/html') === -1)
311
+ )
312
+ },
313
+ onProxyReq: proxyReq => {
314
+ // Browsers may send Origin headers even with same-origin
315
+ // requests. To prevent CORS issues, we have to change
316
+ // the Origin to match the target URL.
317
+ if (proxyReq.getHeader('origin')) {
318
+ proxyReq.setHeader('origin', target)
319
+ }
320
+ },
321
+ onError: onProxyError(target),
322
+ secure: false,
323
+ changeOrigin: true,
324
+ ws: true,
325
+ xfwd: true
326
+ }
327
+ ]
328
+ }
329
+
330
+ async function choosePort(defaultPort) {
331
+ const isDefaultPortFree = await isFreePort(defaultPort)
332
+ if (isDefaultPortFree) return defaultPort
333
+
334
+ console.log(`Something is already running on port ${defaultPort}.`)
335
+
336
+ const [freePort] = await findFreePorts(1, {startPort: 3000})
337
+
338
+ if (isInteractive) {
339
+ clearConsole()
340
+ const existingProcess = getProcessForPort(defaultPort)
341
+ if (existingProcess) {
342
+ console.log(`It seems that ${existingProcess} is using the default port.`)
343
+ console.log(green(`Using free port: ${freePort} instead.`))
344
+ }
345
+ return freePort
346
+ }
347
+ }
348
+
349
+ module.exports = {
350
+ choosePort,
351
+ createCompiler,
352
+ prepareProxy,
353
+ prepareUrls
354
+ }
@@ -0,0 +1,81 @@
1
+ // @ts-check
2
+
3
+ 'use strict'
4
+
5
+ const {execSync, execFileSync} = require('child_process')
6
+ const {cyan, gray, bold} = require('@s-ui/helpers/colors')
7
+
8
+ /** @type {import('child_process').ExecSyncOptionsWithStringEncoding} */
9
+ const execOptions = {
10
+ encoding: 'utf8',
11
+ stdio: [
12
+ 'pipe', // stdin (default)
13
+ 'pipe', // stdout (default)
14
+ 'ignore' // stderr
15
+ ]
16
+ }
17
+
18
+ /**
19
+ * Get the process id for a given port.
20
+ * @param {number} port - The port to look for
21
+ * @returns {string} The process id
22
+ */
23
+ function getProcessIdOnPort(port) {
24
+ return execFileSync(
25
+ 'lsof',
26
+ [`-i:${port}`, '-P', '-t', '-sTCP:LISTEN'],
27
+ execOptions
28
+ )
29
+ .split('\n')[0]
30
+ .trim()
31
+ }
32
+
33
+ /**
34
+ * Get the command for a given process id.
35
+ * @param {string} processId - The process id
36
+ * @returns {string} - The process name
37
+ */
38
+ function getProcessCommand(processId) {
39
+ const command = execSync(
40
+ 'ps -o command -p ' + processId + ' | sed -n 2p',
41
+ execOptions
42
+ )
43
+
44
+ return command.replace(/\n$/, '')
45
+ }
46
+
47
+ /**
48
+ * Get the directory of a process by its id.
49
+ * @param {string} processId - The process id
50
+ * @returns {string} - The process directory
51
+ */
52
+ function getDirectoryOfProcessById(processId) {
53
+ return execSync(
54
+ `lsof -p ${processId} | awk '$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}'`,
55
+ execOptions
56
+ ).trim()
57
+ }
58
+
59
+ /**
60
+ * Get all the information about a process running in a port
61
+ * @param {number} port - The port to look for
62
+ * @returns {null |}
63
+ */
64
+ function getProcessForPort(port) {
65
+ try {
66
+ const processId = getProcessIdOnPort(port)
67
+ const directory = getDirectoryOfProcessById(processId)
68
+ const command = getProcessCommand(processId)
69
+
70
+ return (
71
+ bold(command) +
72
+ gray(' (pid ' + processId + ')\n') +
73
+ gray(' in ') +
74
+ cyan(directory)
75
+ )
76
+ } catch (e) {
77
+ return null
78
+ }
79
+ }
80
+
81
+ module.exports = getProcessForPort
@@ -0,0 +1,22 @@
1
+ // Extracted from: https://github.com/facebook/create-react-app/blob/bb64e31a81eb12d688c14713dce812143688750a/packages/react-dev-utils/ignoredFiles.js
2
+
3
+ /**
4
+ * Copyright (c) 2015-present, Facebook, Inc.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ */
9
+
10
+ 'use strict'
11
+
12
+ const path = require('path')
13
+ const escape = require('escape-string-regexp')
14
+
15
+ module.exports = function ignoredFiles(appSrc) {
16
+ return new RegExp(
17
+ `^(?!${escape(
18
+ path.normalize(appSrc + '/').replace(/[\\]+/g, '/')
19
+ )}).+/node_modules/`,
20
+ 'g'
21
+ )
22
+ }
@@ -0,0 +1,40 @@
1
+ // from: https://github.com/facebook/create-react-app/blob/main/packages/react-dev-utils/noopServiceWorkerMiddleware.js
2
+
3
+ /**
4
+ * Copyright (c) 2015-present, Facebook, Inc.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ */
9
+
10
+ 'use strict'
11
+
12
+ const path = require('path')
13
+
14
+ module.exports = function createNoopServiceWorkerMiddleware(servedPath) {
15
+ return function noopServiceWorkerMiddleware(req, res, next) {
16
+ if (req.url === path.join(servedPath, 'service-worker.js')) {
17
+ res.setHeader('Content-Type', 'text/javascript')
18
+ res.send(
19
+ `// This service worker file is effectively a 'no-op' that will reset any
20
+ // previous service worker registered for the same host:port combination.
21
+ // In the production build, this file is replaced with an actual service worker
22
+ // file that will precache your site's local assets.
23
+ // See https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
24
+ self.addEventListener('install', () => self.skipWaiting());
25
+ self.addEventListener('activate', () => {
26
+ self.clients.matchAll({ type: 'window' }).then(windowClients => {
27
+ for (let windowClient of windowClients) {
28
+ // Force open pages to refresh, so that they have a chance to load the
29
+ // fresh navigation response from the local dev server.
30
+ windowClient.navigate(windowClient.url);
31
+ }
32
+ });
33
+ });
34
+ `
35
+ )
36
+ } else {
37
+ next()
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,253 @@
1
+ // @ts-check
2
+
3
+ /* globals __webpack_hash__ */
4
+
5
+ /**
6
+ * Copyright (c) 2015-present, Facebook, Inc.
7
+ *
8
+ * This source code is licensed under the MIT license found in the
9
+ * LICENSE file in the root directory of this source tree.
10
+ */
11
+
12
+ 'use strict'
13
+
14
+ // This alternative WebpackDevServer combines the functionality of:
15
+ // https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
16
+ // https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
17
+
18
+ // It only supports their simplest configuration (hot updates on same server).
19
+ // It makes some opinionated choices on top, like adding a syntax error overlay
20
+ // that looks similar to our console output. The error overlay is inspired by:
21
+ // https://github.com/glenjamin/webpack-hot-middleware
22
+
23
+ const stripAnsi = require('strip-ansi')
24
+ const url = require('url')
25
+ const formatWebpackMessages = require('./formatWebpackMessages')
26
+
27
+ // We need to keep track of if there has been a runtime error.
28
+ // Essentially, we cannot guarantee application state was not corrupted by the
29
+ // runtime error. To prevent confusing behavior, we forcibly reload the entire
30
+ // application. This is handled below when we are notified of a compile (code
31
+ // change).
32
+ // See https://github.com/facebook/create-react-app/issues/3096
33
+ const hadRuntimeError = false
34
+
35
+ // Connect to WebpackDevServer via a socket.
36
+ const connection = new WebSocket(
37
+ url.format({
38
+ protocol: window.location.protocol === 'https:' ? 'wss' : 'ws',
39
+ hostname: process.env.WDS_SOCKET_HOST || window.location.hostname,
40
+ port: process.env.WDS_SOCKET_PORT || window.location.port,
41
+ // Hardcoded in WebpackDevServer
42
+ pathname: process.env.WDS_SOCKET_PATH || '/ws',
43
+ slashes: true
44
+ })
45
+ )
46
+
47
+ // Unlike WebpackDevServer client, we won't try to reconnect
48
+ // to avoid spamming the console. Disconnect usually happens
49
+ // when developer stops the server.
50
+ connection.onclose = function() {
51
+ if (typeof console !== 'undefined' && typeof console.info === 'function') {
52
+ console.info(
53
+ 'The development server has disconnected.\nRefresh the page if necessary.'
54
+ )
55
+ }
56
+ }
57
+
58
+ // Remember some state related to hot module replacement.
59
+ let isFirstCompilation = true
60
+ let mostRecentCompilationHash = null
61
+ let hasCompileErrors = false
62
+
63
+ function clearOutdatedErrors() {
64
+ // Clean up outdated compile errors, if any.
65
+ if (typeof console !== 'undefined' && typeof console.clear === 'function') {
66
+ if (hasCompileErrors) {
67
+ console.clear()
68
+ }
69
+ }
70
+ }
71
+
72
+ // Successful compilation.
73
+ function handleSuccess() {
74
+ clearOutdatedErrors()
75
+
76
+ const isHotUpdate = !isFirstCompilation
77
+ isFirstCompilation = false
78
+ hasCompileErrors = false
79
+
80
+ // Attempt to apply hot updates or reload.
81
+ if (isHotUpdate) {
82
+ tryApplyUpdates()
83
+ }
84
+ }
85
+
86
+ // Compilation with warnings (e.g. ESLint).
87
+ function handleWarnings(warnings) {
88
+ clearOutdatedErrors()
89
+
90
+ const isHotUpdate = !isFirstCompilation
91
+ isFirstCompilation = false
92
+ hasCompileErrors = false
93
+
94
+ function printWarnings() {
95
+ // Print warnings to the console.
96
+ const formatted = formatWebpackMessages({
97
+ warnings: warnings,
98
+ errors: []
99
+ })
100
+
101
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
102
+ for (let i = 0; i < formatted.warnings.length; i++) {
103
+ if (i === 5) {
104
+ console.warn(
105
+ 'There were more warnings in other files.\n' +
106
+ 'You can find a complete log in the terminal.'
107
+ )
108
+ break
109
+ }
110
+ console.warn(stripAnsi(formatted.warnings[i]))
111
+ }
112
+ }
113
+ }
114
+
115
+ printWarnings()
116
+
117
+ // Attempt to apply hot updates or reload.
118
+ if (isHotUpdate) {
119
+ tryApplyUpdates()
120
+ }
121
+ }
122
+
123
+ // Compilation with errors (e.g. syntax error or missing modules).
124
+ function handleErrors(errors) {
125
+ clearOutdatedErrors()
126
+
127
+ isFirstCompilation = false
128
+ hasCompileErrors = true
129
+
130
+ // "Massage" webpack messages.
131
+ const formatted = formatWebpackMessages({
132
+ errors: errors,
133
+ warnings: []
134
+ })
135
+
136
+ // Also log them to the console.
137
+ if (typeof console !== 'undefined' && typeof console.error === 'function') {
138
+ for (let i = 0; i < formatted.errors.length; i++) {
139
+ console.error(stripAnsi(formatted.errors[i]))
140
+ }
141
+ }
142
+
143
+ // Do not attempt to reload now.
144
+ // We will reload on next success instead.
145
+ }
146
+
147
+ // There is a newer version of the code available.
148
+ function handleAvailableHash(hash) {
149
+ // Update last known compilation hash.
150
+ mostRecentCompilationHash = hash
151
+ }
152
+
153
+ // Handle messages from the server.
154
+ connection.onmessage = function(e) {
155
+ const message = JSON.parse(e.data)
156
+ switch (message.type) {
157
+ case 'hash':
158
+ handleAvailableHash(message.data)
159
+ break
160
+ case 'still-ok':
161
+ case 'ok':
162
+ handleSuccess()
163
+ break
164
+ case 'content-changed':
165
+ // Triggered when a file from `contentBase` changed.
166
+ window.location.reload()
167
+ break
168
+ case 'warnings':
169
+ handleWarnings(message.data)
170
+ break
171
+ case 'errors':
172
+ handleErrors(message.data)
173
+ break
174
+ default:
175
+ // Do nothing.
176
+ }
177
+ }
178
+
179
+ // Is there a newer version of this code available?
180
+ function isUpdateAvailable() {
181
+ // __webpack_hash__ is the hash of the current compilation.
182
+ // It's a global variable injected by webpack.
183
+ // eslint-disable-next-line camelcase
184
+ return mostRecentCompilationHash !== __webpack_hash__
185
+ }
186
+
187
+ // webpack disallows updates in other states.
188
+ function canApplyUpdates() {
189
+ return module.hot.status() === 'idle'
190
+ }
191
+
192
+ function canAcceptErrors() {
193
+ // NOTE: This var is injected by Webpack's DefinePlugin, and is a boolean instead of string.
194
+ const hasReactRefresh = process.env.FAST_REFRESH
195
+
196
+ const status = module.hot.status()
197
+ // React refresh can handle hot-reloading over errors.
198
+ // However, when hot-reload status is abort or fail,
199
+ // it indicates the current update cannot be applied safely,
200
+ // and thus we should bail out to a forced reload for consistency.
201
+ return hasReactRefresh && ['abort', 'fail'].indexOf(status) === -1
202
+ }
203
+
204
+ // Attempt to update code on the fly, fall back to a hard reload.
205
+ function tryApplyUpdates(onHotUpdateSuccess) {
206
+ if (!module.hot) {
207
+ // HotModuleReplacementPlugin is not in webpack configuration.
208
+ window.location.reload()
209
+ return
210
+ }
211
+
212
+ if (!isUpdateAvailable() || !canApplyUpdates()) {
213
+ return
214
+ }
215
+
216
+ function handleApplyUpdates(err, updatedModules) {
217
+ const haveErrors = err || hadRuntimeError
218
+ // When there is no error but updatedModules is unavailable,
219
+ // it indicates a critical failure in hot-reloading,
220
+ // e.g. server is not ready to serve new bundle,
221
+ // and hence we need to do a forced reload.
222
+ const needsForcedReload = !err && !updatedModules
223
+ if ((haveErrors && !canAcceptErrors()) || needsForcedReload) {
224
+ window.location.reload()
225
+ return
226
+ }
227
+
228
+ if (typeof onHotUpdateSuccess === 'function') {
229
+ // Maybe we want to do something.
230
+ onHotUpdateSuccess()
231
+ }
232
+
233
+ if (isUpdateAvailable()) {
234
+ // While we were updating, there was a new update! Do it again.
235
+ tryApplyUpdates()
236
+ }
237
+ }
238
+
239
+ // https://webpack.github.io/docs/hot-module-replacement.html#check
240
+ const result = module.hot.check(/* autoApply */ true, handleApplyUpdates)
241
+
242
+ // // webpack 2 returns a Promise instead of invoking a callback
243
+ if (result && result.then) {
244
+ result.then(
245
+ function(updatedModules) {
246
+ handleApplyUpdates(null, updatedModules)
247
+ },
248
+ function(err) {
249
+ handleApplyUpdates(err, null)
250
+ }
251
+ )
252
+ }
253
+ }