@rspack/dev-server 1.0.10 → 1.1.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/client/index.js CHANGED
@@ -1,79 +1,38 @@
1
1
  // @ts-nocheck
2
- function ownKeys(object, enumerableOnly) {
3
- var keys = Object.keys(object);
4
- if (Object.getOwnPropertySymbols) {
5
- var symbols = Object.getOwnPropertySymbols(object);
6
- enumerableOnly &&
7
- (symbols = symbols.filter(function (sym) {
8
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
9
- })),
10
- keys.push.apply(keys, symbols);
11
- }
12
- return keys;
13
- }
14
- function _objectSpread(target) {
15
- for (var i = 1; i < arguments.length; i++) {
16
- var source = null != arguments[i] ? arguments[i] : {};
17
- i % 2
18
- ? ownKeys(Object(source), !0).forEach(function (key) {
19
- _defineProperty(target, key, source[key]);
20
- })
21
- : Object.getOwnPropertyDescriptors
22
- ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source))
23
- : ownKeys(Object(source)).forEach(function (key) {
24
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
25
- });
26
- }
27
- return target;
28
- }
29
- function _defineProperty(obj, key, value) {
30
- key = _toPropertyKey(key);
31
- if (key in obj) {
32
- Object.defineProperty(obj, key, {
33
- value: value,
34
- enumerable: true,
35
- configurable: true,
36
- writable: true
37
- });
38
- }
39
- else {
40
- obj[key] = value;
41
- }
42
- return obj;
43
- }
44
- function _toPropertyKey(arg) {
45
- var key = _toPrimitive(arg, "string");
46
- return typeof key === "symbol" ? key : String(key);
47
- }
48
- function _toPrimitive(input, hint) {
49
- if (typeof input !== "object" || input === null)
50
- return input;
51
- var prim = input[Symbol.toPrimitive];
52
- if (prim !== undefined) {
53
- var res = prim.call(input, hint || "default");
54
- if (typeof res !== "object")
55
- return res;
56
- throw new TypeError("@@toPrimitive must return a primitive value.");
57
- }
58
- return (hint === "string" ? String : Number)(input);
59
- }
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ import hotEmitter from "@rspack/core/hot/emitter.js";
60
14
  /* global __resourceQuery, __webpack_hash__ */
15
+ /* Rspack dev server runtime client */
61
16
  /// <reference types="webpack/module" />
62
17
  import webpackHotLog from "@rspack/core/hot/log.js";
63
- import stripAnsi from "webpack-dev-server/client/utils/stripAnsi.js";
64
- import parseURL from "webpack-dev-server/client/utils/parseURL.js";
18
+ import { createOverlay, formatProblem, } from "webpack-dev-server/client/overlay.js";
65
19
  import socket from "webpack-dev-server/client/socket.js";
66
- import { formatProblem, createOverlay } from "webpack-dev-server/client/overlay.js";
67
- import { log, logEnabledFeatures, setLogLevel } from "webpack-dev-server/client/utils/log.js";
20
+ import { defineProgressElement, isProgressSupported, } from "webpack-dev-server/client/progress.js";
21
+ import { log, setLogLevel } from "webpack-dev-server/client/utils/log.js";
68
22
  import sendMessage from "webpack-dev-server/client/utils/sendMessage.js";
69
- import reloadApp from "./utils/reloadApp.js";
70
- import createSocketURL from "webpack-dev-server/client/utils/createSocketURL.js";
23
+ /**
24
+ * @typedef {Object} OverlayOptions
25
+ * @property {boolean | (error: Error) => boolean} [warnings]
26
+ * @property {boolean | (error: Error) => boolean} [errors]
27
+ * @property {boolean | (error: Error) => boolean} [runtimeErrors]
28
+ * @property {string} [trustedTypesPolicyName]
29
+ */
71
30
  /**
72
31
  * @typedef {Object} Options
73
32
  * @property {boolean} hot
74
33
  * @property {boolean} liveReload
75
34
  * @property {boolean} progress
76
- * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean, trustedTypesPolicyName?: string }} overlay
35
+ * @property {boolean | OverlayOptions} overlay
77
36
  * @property {string} [logging]
78
37
  * @property {number} [reconnect]
79
38
  */
@@ -84,39 +43,94 @@ import createSocketURL from "webpack-dev-server/client/utils/createSocketURL.js"
84
43
  * @property {string} [previousHash]
85
44
  */
86
45
  /**
87
- * @type {Status}
46
+ * @param {boolean | { warnings?: boolean | string; errors?: boolean | string; runtimeErrors?: boolean | string; }} overlayOptions
88
47
  */
