@rspack/dev-server 2.0.0-beta.1 → 2.0.0-beta.2

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 (42) hide show
  1. package/README.md +4 -3
  2. package/client/clients/WebSocketClient.d.ts +17 -0
  3. package/client/clients/WebSocketClient.js +28 -28
  4. package/client/index.d.ts +17 -0
  5. package/client/index.js +224 -363
  6. package/client/modules/logger/Logger.d.ts +40 -0
  7. package/client/modules/logger/Logger.js +123 -0
  8. package/client/modules/logger/createConsoleLogger.d.ts +12 -0
  9. package/client/modules/logger/createConsoleLogger.js +119 -0
  10. package/client/modules/logger/index.d.ts +18 -0
  11. package/client/modules/logger/index.js +20 -712
  12. package/client/modules/types.d.ts +45 -0
  13. package/client/modules/types.js +17 -0
  14. package/client/overlay.d.ts +44 -0
  15. package/client/overlay.js +241 -290
  16. package/client/progress.d.ts +11 -0
  17. package/client/progress.js +178 -111
  18. package/client/socket.d.ts +15 -0
  19. package/client/socket.js +19 -46
  20. package/client/utils/ansiHTML.d.ts +30 -0
  21. package/client/utils/ansiHTML.js +106 -153
  22. package/client/utils/log.d.ts +13 -0
  23. package/client/utils/log.js +7 -17
  24. package/client/utils/sendMessage.d.ts +11 -0
  25. package/client/utils/sendMessage.js +6 -15
  26. package/dist/0~launch-editor.js +618 -0
  27. package/dist/0~open.js +547 -0
  28. package/dist/0~p-retry.js +158 -0
  29. package/dist/131.js +1398 -0
  30. package/dist/getPort.d.ts +4 -1
  31. package/dist/index.js +1 -5
  32. package/dist/rslib-runtime.js +66 -0
  33. package/dist/server.d.ts +7 -7
  34. package/dist/servers/WebsocketServer.d.ts +8 -1
  35. package/dist/types.d.ts +7 -5
  36. package/package.json +55 -58
  37. package/dist/config.js +0 -2
  38. package/dist/getPort.js +0 -141
  39. package/dist/server.js +0 -1971
  40. package/dist/servers/BaseServer.js +0 -20
  41. package/dist/servers/WebsocketServer.js +0 -72
  42. package/dist/types.js +0 -5
package/dist/getPort.d.ts CHANGED
@@ -7,4 +7,7 @@
7
7
  * Copyright (c) JS Foundation and other contributors
8
8
  * https://github.com/webpack/webpack-dev-server/blob/main/LICENSE
9
9
  */
10
- export {};
10
+ /**
11
+ * Get available ports
12
+ */
13
+ export declare function getPort(basePort: number, host?: string): Promise<number>;
package/dist/index.js CHANGED
@@ -1,5 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RspackDevServer = void 0;
4
- var server_1 = require("./server");
5
- Object.defineProperty(exports, "RspackDevServer", { enumerable: true, get: function () { return server_1.Server; } });
1
+ export { RspackDevServer } from "./131.js";
@@ -0,0 +1,66 @@
1
+ var __webpack_modules__ = {};
2
+ var __webpack_module_cache__ = {};
3
+ function __webpack_require__(moduleId) {
4
+ var cachedModule = __webpack_module_cache__[moduleId];
5
+ if (void 0 !== cachedModule) return cachedModule.exports;
6
+ var module = __webpack_module_cache__[moduleId] = {
7
+ exports: {}
8
+ };
9
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
10
+ return module.exports;
11
+ }
12
+ __webpack_require__.m = __webpack_modules__;
13
+ (()=>{
14
+ __webpack_require__.add = function(modules) {
15
+ Object.assign(__webpack_require__.m, modules);
16
+ };
17
+ })();
18
+ (()=>{
19
+ var getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__;
20
+ var leafPrototypes;
21
+ __webpack_require__.t = function(value, mode) {
22
+ if (1 & mode) value = this(value);
23
+ if (8 & mode) return value;
24
+ if ('object' == typeof value && value) {
25
+ if (4 & mode && value.__esModule) return value;
26
+ if (16 & mode && 'function' == typeof value.then) return value;
27
+ }
28
+ var ns = Object.create(null);
29
+ __webpack_require__.r(ns);
30
+ var def = {};
31
+ leafPrototypes = leafPrototypes || [
32
+ null,
33
+ getProto({}),
34
+ getProto([]),
35
+ getProto(getProto)
36
+ ];
37
+ for(var current = 2 & mode && value; ('object' == typeof current || 'function' == typeof current) && !~leafPrototypes.indexOf(current); current = getProto(current))Object.getOwnPropertyNames(current).forEach((key)=>{
38
+ def[key] = ()=>value[key];
39
+ });
40
+ def['default'] = ()=>value;
41
+ __webpack_require__.d(ns, def);
42
+ return ns;
43
+ };
44
+ })();
45
+ (()=>{
46
+ __webpack_require__.d = (exports, definition)=>{
47
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
48
+ enumerable: true,
49
+ get: definition[key]
50
+ });
51
+ };
52
+ })();
53
+ (()=>{
54
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
55
+ })();
56
+ (()=>{
57
+ __webpack_require__.r = (exports)=>{
58
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports, Symbol.toStringTag, {
59
+ value: 'Module'
60
+ });
61
+ Object.defineProperty(exports, '__esModule', {
62
+ value: true
63
+ });
64
+ };
65
+ })();
66
+ export { __webpack_require__ };
package/dist/server.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * Copyright (c) JS Foundation and other contributors
8
8
  * https://github.com/webpack/webpack-dev-server/blob/main/LICENSE