89
- var status = {
90
- isUnloading: false,
91
- // TODO Workaround for webpack v4, `__webpack_hash__` is not replaced without HotModuleReplacement
92
- // eslint-disable-next-line camelcase
93
- currentHash: typeof __webpack_hash__ !== "undefined" ? __webpack_hash__ : ""
94
- };
95
- var decodeOverlayOptions = function decodeOverlayOptions(overlayOptions) {
48
+ var decodeOverlayOptions = function (overlayOptions) {
96
49
  if (typeof overlayOptions === "object") {
97
50
  ["warnings", "errors", "runtimeErrors"].forEach(function (property) {
98
51
  if (typeof overlayOptions[property] === "string") {
99
52
  var overlayFilterFunctionString = decodeURIComponent(overlayOptions[property]);
100
53
  // eslint-disable-next-line no-new-func
101
- var overlayFilterFunction = new Function("message", "var callback = ".concat(overlayFilterFunctionString, "\n return callback(message)"));
102
- overlayOptions[property] = overlayFilterFunction;
54
+ overlayOptions[property] = new Function("message", "var callback = ".concat(overlayFilterFunctionString, "\n\t\t\t\treturn callback(message)"));
103
55
  }
104
56
  });
105
57
  }
106
58
  };
107
- /** @type {Options} */
108
- var options = {
109
- hot: false,
110
- liveReload: false,
111
- progress: false,
112
- overlay: false
59
+ /**
60
+ * @param {string} resourceQuery
61
+ * @returns {{ [key: string]: string | boolean }}
62
+ */
63
+ var parseURL = function (resourceQuery) {
64
+ /** @type {{ [key: string]: string }} */
65
+ var result = {};
66
+ if (typeof resourceQuery === "string" && resourceQuery !== "") {
67
+ var searchParams = resourceQuery.slice(1).split("&");
68
+ for (var i = 0; i < searchParams.length; i++) {
69
+ var pair = searchParams[i].split("=");
70
+ result[pair[0]] = decodeURIComponent(pair[1]);
71
+ }
72
+ }
73
+ else {
74
+ // Else, get the url from the <script> this file was called with.
75
+ var scriptSource = getCurrentScriptSource();
76
+ var scriptSourceURL = void 0;
77
+ try {
78
+ // The placeholder `baseURL` with `window.location.href`,
79
+ // is to allow parsing of path-relative or protocol-relative URLs,
80
+ // and will have no effect if `scriptSource` is a fully valid URL.
81
+ scriptSourceURL = new URL(scriptSource, self.location.href);
82
+ }
83
+ catch (error) {
84
+ // URL parsing failed, do nothing.
85
+ // We will still proceed to see if we can recover using `resourceQuery`
86
+ }
87
+ if (scriptSourceURL) {
88
+ result = scriptSourceURL;
89
+ result.fromCurrentScript = true;
90
+ }
91
+ }
92
+ return result;
93
+ };
94
+ /**
95
+ * @type {Status}
96
+ */
97
+ var status = {
98
+ isUnloading: false,
99
+ // eslint-disable-next-line camelcase
100
+ currentHash: __webpack_hash__,
101
+ };
102
+ /**
103
+ * @returns {string}
104
+ */
105
+ var getCurrentScriptSource = function () {
106
+ // `document.currentScript` is the most accurate way to find the current script,
107
+ // but is not supported in all browsers.
108
+ if (document.currentScript) {
109
+ return document.currentScript.getAttribute("src");
110
+ }
111
+ // Fallback to getting all scripts running in the document.
112
+ var scriptElements = document.scripts || [];
113
+ var scriptElementsWithSrc = Array.prototype.filter.call(scriptElements, function (element) { return element.getAttribute("src"); });
114
+ if (scriptElementsWithSrc.length > 0) {
115
+ var currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1];
116
+ return currentScript.getAttribute("src");
117
+ }
118
+ // Fail as there was no script to use.
119
+ throw new Error("[webpack-dev-server] Failed to get current script source.");
113
120
  };
114
121
  var parsedResourceQuery = parseURL(__resourceQuery);
115
122
  var enabledFeatures = {
116
123
  "Hot Module Replacement": false,
117
124
  "Live Reloading": false,
118
125
  Progress: false,
119
- Overlay: false
126
+ Overlay: false,
127
+ };
128
+ /** @type {Options} */
129
+ var options = {
130
+ hot: false,
131
+ liveReload: false,
132
+ progress: false,
133
+ overlay: false,
120
134
  };
121
135
  if (parsedResourceQuery.hot === "true") {
122
136
  options.hot = true;
@@ -139,11 +153,7 @@ if (parsedResourceQuery.overlay) {
139
153
  }
140
154
  // Fill in default "true" params for partially-specified objects.
141
155
  if (typeof options.overlay === "object") {
142
- options.overlay = _objectSpread({
143
- errors: true,
144
- warnings: true,
145
- runtimeErrors: true
146
- }, options.overlay);
156
+ options.overlay = __assign({ errors: true, warnings: true, runtimeErrors: true }, options.overlay);
147
157
  decodeOverlayOptions(options.overlay);
148
158
  }
149
159
  enabledFeatures.Overlay = true;
@@ -157,14 +167,29 @@ if (typeof parsedResourceQuery.reconnect !== "undefined") {
157
167
  /**
158
168
  * @param {string} level
159
169
  */
160
- function setAllLogLevel(level) {
170
+ var setAllLogLevel = function (level) {
161
171
  // This is needed because the HMR logger operate separately from dev server logger
162
172
  webpackHotLog.setLogLevel(level === "verbose" || level === "log" ? "info" : level);
163
173
  setLogLevel(level);
164
- }
174
+ };
165
175
  if (options.logging) {
166
176
  setAllLogLevel(options.logging);
167
177
  }
178
+ var logEnabledFeatures = function (features) {
179
+ var listEnabledFeatures = Object.keys(features);
180
+ if (!features || listEnabledFeatures.length === 0) {
181
+ return;
182
+ }
183
+ var logString = "Server started:";
184
+ // Server started: Hot Module Replacement enabled, Live Reloading enabled, Overlay disabled.
185
+ for (var i = 0; i < listEnabledFeatures.length; i++) {
186
+ var key = listEnabledFeatures[i];
187
+ logString += " ".concat(key, " ").concat(features[key] ? "enabled" : "disabled", ",");
188
+ }
189
+ // replace last comma with a period
190
+ logString = logString.slice(0, -1).concat(".");
191
+ log.info(logString);
192
+ };
168
193
  logEnabledFeatures(enabledFeatures);
169
194
  self.addEventListener("beforeunload", function () {
170
195
  status.isUnloading = true;
@@ -173,41 +198,108 @@ var overlay = typeof window !== "undefined"
173
198
  ? createOverlay(typeof options.overlay === "object"
174
199
  ? {
175
200
  trustedTypesPolicyName: options.overlay.trustedTypesPolicyName,
176
- catchRuntimeError: options.overlay.runtimeErrors
201
+ catchRuntimeError: options.overlay.runtimeErrors,
177
202
  }
178
203
  : {
179
204
  trustedTypesPolicyName: false,
180
- catchRuntimeError: options.overlay
205
+ catchRuntimeError: options.overlay,
181
206
  })
182
- : {
183
- send: function send() { }
184
- };
185
- /* Rspack dev server runtime client */
207
+ : { send: function () { } };
208
+ /**
209
+ * @param {Options} options
210
+ * @param {Status} currentStatus
211
+ */
212
+ var reloadApp = function (_a, currentStatus) {
213
+ var hot = _a.hot, liveReload = _a.liveReload;
214
+ if (currentStatus.isUnloading) {
215
+ return;
216
+ }
217
+ var currentHash = currentStatus.currentHash, previousHash = currentStatus.previousHash;
218
+ var isInitial = currentHash.indexOf(/** @type {string} */ (previousHash)) >= 0;
219
+ if (isInitial) {
220
+ return;
221
+ }
222
+ /**
223
+ * @param {Window} rootWindow
224
+ * @param {number} intervalId
225
+ */
226
+ function applyReload(rootWindow, intervalId) {
227
+ clearInterval(intervalId);
228
+ log.info("App updated. Reloading...");
229
+ rootWindow.location.reload();
230
+ }
231
+ var search = self.location.search.toLowerCase();
232
+ var allowToHot = search.indexOf("webpack-dev-server-hot=false") === -1;
233
+ var allowToLiveReload = search.indexOf("webpack-dev-server-live-reload=false") === -1;
234
+ if (hot && allowToHot) {
235
+ log.info("App hot update...");
236
+ hotEmitter.emit("webpackHotUpdate", currentStatus.currentHash);
237
+ if (typeof self !== "undefined" && self.window) {
238
+ // broadcast update to window
239
+ self.postMessage("webpackHotUpdate".concat(currentStatus.currentHash), "*");
240
+ }
241
+ }
242
+ // allow refreshing the page only if liveReload isn't disabled
243
+ else if (liveReload && allowToLiveReload) {
244
+ var rootWindow_1 = self;
245
+ // use parent window for reload (in case we're in an iframe with no valid src)
246
+ var intervalId_1 = self.setInterval(function () {
247
+ if (rootWindow_1.location.protocol !== "about:") {
248
+ // reload immediately if protocol is valid
249
+ applyReload(rootWindow_1, intervalId_1);
250
+ }
251
+ else {
252
+ rootWindow_1 = rootWindow_1.parent;
253
+ if (rootWindow_1.parent === rootWindow_1) {
254
+ // if parent equals current window we've reached the root which would continue forever, so trigger a reload anyways
255
+ applyReload(rootWindow_1, intervalId_1);
256
+ }
257
+ }
258
+ });
259
+ }
260
+ };
261
+ var ansiRegex = new RegExp([
262
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
263
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))",
264
+ ].join("|"), "g");
265
+ /**
266
+ *
267
+ * Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string.
268
+ * Adapted from code originally released by Sindre Sorhus
269
+ * Licensed the MIT License
270
+ *
271
+ * @param {string} string
272
+ * @return {string}
273
+ */
274
+ var stripAnsi = function (string) {
275
+ if (typeof string !== "string") {
276
+ throw new TypeError("Expected a `string`, got `".concat(typeof string, "`"));
277
+ }
278
+ return string.replace(ansiRegex, "");
279
+ };
186
280
  var onSocketMessage = {
187
- hot: function hot() {
281
+ hot: function () {
188
282
  if (parsedResourceQuery.hot === "false") {
189
283
  return;
190
284
  }
191
285
  options.hot = true;
192
286
  },
193
- liveReload: function liveReload() {
287
+ liveReload: function () {
194
288
  if (parsedResourceQuery["live-reload"] === "false") {
195
289
  return;
196
290
  }
197
291
  options.liveReload = true;
198
292
  },
199
- invalid: function invalid() {
293
+ invalid: function () {
200
294
  log.info("App updated. Recompiling...");
201
295
  // Fixes #1042. overlay doesn't clear if errors are fixed but warnings remain.
202
296
  if (options.overlay) {
203
- overlay.send({
204
- type: "DISMISS"
205
- });
297
+ overlay.send({ type: "DISMISS" });
206
298
  }
207
299
  sendMessage("Invalid");
208
300
  },
209
301
  /**
210
- * @param {string | undefined} _hash
302
+ * @param {string | undefined} hash
211
303
  */
212
304
  hash: function hash(_hash) {
213
305
  if (!_hash) {
@@ -220,7 +312,7 @@ var onSocketMessage = {
220
312
  /**
221
313
  * @param {boolean} value
222
314
  */
223
- overlay: function overlay(value) {
315
+ overlay: function (value) {
224
316
  if (typeof document === "undefined") {
225
317
  return;
226
318
  }
@@ -230,7 +322,7 @@ var onSocketMessage = {
230
322
  /**
231
323
  * @param {number} value
232
324
  */
233
- reconnect: function reconnect(value) {
325
+ reconnect: function (value) {
234
326
  if (parsedResourceQuery.reconnect === "false") {
235
327
  return;
236
328
  }
@@ -239,7 +331,7 @@ var onSocketMessage = {
239
331
  /**
240
332
  * @param {boolean} value
241
333
  */
242
- progress: function progress(value) {
334
+ progress: function (value) {
243
335
  options.progress = value;
244
336
  },
245
337
  /**
@@ -247,54 +339,51 @@ var onSocketMessage = {
247
339
  */
248
340
  "progress-update": function progressUpdate(data) {
249
341
  if (options.progress) {
250
- log.info(""
251
- .concat(data.pluginName ? "[".concat(data.pluginName, "] ") : "")
252
- .concat(data.percent, "% - ")
253
- .concat(data.msg, "."));
342
+ log.info("".concat(data.pluginName ? "[".concat(data.pluginName, "] ") : "").concat(data.percent, "% - ").concat(data.msg, "."));
343
+ }
344
+ if (isProgressSupported()) {
345
+ if (typeof options.progress === "string") {
346
+ var progress = document.querySelector("wds-progress");
347
+ if (!progress) {
348
+ defineProgressElement();
349
+ progress = document.createElement("wds-progress");
350
+ document.body.appendChild(progress);
351
+ }
352
+ progress.setAttribute("progress", data.percent);
353
+ progress.setAttribute("type", options.progress);
354
+ }
254
355
  }
255
356
  sendMessage("Progress", data);
256
357
  },
257
358
  "still-ok": function stillOk() {
258
359
  log.info("Nothing changed.");
259
360
  if (options.overlay) {
260
- overlay.send({
261
- type: "DISMISS"
262
- });
361
+ overlay.send({ type: "DISMISS" });
263
362
  }
264
363
  sendMessage("StillOk");
265
364
  },
266
- ok: function ok() {
365
+ ok: function () {
267
366
  sendMessage("Ok");
268
367
  if (options.overlay) {
269
- overlay.send({
270
- type: "DISMISS"
271
- });
368
+ overlay.send({ type: "DISMISS" });
272
369
  }
273
370
  reloadApp(options, status);
274
371
  },
275
- // TODO: remove in v5 in favor of 'static-changed'
276
- /**
277
- * @param {string} file
278
- */
279
- "content-changed": function contentChanged(file) {
280
- log.info("".concat(file ? '"'.concat(file, '"') : "Content", " from static directory was changed. Reloading..."));
281
- self.location.reload();
282
- },
283
372
  /**
284
373
  * @param {string} file
285
374
  */
286
375
  "static-changed": function staticChanged(file) {
287
- log.info("".concat(file ? '"'.concat(file, '"') : "Content", " from static directory was changed. Reloading..."));
376
+ log.info("".concat(file ? "\"".concat(file, "\"") : "Content", " from static directory was changed. Reloading..."));
288
377
  self.location.reload();
289
378
  },
290
379
  /**
291
380
  * @param {Error[]} warnings
292
381
  * @param {any} params
293
382
  */
294
- warnings: function warnings(_warnings, params) {
383
+ warnings: function (warnings, params) {
295
384
  log.warn("Warnings while compiling.");
296
- var printableWarnings = _warnings.map(function (error) {
297
- var _formatProblem = formatProblem("warning", error), header = _formatProblem.header, body = _formatProblem.body;
385
+ var printableWarnings = warnings.map(function (error) {
386
+ var _a = formatProblem("warning", error), header = _a.header, body = _a.body;
298
387
  return "".concat(header, "\n").concat(stripAnsi(body));
299
388
  });
300
389
  sendMessage("Warnings", printableWarnings);
@@ -306,13 +395,13 @@ var onSocketMessage = {
306
395
  : options.overlay && options.overlay.warnings;
307
396
  if (overlayWarningsSetting) {
308
397
  var warningsToDisplay = typeof overlayWarningsSetting === "function"
309
- ? _warnings.filter(overlayWarningsSetting)
310
- : _warnings;
398
+ ? warnings.filter(overlayWarningsSetting)
399
+ : warnings;
311
400
  if (warningsToDisplay.length) {
312
401
  overlay.send({
313
402
  type: "BUILD_ERROR",
314
403
  level: "warning",
315
- messages: _warnings
404
+ messages: warnings,
316
405
  });
317
406
  }
318
407
  }
@@ -324,10 +413,10 @@ var onSocketMessage = {
324
413
  /**
325
414
  * @param {Error[]} errors
326
415
  */
327
- errors: function errors(_errors) {
416
+ errors: function (errors) {
328
417
  log.error("Errors while compiling. Reload prevented.");
329
- var printableErrors = _errors.map(function (error) {
330
- var _formatProblem2 = formatProblem("error", error), header = _formatProblem2.header, body = _formatProblem2.body;
418
+ var printableErrors = errors.map(function (error) {
419
+ var _a = formatProblem("error", error), header = _a.header, body = _a.body;
331
420
  return "".concat(header, "\n").concat(stripAnsi(body));
332
421
  });
333
422
  sendMessage("Errors", printableErrors);
@@ -339,13 +428,13 @@ var onSocketMessage = {
339
428
  : options.overlay && options.overlay.errors;
340
429
  if (overlayErrorsSettings) {
341
430
  var errorsToDisplay = typeof overlayErrorsSettings === "function"
342
- ? _errors.filter(overlayErrorsSettings)
343
- : _errors;
431
+ ? errors.filter(overlayErrorsSettings)
432
+ : errors;
344
433
  if (errorsToDisplay.length) {
345
434
  overlay.send({
346
435
  type: "BUILD_ERROR",
347
436
  level: "error",
348
- messages: _errors
437
+ messages: errors,
349
438
  });
350
439
  }
351
440
  }
@@ -353,18 +442,137 @@ var onSocketMessage = {
353
442
  /**
354
443
  * @param {Error} error
355
444
  */
356
- error: function error(_error) {
357
- log.error(_error);
445
+ error: function (error) {
446
+ log.error(error);
358
447
  },
359
- close: function close() {
448
+ close: function () {
360
449
  log.info("Disconnected!");
361
450
  if (options.overlay) {
362
- overlay.send({
363
- type: "DISMISS"
364
- });
451
+ overlay.send({ type: "DISMISS" });
365
452
  }
366
453
  sendMessage("Close");
454
+ },
455
+ };
456
+ /**
457
+ * @param {{ protocol?: string, auth?: string, hostname?: string, port?: string, pathname?: string, search?: string, hash?: string, slashes?: boolean }} objURL
458
+ * @returns {string}
459
+ */
460
+ var formatURL = function (objURL) {
461
+ var protocol = objURL.protocol || "";
462
+ if (protocol && protocol.substr(-1) !== ":") {
463
+ protocol += ":";
464
+ }
465
+ var auth = objURL.auth || "";
466
+ if (auth) {
467
+ auth = encodeURIComponent(auth);
468
+ auth = auth.replace(/%3A/i, ":");
469
+ auth += "@";
470
+ }
471
+ var host = "";
472
+ if (objURL.hostname) {
473
+ host =
474
+ auth +
475
+ (objURL.hostname.indexOf(":") === -1
476
+ ? objURL.hostname
477
+ : "[".concat(objURL.hostname, "]"));
478
+ if (objURL.port) {
479
+ host += ":".concat(objURL.port);
480
+ }
481
+ }
482
+ var pathname = objURL.pathname || "";
483
+ if (objURL.slashes) {
484
+ host = "//".concat(host || "");
485
+ if (pathname && pathname.charAt(0) !== "/") {
486
+ pathname = "/".concat(pathname);
487
+ }
488
+ }
489
+ else if (!host) {
490
+ host = "";
491
+ }
492
+ var search = objURL.search || "";
493
+ if (search && search.charAt(0) !== "?") {
494
+ search = "?".concat(search);
495
+ }
496
+ var hash = objURL.hash || "";
497
+ if (hash && hash.charAt(0) !== "#") {
498
+ hash = "#".concat(hash);
499
+ }
500
+ pathname = pathname.replace(/[?#]/g,
501
+ /**
502
+ * @param {string} match
503
+ * @returns {string}
504
+ */
505
+ function (match) { return encodeURIComponent(match); });
506
+ search = search.replace("#", "%23");
507
+ return "".concat(protocol).concat(host).concat(pathname).concat(search).concat(hash);
508
+ };
509
+ /**
510
+ * @param {URL & { fromCurrentScript?: boolean }} parsedURL
511
+ * @returns {string}
512
+ */
513
+ var createSocketURL = function (parsedURL) {
514
+ var hostname = parsedURL.hostname;
515
+ // Node.js module parses it as `::`
516
+ // `new URL(urlString, [baseURLString])` parses it as '[::]'
517
+ var isInAddrAny = hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]";
518
+ // why do we need this check?
519
+ // hostname n/a for file protocol (example, when using electron, ionic)
520
+ // see: https://github.com/webpack/webpack-dev-server/pull/384
521
+ if (isInAddrAny &&
522
+ self.location.hostname &&
523
+ self.location.protocol.indexOf("http") === 0) {
524
+ hostname = self.location.hostname;
525
+ }
526
+ var socketURLProtocol = parsedURL.protocol || self.location.protocol;
527
+ // When https is used in the app, secure web sockets are always necessary because the browser doesn't accept non-secure web sockets.
528
+ if (socketURLProtocol === "auto:" ||
529
+ (hostname && isInAddrAny && self.location.protocol === "https:")) {
530
+ socketURLProtocol = self.location.protocol;
531
+ }
532
+ socketURLProtocol = socketURLProtocol.replace(/^(?:http|.+-extension|file)/i, "ws");
533
+ var socketURLAuth = "";
534
+ // `new URL(urlString, [baseURLstring])` doesn't have `auth` property
535
+ // Parse authentication credentials in case we need them
536
+ if (parsedURL.username) {
537
+ socketURLAuth = parsedURL.username;
538
+ // Since HTTP basic authentication does not allow empty username,
539
+ // we only include password if the username is not empty.
540
+ if (parsedURL.password) {
541
+ // Result: <username>:<password>
542
+ socketURLAuth = socketURLAuth.concat(":", parsedURL.password);
543
+ }
544
+ }
545
+ // In case the host is a raw IPv6 address, it can be enclosed in
546
+ // the brackets as the brackets are needed in the final URL string.
547
+ // Need to remove those as url.format blindly adds its own set of brackets
548
+ // if the host string contains colons. That would lead to non-working
549
+ // double brackets (e.g. [[::]]) host
550
+ //
551
+ // All of these web socket url params are optionally passed in through resourceQuery,
552
+ // so we need to fall back to the default if they are not provided
553
+ var socketURLHostname = (hostname ||
554
+ self.location.hostname ||
555
+ "localhost").replace(/^\[(.*)\]$/, "$1");
556
+ var socketURLPort = parsedURL.port;
557
+ if (!socketURLPort || socketURLPort === "0") {
558
+ socketURLPort = self.location.port;
559
+ }
560
+ // If path is provided it'll be passed in via the resourceQuery as a
561
+ // query param so it has to be parsed out of the querystring in order for the
562
+ // client to open the socket to the correct location.
563
+ var socketURLPathname = "/ws";
564
+ if (parsedURL.pathname && !parsedURL.fromCurrentScript) {
565
+ socketURLPathname = parsedURL.pathname;
367
566
  }
567
+ return formatURL({
568
+ protocol: socketURLProtocol,
569
+ auth: socketURLAuth,
570
+ hostname: socketURLHostname,
571
+ port: socketURLPort,
572
+ pathname: socketURLPathname,
573
+ slashes: true,
574
+ });
368
575
  };
369
576
  var socketURL = createSocketURL(parsedResourceQuery);
370
577
  socket(socketURL, onSocketMessage, options.reconnect);
578
+ export { getCurrentScriptSource, parseURL, createSocketURL };
@@ -10,7 +10,7 @@ var _defColors = {
10
10
  magenta: "ff00ff",
11
11
  cyan: "00ffee",
12
12
  lightgrey: "f0f0f0",
13
- darkgrey: "888"
13
+ darkgrey: "888",
14
14
  };
15
15
  var _styles = {
16
16
  30: "black",
@@ -20,10 +20,10 @@ var _styles = {
20
20
  34: "blue",
21
21
  35: "magenta",
22
22
  36: "cyan",
23
- 37: "lightgrey"
23
+ 37: "lightgrey",
24
24
  };
25
25
  var _colorMode = {
26
- 2: "rgb"
26
+ 2: "rgb",
27
27
  };
28
28
  var _openTags = {
29
29
  1: "font-weight:bold",
@@ -53,12 +53,12 @@ var _openTags = {
53
53
  match.advance(4);
54
54
  return "background-color: rgb(".concat(r, ",").concat(g, ",").concat(b, ")");
55
55
  }
56
- }
56
+ },
57
57
  };
58
58
  var _openTagToCloseTag = {
59
59
  3: "23",
60
60
  4: "24",
61
- 9: "29"
61
+ 9: "29",
62
62
  };
63
63
  var _closeTags = {
64
64
  0: function (ansiCodes) {
@@ -80,7 +80,7 @@ var _closeTags = {
80
80
  },
81
81
  23: "</i>",
82
82
  24: "</u>",
83
- 29: "</del>" // reset delete
83
+ 29: "</del>", // reset delete
84
84
  };
85
85
  for (var _i = 0, _a = [21, 22, 27, 28, 39, 49]; _i < _a.length; _i++) {
86
86
  var n = _a[_i];
@@ -115,7 +115,7 @@ export default function ansiHTML(text) {
115
115
  Object.defineProperty(match, "advance", {
116
116
  value: function (count) {
117
117
  this.splice(0, count);
118
- }
118
+ },
119
119
  });
120
120
  var rep = "";
121
121
  var seq;
@@ -127,7 +127,8 @@ export default function ansiHTML(text) {
127
127
  function applySeq(seq) {
128
128
  var other = _openTags[seq];
129
129
  if (other &&
130
- (other = typeof other === "function" ? other(match) : other)) {
130
+ (other =
131
+ typeof other === "function" ? other(match) : other)) {
131
132
  // If reset signal is encountered, we have to reset everything.
132
133
  var ret_1 = "";
133
134
  if (seq === "0") {
@@ -213,10 +214,10 @@ ansiHTML.reset = function () {
213
214
  ansiHTML.tags = {};
214
215
  if (Object.defineProperty) {
215
216
  Object.defineProperty(ansiHTML.tags, "open", {
216
- get: function () { return _openTags; }
217
+ get: function () { return _openTags; },
217
218
  });
218
219
  Object.defineProperty(ansiHTML.tags, "close", {
219
- get: function () { return _closeTags; }
220
+ get: function () { return _closeTags; },
220
221
  });
221
222
  }
222
223
  else {
@@ -8,6 +8,7 @@ const node_crypto_1 = __importDefault(require("node:crypto"));
8
8
  const node_path_1 = require("node:path");
9
9
  const node_url_1 = require("node:url");
10
10
  const mime_types_1 = __importDefault(require("mime-types"));
11
+ // biome-ignore lint/suspicious/noExplicitAny: _
11
12
  function etag(buf) {
12
13
  const hash = node_crypto_1.default.createHash("sha256").update(buf).digest("hex");
13
14
  const etag = hash;
package/dist/server.d.ts CHANGED
@@ -30,5 +30,6 @@ export declare class RspackDevServer extends WebpackDevServer {
30
30
  static version: string;
31
31
  constructor(options: DevServer, compiler: Compiler | MultiCompiler);
32
32
  initialize(): Promise<void>;
33
- private addAdditionalEntries;
33
+ getClientEntry(): string;
34
+ getClientHotEntry(): string | undefined;
34
35
  }
package/dist/server.js CHANGED
@@ -8,14 +8,13 @@ const core_1 = require("@rspack/core");
8
8
  const webpack_dev_server_1 = __importDefault(require("webpack-dev-server"));
9
9
  // @ts-ignore 'package.json' is not under 'rootDir'
10
10
  const package_json_1 = require("../package.json");
11
- const alias_1 = require("./alias");
12
11
  const patch_1 = require("./patch");
13
12
  (0, patch_1.applyDevServerPatch)();
14
13
  const getFreePort = async function getFreePort(port, host) {
15
14
  if (typeof port !== "undefined" && port !== null && port !== "auto") {
16
15
  return port;
17
16
  }
18
- const pRetry = require("p-retry");
17
+ const { default: pRetry } = await import("p-retry");
19
18
  const getPort = require("webpack-dev-server/lib/getPort");
20
19
  const basePort = typeof process.env.WEBPACK_DEV_SERVER_BASE_PORT !== "undefined"
21
20
  ? Number.parseInt(process.env.WEBPACK_DEV_SERVER_BASE_PORT, 10)
@@ -26,12 +25,13 @@ const getFreePort = async function getFreePort(port, host) {
26
25
  ? Number.parseInt(process.env.WEBPACK_DEV_SERVER_PORT_RETRY, 10)
27
26
  : 3;
28
27
  return pRetry(() => getPort(basePort, host), {
29
- retries: defaultPortRetry
28
+ retries: defaultPortRetry,
30
29
  });
31
30
  };
32
31
  webpack_dev_server_1.default.getFreePort = getFreePort;
33
32
  class RspackDevServer extends webpack_dev_server_1.default {
34
33
  constructor(options, compiler) {
34
+ // biome-ignore lint/suspicious/noExplicitAny: _
35
35
  super(options, compiler);
36
36
  // override
37
37
  }
@@ -48,26 +48,22 @@ class RspackDevServer extends webpack_dev_server_1.default {
48
48
  }
49
49
  compiler.options.resolve.alias = {
50
50
  "ansi-html-community": require.resolve("@rspack/dev-server/client/utils/ansiHTML"),
51
- ...compiler.options.resolve.alias
51
+ ...compiler.options.resolve.alias,
52
52
  };
53
53
  }
54
54
  }
55
55
  // @ts-expect-error
56
56
  await super.initialize();
57
57
  }
58
- // @ts-ignore
59
- addAdditionalEntries(compiler) {
60
- (0, alias_1.addResolveAlias)("webpack-dev-server", {
61
- "../client/index.js": require.resolve("@rspack/dev-server/client/index"),
62
- "webpack/hot/only-dev-server": require.resolve("@rspack/core/hot/only-dev-server"),
63
- "webpack/hot/dev-server": require.resolve("@rspack/core/hot/dev-server")
64
- });
65
- try {
66
- // @ts-expect-error
67
- super.addAdditionalEntries(compiler);
58
+ getClientEntry() {
59
+ return require.resolve("@rspack/dev-server/client/index");
60
+ }
61
+ getClientHotEntry() {
62
+ if (this.options.hot === "only") {
63
+ return require.resolve("@rspack/core/hot/only-dev-server");
68
64
  }
69
- finally {
70
- (0, alias_1.removeResolveAlias)("webpack-dev-server");
65
+ if (this.options.hot) {
66
+ return require.resolve("@rspack/core/hot/dev-server");
71
67
  }
72
68
  }
73
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspack/dev-server",
3
- "version": "1.0.10",
3
+ "version": "1.1.1",
4
4
  "license": "MIT",
5
5
  "description": "Development server for rspack",
6
6
  "main": "./dist/index.js",
@@ -41,54 +41,52 @@
41
41
  },
42
42
  "devDependencies": {
43
43
  "@biomejs/biome": "^1.8.3",
44
+ "@jest/reporters": "29.7.0",
44
45
  "@jest/test-sequencer": "^29.7.0",
45
46
  "@rspack/core": "1.0.11",
46
47
  "@rspack/plugin-react-refresh": "1.0.0",
47
- "@types/connect-history-api-fallback": "1.5.4",
48
48
  "@types/express": "4.17.21",
49
+ "@types/jest": "29.5.12",
49
50
  "@types/mime-types": "2.1.4",
50
51
  "@types/ws": "8.5.10",
52
+ "@hono/node-server": "^1.13.3",
53
+ "cross-env": "^7.0.3",
51
54
  "css-loader": "^6.11.0",
55
+ "connect": "^3.7.0",
56
+ "execa": "9.3.0",
57
+ "fs-extra": "11.2.0",
52
58
  "graceful-fs": "4.2.10",
53
59
  "http-proxy": "^1.18.1",
60
+ "hono": "^4.6.8",
61
+ "jest": "29.7.0",
62
+ "jest-cli": "29.7.0",
63
+ "jest-environment-node": "29.7.0",
54
64
  "jest-serializer-path": "^0.1.15",
65
+ "nano-staged": "^0.8.0",
55
66
  "prettier": "3.2.5",
56
67
  "puppeteer": "^23.2.2",
68
+ "react-refresh": "0.14.0",
57
69
  "require-from-string": "^2.0.2",
70
+ "semver": "7.6.3",
71
+ "simple-git-hooks": "^2.11.1",
58
72
  "sockjs-client": "^1.6.1",
59
73
  "style-loader": "^3.3.3",
60
74
  "supertest": "^6.1.3",
61
75
  "tcp-port-used": "^1.0.2",
76
+ "ts-jest": "29.1.2",
62
77
  "typescript": "5.0.2",
63
78
  "wait-for-expect": "^3.0.2",
64
- "@jest/reporters": "29.7.0",
65
- "@types/jest": "29.5.12",
66
- "cross-env": "^7.0.3",
67
- "husky": "^9.0.0",
68
- "jest": "29.7.0",
69
- "jest-cli": "29.7.0",
70
- "jest-environment-node": "29.7.0",
71
- "rimraf": "3.0.2",
72
- "ts-jest": "29.1.2",
73
- "webpack": "^5.94.0",
74
- "webpack-cli": "5.1.4",
75
- "react-refresh": "0.14.0",
76
- "execa": "9.3.0",
77
- "fs-extra": "11.2.0",
78
- "nano-staged": "^0.8.0",
79
- "semver": "7.6.3",
80
- "simple-git-hooks": "^2.11.1"
79
+ "webpack": "^5.94.0"
81
80
  },
82
81
  "dependencies": {
83
82
  "chokidar": "^3.6.0",
84
- "connect-history-api-fallback": "^2.0.0",
85
- "express": "^4.19.2",
86
- "http-proxy-middleware": "^2.0.6",
83
+ "express": "^4.21.2",
84
+ "http-proxy-middleware": "^2.0.7",
87
85
  "mime-types": "^2.1.35",
88
- "p-retry": "4.6.2",
86
+ "p-retry": "^6.2.0",
89
87
  "webpack-dev-middleware": "^7.4.2",
90
- "webpack-dev-server": "5.0.4",
91
- "ws": "^8.16.0"
88
+ "webpack-dev-server": "5.2.0",
89
+ "ws": "^8.18.0"
92
90
  },
93
91
  "peerDependencies": {
94
92
  "@rspack/core": "*"
@@ -1,60 +0,0 @@
1
- // @ts-nocheck
2
- import hotEmitter from "@rspack/core/hot/emitter.js";
3
- import { log } from "webpack-dev-server/client/utils/log.js";
4
- /** @typedef {import("../index").Options} Options
5
- /** @typedef {import("../index").Status} Status
6
-
7
- /**
8
- * @param {Options} options
9
- * @param {Status} status
10
- */
11
- function reloadApp(_ref, status) {
12
- var hot = _ref.hot, liveReload = _ref.liveReload;
13
- if (status.isUnloading) {
14
- return;
15
- }
16
- var currentHash = status.currentHash, previousHash = status.previousHash;
17
- var isInitial = currentHash.indexOf(/** @type {string} */ previousHash) >= 0;
18
- if (isInitial) {
19
- return;
20
- }
21
- /**
22
- * @param {Window} rootWindow
23
- * @param {number} intervalId
24
- */
25
- function applyReload(rootWindow, intervalId) {
26
- clearInterval(intervalId);
27
- log.info("App updated. Reloading...");
28
- rootWindow.location.reload();
29
- }
30
- var search = self.location.search.toLowerCase();
31
- var allowToHot = search.indexOf("webpack-dev-server-hot=false") === -1;
32
- var allowToLiveReload = search.indexOf("webpack-dev-server-live-reload=false") === -1;
33
- if (hot && allowToHot) {
34
- log.info("App hot update...");
35
- hotEmitter.emit("webpackHotUpdate", status.currentHash);
36
- if (typeof self !== "undefined" && self.window) {
37
- // broadcast update to window
38
- self.postMessage("webpackHotUpdate".concat(status.currentHash), "*");
39
- }
40
- }
41
- // allow refreshing the page only if liveReload isn't disabled
42
- else if (liveReload && allowToLiveReload) {
43
- var rootWindow = self;
44
- // use parent window for reload (in case we're in an iframe with no valid src)
45
- var intervalId = self.setInterval(function () {
46
- if (rootWindow.location.protocol !== "about:") {
47
- // reload immediately if protocol is valid
48
- applyReload(rootWindow, intervalId);
49
- }
50
- else {
51
- rootWindow = rootWindow.parent;
52
- if (rootWindow.parent === rootWindow) {
53
- // if parent equals current window we've reached the root which would continue forever, so trigger a reload anyways
54
- applyReload(rootWindow, intervalId);
55
- }
56
- }
57
- });
58
- }
59
- }
60
- export default reloadApp;
package/dist/alias.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export declare const addResolveAlias: (name: string, aliasMap: Record<string, string>) => void;
2
- export declare const removeResolveAlias: (name: string) => void;
package/dist/alias.js DELETED
@@ -1,45 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeResolveAlias = exports.addResolveAlias = void 0;
4
- const Module = require("node:module");
5
- const MODULE_MAP = {};
6
- const RESOLVER_MAP = {};
7
- const addResolveAlias = (name, aliasMap) => {
8
- const modulePath = require.resolve(name);
9
- if (modulePath in RESOLVER_MAP) {
10
- throw new Error(`Should not add resolve alias to ${name} again.`);
11
- }
12
- const m = require.cache[modulePath];
13
- if (!m) {
14
- throw new Error("Failed to resolve webpack-dev-server.");
15
- }
16
- RESOLVER_MAP[modulePath] = m.require.resolve;
17
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
18
- m.require.resolve = ((id, options) => aliasMap[id] ||
19
- RESOLVER_MAP[modulePath].apply(m.require, [
20
- id,
21
- options,
22
- ]));
23
- MODULE_MAP[modulePath] = Module._resolveFilename;
24
- Module._resolveFilename = (request, mod, ...args) => {
25
- if (mod.filename === modulePath && aliasMap[request]) {
26
- return aliasMap[request];
27
- }
28
- return MODULE_MAP[modulePath](request, mod, ...args);
29
- };
30
- };
31
- exports.addResolveAlias = addResolveAlias;
32
- const removeResolveAlias = (name) => {
33
- const modulePath = require.resolve(name);
34
- if (!(modulePath in RESOLVER_MAP)) {
35
- return;
36
- }
37
- const m = require.cache[modulePath];
38
- if (!m) {
39
- throw new Error("Failed to resolve webpack-dev-server");
40
- }
41
- Module._resolveFilename = MODULE_MAP[modulePath];
42
- m.require.resolve = RESOLVER_MAP[modulePath];
43
- delete RESOLVER_MAP[modulePath];
44
- };
45
- exports.removeResolveAlias = removeResolveAlias;