9
9
  */
10
- import type { BasicApplication, ClientConfiguration, ClientConnection, Compiler, ConnectHistoryApiFallbackOptions, DevMiddlewareContext, DevMiddlewareOptions, DevServer, EXPECTED_ANY, ExpressApplication, FSWatcher, HTTPServer, Headers, Host, Middleware, MultiCompiler, MultiStats, NextFunction, Open, Port, ProxyConfigArray, Request, RequestHandler, Response, ServerConfiguration, ServerType, Socket, Static, Stats, StatsCompilation, StatsOptions, WatchFiles, WatchOptions, WebSocketServerConfiguration, WebSocketServerImplementation } from './types';
10
+ import type { BasicApplication, ClientConfiguration, ClientConnection, Compiler, ConnectHistoryApiFallbackOptions, DevMiddlewareContext, DevMiddlewareOptions, DevServer, EXPECTED_ANY, ExpressApplication, FSWatcher, HTTPServer, Headers, Host, LiteralUnion, Middleware, MultiCompiler, MultiStats, NextFunction, Open, Port, ProxyConfigArray, Request, RequestHandler, Response, ServerConfiguration, ServerType, Socket, Static, Stats, StatsCompilation, StatsOptions, WatchFiles, WatchOptions, WebSocketServerConfiguration, WebSocketServerImplementation } from './types';
11
11
  export interface Configuration<A extends BasicApplication = ExpressApplication, S extends HTTPServer = HTTPServer> {
12
12
  ipc?: boolean | string;
13
13
  host?: Host;
@@ -16,13 +16,13 @@ export interface Configuration<A extends BasicApplication = ExpressApplication,
16
16
  liveReload?: boolean;
17
17
  devMiddleware?: DevMiddlewareOptions<Request, Response>;
18
18
  compress?: boolean;
19
- allowedHosts?: 'auto' | 'all' | string | string[];
19
+ allowedHosts?: LiteralUnion<'auto' | 'all', string> | string[];
20
20
  historyApiFallback?: boolean | ConnectHistoryApiFallbackOptions;
21
21
  watchFiles?: string | string[] | WatchFiles | Array<string | WatchFiles>;
22
22
  static?: boolean | string | Static | Array<string | Static>;
23
23
  server?: ServerType<A, S> | ServerConfiguration<A, S>;
24
24
  app?: () => Promise<A>;
25
- webSocketServer?: boolean | 'ws' | string | WebSocketServerConfiguration;
25
+ webSocketServer?: boolean | LiteralUnion<'ws', string> | WebSocketServerConfiguration;
26
26
  proxy?: ProxyConfigArray;
27
27
  open?: boolean | string | Open | Array<string | Open>;
28
28
  setupExitSignals?: boolean;
@@ -54,14 +54,14 @@ declare class Server<A extends BasicApplication = ExpressApplication, S extends
54
54
  static isAbsoluteURL(URL: string): boolean;
55
55
  static findIp(gatewayOrFamily: string, isInternal: boolean): string | undefined;
56
56
  static getHostname(hostname: Host): Promise<string>;
57
- static getFreePort(port: string, host: string): Promise<any>;
57
+ static getFreePort(port: string, host: string): Promise<string | number>;
58
58
  static findCacheDir(): string;
59
59
  addAdditionalEntries(compiler: Compiler): void;
60
60
  /**
61
61
  * @private
62
62
  * @returns {Compiler["options"]} compiler options
63
63
  */
64
- getCompilerOptions(): import("@rspack/core", { with: { "resolution-mode": "import" } }).RspackOptionsNormalized;
64
+ getCompilerOptions(): import("@rspack/core").RspackOptionsNormalized;
65
65
  shouldLogInfrastructureInfo(): boolean;
66
66
  normalizeOptions(): Promise<void>;
67
67
  /**
@@ -69,7 +69,7 @@ declare class Server<A extends BasicApplication = ExpressApplication, S extends
69
69
  * @returns {string} client transport
70
70
  */
71
71
  getClientTransport(): string;
72
- getServerTransport(): typeof import("./servers/WebsocketServer") | undefined;
72
+ getServerTransport(): unknown;
73
73
  getClientEntry(): string;
74
74
  getClientHotEntry(): string | undefined;
75
75
  setupProgressPlugin(): void;
@@ -83,7 +83,7 @@ declare class Server<A extends BasicApplication = ExpressApplication, S extends
83
83
  setupHooks(): void;
84
84
  setupWatchStaticFiles(): void;
85
85
  setupWatchFiles(): void;
86
- setupMiddlewares(): void;
86
+ setupMiddlewares(): Promise<void>;
87
87
  /**
88
88
  * @private
89
89
  * @returns {Promise<void>}
@@ -7,4 +7,11 @@
7
7
  * Copyright (c) JS Foundation and other contributors
8
8
  * https://github.com/webpack/webpack-dev-server/blob/main/LICENSE
9
9
  */
10
- export {};
10
+ import * as Ws from 'ws';
11
+ import type { Server } from '../server';
12
+ import BaseServer from './BaseServer';
13
+ export declare class WebsocketServer extends BaseServer {
14
+ static heartbeatInterval: number;
15
+ implementation: Ws.WebSocketServer;
16
+ constructor(server: Server);
17
+ }
package/dist/types.d.ts CHANGED
@@ -17,6 +17,8 @@ import type { Options as ServeIndexOptions } from 'serve-index';
17
17
  export type { ServeIndexOptions };
18
18
  import type { ServeStaticOptions } from 'serve-static';
19
19
  export type EXPECTED_ANY = any;
20
+ /** https://github.com/microsoft/TypeScript/issues/29729 */
21
+ export type LiteralUnion<T extends U, U> = T | (U & Record<never, never>);
20
22
  export type NextFunction = (err?: EXPECTED_ANY) => void;
21
23
  export type SimpleHandleFunction = (req: IncomingMessage, res: ServerResponse) => void;
22
24
  export type NextHandleFunction = (req: IncomingMessage, res: ServerResponse, next: NextFunction) => void;
@@ -27,8 +29,8 @@ export type Request<T extends BasicApplication = ExpressApplication> = T extends
27
29
  export type Response<T extends BasicApplication = ExpressApplication> = T extends ExpressApplication ? ExpressResponse : ServerResponse;
28
30
  export type DevMiddlewareOptions<T extends Request, U extends Response> = import('webpack-dev-middleware').Options<T, U>;
29
31
  export type DevMiddlewareContext<T extends Request, U extends Response> = import('webpack-dev-middleware').Context<T, U>;
30
- export type Host = 'local-ip' | 'local-ipv4' | 'local-ipv6' | string;
31
- export type Port = number | string | 'auto';
32
+ export type Host = LiteralUnion<'local-ip' | 'local-ipv4' | 'local-ipv6', string>;
33
+ export type Port = number | LiteralUnion<'auto', string>;
32
34
  export interface WatchFiles {
33
35
  paths: string | string[];
34
36
  options?: WatchOptions & {
@@ -55,13 +57,13 @@ export interface NormalizedStatic {
55
57
  staticOptions: ServeStaticOptions;
56
58
  watch: false | WatchOptions;
57
59
  }
58
- export type ServerType<A extends BasicApplication = ExpressApplication, S extends import('http').Server = import('http').Server> = 'http' | 'https' | 'http2' | string | ((serverOptions: ServerOptions, application: A) => S);
60
+ export type ServerType<A extends BasicApplication = ExpressApplication, S extends import('http').Server = import('http').Server> = LiteralUnion<'http' | 'https' | 'http2', string> | ((serverOptions: ServerOptions, application: A) => S);
59
61
  export interface ServerConfiguration<A extends BasicApplication = ExpressApplication, S extends import('http').Server = import('http').Server> {
60
62
  type?: ServerType<A, S>;
61
63
  options?: ServerOptions;
62
64
  }
63
65
  export interface WebSocketServerConfiguration {
64
- type?: 'ws' | string | (() => WebSocketServerConfiguration);
66
+ type?: LiteralUnion<'ws', string> | (() => WebSocketServerConfiguration);
65
67
  options?: Record<string, EXPECTED_ANY>;
66
68
  }
67
69
  export type ClientConnection = import('ws').WebSocket & {
@@ -109,7 +111,7 @@ export interface ClientConfiguration {
109
111
  };
110
112
  progress?: boolean;
111
113
  reconnect?: boolean | number;
112
- webSocketTransport?: 'ws' | string;
114
+ webSocketTransport?: LiteralUnion<'ws', string>;
113
115
  webSocketURL?: string | WebSocketURL;
114
116
  }
115
117
  export type Headers = Array<{
package/package.json CHANGED
@@ -1,38 +1,36 @@
1
1
  {
2
2
  "name": "@rspack/dev-server",
3
- "version": "2.0.0-beta.1",
4
- "license": "MIT",
3
+ "version": "2.0.0-beta.2",
5
4
  "description": "Development server for rspack",
6
- "main": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
8
- "publishConfig": {
9
- "access": "public",
10
- "registry": "https://registry.npmjs.org/"
5
+ "homepage": "https://rspack.rs",
6
+ "bugs": "https://github.com/rstackjs/rspack-dev-server/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/rstackjs/rspack-dev-server"
11
10
  },
11
+ "license": "MIT",
12
+ "type": "module",
12
13
  "exports": {
13
- ".": {
14
- "default": "./dist/index.js"
15
- },
16
- "./getPort": "./getPort.js",
17
- "./servers/*": "./servers/*.js",
18
- "./servers/*.js": "./servers/*.js",
19
- "./client/*": "./client/*.js",
14
+ ".": "./dist/index.js",
20
15
  "./client/*.js": "./client/*.js",
16
+ "./client/*": "./client/*.js",
21
17
  "./package.json": "./package.json"
22
18
  },
19
+ "types": "./dist/index.d.ts",
20
+ "files": [
21
+ "dist",
22
+ "client"
23
+ ],
23
24
  "scripts": {
24
- "build": "pnpm run build:server && pnpm run build:client && pnpm run build:client-modules",
25
- "build:server": "tsc -b ./tsconfig.build.json",
26
- "build:client": "tsc -b ./tsconfig.client.json",
27
- "build:client-modules": "node ./scripts/build-client-modules.cjs",
28
- "dev": "tsc -b -w",
25
+ "build": "rslib",
26
+ "bump": "npx bumpp",
27
+ "dev": "rslib -w",
28
+ "format": "prettier --write .",
29
29
  "lint": "biome check .",
30
30
  "lint:write": "biome check . --write",
31
- "format": "prettier --write .",
32
31
  "prettier:ci": "prettier --check .",
33
- "test:install": "cross-env ./node_modules/.bin/puppeteer browsers install chrome",
34
32
  "test": "pnpm run test:install && pnpm run build && rstest",
35
- "bump": "npx bumpp"
33
+ "test:install": "cross-env ./node_modules/.bin/puppeteer browsers install chrome"
36
34
  },
37
35
  "simple-git-hooks": {
38
36
  "pre-commit": "npx nano-staged"
@@ -46,23 +44,24 @@
46
44
  "biome lint --write --no-errors-on-unmatched"
47
45
  ]
48
46
  },
49
- "files": [
50
- "dist",
51
- "client"
52
- ],
53
- "engines": {
54
- "node": "^20.19.0 || >=22.12.0"
55
- },
56
- "packageManager": "pnpm@10.30.3",
57
- "homepage": "https://rspack.rs",
58
- "bugs": "https://github.com/rstackjs/rspack-dev-server/issues",
59
- "repository": {
60
- "type": "git",
61
- "url": "https://github.com/rstackjs/rspack-dev-server"
47
+ "dependencies": {
48
+ "@types/connect-history-api-fallback": "^1.5.4",
49
+ "@types/serve-index": "^1.9.4",
50
+ "@types/serve-static": "^2.2.0",
51
+ "@types/ws": "^8.18.1",
52
+ "chokidar": "^3.6.0",
53
+ "connect-history-api-fallback": "^2.0.0",
54
+ "express": "^5.2.1",
55
+ "http-proxy-middleware": "^3.0.5",
56
+ "ipaddr.js": "^2.3.0",
57
+ "serve-index": "^1.9.2",
58
+ "webpack-dev-middleware": "^7.4.5",
59
+ "ws": "^8.19.0"
62
60
  },
63
61
  "devDependencies": {
64
62
  "@biomejs/biome": "^1.9.4",
65
63
  "@hono/node-server": "^1.19.9",
64
+ "@rslib/core": "^0.19.6",
66
65
  "@rspack/core": "2.0.0-beta.5",
67
66
  "@rspack/plugin-react-refresh": "1.6.1",
68
67
  "@rstest/core": "^0.8.5",
@@ -73,43 +72,41 @@
73
72
  "@types/node-forge": "^1.3.14",
74
73
  "@types/trusted-types": "^2.0.7",
75
74
  "@types/ws": "8.18.1",
75
+ "compression": "^1.8.1",
76
76
  "connect": "^3.7.0",
77
77
  "cross-env": "^10.1.0",
78
78
  "css-loader": "^7.1.4",
79
79
  "hono": "^4.12.3",
80
80
  "http-proxy": "^1.18.1",
81
+ "launch-editor": "^2.13.1",
81
82
  "nano-staged": "^0.9.0",
83
+ "open": "^11.0.0",
84
+ "p-retry": "^7.1.1",
82
85
  "prettier": "3.8.1",
83
86
  "puppeteer": "^24.37.5",
84
87
  "react-refresh": "0.18.0",
85
88
  "require-from-string": "^2.0.2",
89
+ "selfsigned": "^5.5.0",
86
90
  "simple-git-hooks": "^2.13.1",
87
91
  "style-loader": "^4.0.0",
88
92
  "typescript": "^5.9.3",
89
- "webpack": "^5.105.3",
90
- "webpack-dev-middleware": "^7.4.5",
91
- "webpack-merge": "^6.0.1"
92
- },
93
- "dependencies": {
94
- "@types/connect-history-api-fallback": "^1.5.4",
95
- "@types/serve-index": "^1.9.4",
96
- "@types/serve-static": "^2.2.0",
97
- "@types/ws": "^8.18.1",
98
- "chokidar": "^3.6.0",
99
- "compression": "^1.8.1",
100
- "connect-history-api-fallback": "^2.0.0",
101
- "express": "^5.2.1",
102
- "http-proxy-middleware": "^3.0.5",
103
- "ipaddr.js": "^2.3.0",
104
- "launch-editor": "^2.13.1",
105
- "open": "^11.0.0",
106
- "p-retry": "^7.1.1",
107
- "selfsigned": "^5.5.0",
108
- "serve-index": "^1.9.2",
109
- "webpack-dev-middleware": "^7.4.5",
110
- "ws": "^8.19.0"
93
+ "webpack-dev-middleware": "^7.4.5"
111
94
  },
112
95
  "peerDependencies": {
113
- "@rspack/core": "^2.0.0-0"
96
+ "@rspack/core": "^2.0.0-0",
97
+ "selfsigned": "^5.0.0"
98
+ },
99
+ "peerDependenciesMeta": {
100
+ "selfsigned": {
101
+ "optional": true
102
+ }
103
+ },
104
+ "packageManager": "pnpm@10.30.3",
105
+ "engines": {
106
+ "node": "^20.19.0 || >=22.12.0"
107
+ },
108
+ "publishConfig": {
109
+ "access": "public",
110
+ "registry": "https://registry.npmjs.org/"
114
111
  }
115
112
  }
package/dist/config.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/dist/getPort.js DELETED
@@ -1,141 +0,0 @@
1
- "use strict";
2
- /**
3
- * The following code is modified based on
4
- * https://github.com/webpack/webpack-dev-server
5
- *
6
- * MIT Licensed
7
- * Author Tobias Koppers @sokra
8
- * Copyright (c) JS Foundation and other contributors
9
- * https://github.com/webpack/webpack-dev-server/blob/main/LICENSE
10
- */
11
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- var desc = Object.getOwnPropertyDescriptor(m, k);
14
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
- desc = { enumerable: true, get: function() { return m[k]; } };
16
- }
17
- Object.defineProperty(o, k2, desc);
18
- }) : (function(o, m, k, k2) {
19
- if (k2 === undefined) k2 = k;
20
- o[k2] = m[k];
21
- }));
22
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
- Object.defineProperty(o, "default", { enumerable: true, value: v });
24
- }) : function(o, v) {
25
- o["default"] = v;
26
- });
27
- var __importStar = (this && this.__importStar) || (function () {
28
- var ownKeys = function(o) {
29
- ownKeys = Object.getOwnPropertyNames || function (o) {
30
- var ar = [];
31
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
- return ar;
33
- };
34
- return ownKeys(o);
35
- };
36
- return function (mod) {
37
- if (mod && mod.__esModule) return mod;
38
- var result = {};
39
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
- __setModuleDefault(result, mod);
41
- return result;
42
- };
43
- })();
44
- Object.defineProperty(exports, "__esModule", { value: true });
45
- /*
46
- * Based on the packages get-port https://www.npmjs.com/package/get-port
47
- * and portfinder https://www.npmjs.com/package/portfinder
48
- * The code structure is similar to get-port, but it searches
49
- * ports deterministically like portfinder
50
- */
51
- const net = __importStar(require("node:net"));
52
- const os = __importStar(require("node:os"));
53
- const minPort = 1024;
54
- const maxPort = 65_535;
55
- /**
56
- * Get all local hosts
57
- */
58
- const getLocalHosts = () => {
59
- const interfaces = os.networkInterfaces();
60
- // Add undefined value for createServer function to use default host,
61
- // and default IPv4 host in case createServer defaults to IPv6.
62
- const results = new Set([undefined, '0.0.0.0']);
63
- for (const _interface of Object.values(interfaces)) {
64
- if (_interface) {
65
- for (const config of _interface) {
66
- results.add(config.address);
67
- }
68
- }
69
- }
70
- return results;
71
- };
72
- /**
73
- * Check if a port is available on a given host
74
- */
75
- const checkAvailablePort = (basePort, host) => new Promise((resolve, reject) => {
76
- const server = net.createServer();
77
- server.unref();
78
- server.on('error', reject);
79
- server.listen(basePort, host, () => {
80
- // Next line should return AddressInfo because we're calling it after listen() and before close()
81
- const { port } = server.address();
82
- server.close(() => {
83
- resolve(port);
84
- });
85
- });
86
- });
87
- /**
88
- * Get available port from hosts
89
- */
90
- const getAvailablePort = async (port, hosts) => {
91
- /**
92
- * Errors that mean that host is not available.
93
- */
94
- const nonExistentInterfaceErrors = new Set(['EADDRNOTAVAIL', 'EINVAL']);
95
- /* Check if the post is available on every local host name */
96
- for (const host of hosts) {
97
- try {
98
- await checkAvailablePort(port, host);
99
- }
100
- catch (error) {
101
- /* We throw an error only if the interface exists */
102
- if (!nonExistentInterfaceErrors.has(error.code || '')) {
103
- throw error;
104
- }
105
- }
106
- }
107
- return port;
108
- };
109
- /**
110
- * Get available ports
111
- */
112
- async function getPorts(basePort, host) {
113
- if (basePort < minPort || basePort > maxPort) {
114
- throw new Error(`Port number must lie between ${minPort} and ${maxPort}`);
115
- }
116
- let port = basePort;
117
- const localhosts = getLocalHosts();
118
- const hosts = host && !localhosts.has(host)
119
- ? new Set([host])
120
- : /* If the host is equivalent to localhost
121
- we need to check every equivalent host
122
- else the port might falsely appear as available
123
- on some operating systems */
124
- localhosts;
125
- const portUnavailableErrors = new Set(['EADDRINUSE', 'EACCES']);
126
- while (port <= maxPort) {
127
- try {
128
- const availablePort = await getAvailablePort(port, hosts);
129
- return availablePort;
130
- }
131
- catch (error) {
132
- /* Try next port if port is busy; throw for any other error */
133
- if (!portUnavailableErrors.has(error.code || '')) {
134
- throw error;
135
- }
136
- port += 1;
137
- }
138
- }
139
- throw new Error('No available ports found');
140
- }
141
- module.exports = getPorts;