first commit

This commit is contained in:
Stefan Hacker
2026-04-03 09:38:48 +02:00
commit 37ad745546
47450 changed files with 3120798 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+326
View File
@@ -0,0 +1,326 @@
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
</div>
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![discussion][discussion]][discussion-url]
[![downloads][downloads]][npm-url]
[![contributors][contributors]][contributors-url]
# webpack-dev-server
Use [webpack](https://webpack.js.org) with a development server that provides
live reloading. This should be used for **development only**.
It uses [webpack-dev-middleware][middleware-url] under the hood, which provides
fast in-memory access to the webpack assets.
## Table of Contents
- [Getting Started](#getting-started)
- [Usage](#usage)
- [With the CLI](#with-the-cli)
- [With NPM Scripts](#with-npm-scripts)
- [With the API](#with-the-api)
- [With TypeScript](#with-typescript)
- [The Result](#the-result)
- [Browser Support](#browser-support)
- [Support](#support)
- [Contributing](#contributing)
- [Attribution](#attribution)
- [License](#license)
## Getting Started
First things first, install the module:
```console
npm install webpack-dev-server --save-dev
```
or
```console
yarn add -D webpack-dev-server
```
or
```console
pnpm add -D webpack-dev-server
```
_Note: While you can install and run webpack-dev-server globally, we recommend
installing it locally. webpack-dev-server will always use a local installation
over a global one._
## Usage
There are two main, recommended methods of using the module:
### With the CLI
The easiest way to use it is with the [webpack CLI](https://webpack.js.org/api/cli/). In the directory where your
`webpack.config.js` is, run:
```console
npx webpack serve
```
Following options are available with `webpack serve`:
```
Usage: webpack serve|server|s [entries...] [options]
Run the webpack dev server.
Options:
-c, --config <value...> Provide path to a webpack configuration file e.g. ./webpack.config.js.
--config-name <value...> Name of the configuration to use.
-m, --merge Merge two or more configurations using 'webpack-merge'.
--disable-interpret Disable interpret for loading the config file.
--env <value...> Environment passed to the configuration when it is a function.
--node-env <value> Sets process.env.NODE_ENV to the specified value.
--define-process-env-node-env <value> Sets process.env.NODE_ENV to the specified value. (Currently an alias for `--node-env`)
--analyze It invokes webpack-bundle-analyzer plugin to get bundle information.
--progress [value] Print compilation progress during build.
-j, --json [value] Prints result as JSON or store it in a file.
--fail-on-warnings Stop webpack-cli process with non-zero exit code on warnings from webpack
-d, --devtool <value> A developer tool to enhance debugging (false | eval | [inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map).
--no-devtool Negative 'devtool' option.
--entry <value...> A module that is loaded upon startup. Only the last one is exported.
--mode <value> Enable production optimizations or development hints.
--name <value> Name of the configuration. Used when loading multiple configurations.
-o, --output-path <value> The output directory as **absolute path** (required).
--stats [value] Stats options object or preset name.
--no-stats Negative 'stats' option.
-t, --target <value...> Environment to build for. Environment to build for. An array of environments to build for all of them when possible.
--no-target Negative 'target' option.
--watch-options-stdin Stop watching when stdin stream has ended.
--no-watch-options-stdin Negative 'watch-options-stdin' option.
--allowed-hosts <value...> Allows to enumerate the hosts from which access to the dev server are allowed (useful when you are proxying dev server, by default is 'auto').
--allowed-hosts-reset Clear all items provided in 'allowedHosts' configuration. Allows to enumerate the hosts from which access to the dev server are allowed (useful when you are proxying dev server, by default is 'auto').
--bonjour Allows to broadcasts dev server via ZeroConf networking on start.
--no-bonjour Disallows to broadcasts dev server via ZeroConf networking on start.
--no-client Disables client script.
--client-logging <value> Allows to set log level in the browser.
--client-overlay Enables a full-screen overlay in the browser when there are compiler errors or warnings.
--no-client-overlay Disables the full-screen overlay in the browser when there are compiler errors or warnings.
--client-overlay-errors Enables a full-screen overlay in the browser when there are compiler errors.
--no-client-overlay-errors Disables the full-screen overlay in the browser when there are compiler errors.
--client-overlay-warnings Enables a full-screen overlay in the browser when there are compiler warnings.
--no-client-overlay-warnings Disables the full-screen overlay in the browser when there are compiler warnings.
--client-overlay-runtime-errors Enables a full-screen overlay in the browser when there are uncaught runtime errors.
--no-client-overlay-runtime-errors Disables the full-screen overlay in the browser when there are uncaught runtime errors.
--client-overlay-trusted-types-policy-name <value> The name of a Trusted Types policy for the overlay. Defaults to 'webpack-dev-server#overlay'.
--client-progress Prints compilation progress in percentage in the browser.
--no-client-progress Does not print compilation progress in percentage in the browser.
--client-reconnect [value] Tells dev-server the number of times it should try to reconnect the client.
--no-client-reconnect Tells dev-server to not to try to reconnect the client.
--client-web-socket-transport <value> Allows to set custom web socket transport to communicate with dev server.
--client-web-socket-url <value> Allows to specify URL to web socket server (useful when you're proxying dev server and client script does not always know where to connect to).
--client-web-socket-url-hostname <value> Tells clients connected to devServer to use the provided hostname.
--client-web-socket-url-pathname <value> Tells clients connected to devServer to use the provided path to connect.
--client-web-socket-url-password <value> Tells clients connected to devServer to use the provided password to authenticate.
--client-web-socket-url-port <value> Tells clients connected to devServer to use the provided port.
--client-web-socket-url-protocol <value> Tells clients connected to devServer to use the provided protocol.
--client-web-socket-url-username <value> Tells clients connected to devServer to use the provided username to authenticate.
--compress Enables gzip compression for everything served.
--no-compress Disables gzip compression for everything served.
--history-api-fallback Allows to proxy requests through a specified index page (by default 'index.html'), useful for Single Page Applications that utilise the HTML5 History API.
--no-history-api-fallback Disallows to proxy requests through a specified index page.
--host <value> Allows to specify a hostname to use.
--hot [value] Enables Hot Module Replacement.
--no-hot Disables Hot Module Replacement.
--ipc [value] Listen to a unix socket.
--live-reload Enables reload/refresh the page(s) when file changes are detected (enabled by default).
--no-live-reload Disables reload/refresh the page(s) when file changes are detected (enabled by default).
--open [value...] Allows to configure dev server to open the browser(s) and page(s) after server had been started (set it to true to open your default browser).
--no-open Does not open the default browser.
--open-target <value...> Opens specified page in browser.
--open-app-name <value...> Open specified browser.
--open-reset Clear all items provided in 'open' configuration. Allows to configure dev server to open the browser(s) and page(s) after server had been started (set it to true to open your default browser).
--open-target-reset Clear all items provided in 'open.target' configuration. Opens specified page in browser.
--open-app-name-reset Clear all items provided in 'open.app.name' configuration. Open specified browser.
--port <value> Allows to specify a port to use.
--server-type <value> Allows to set server and options (by default 'http').
--server-options-passphrase <value> Passphrase for a pfx file.
--server-options-request-cert Request for an SSL certificate.
--no-server-options-request-cert Does not request for an SSL certificate.
--server-options-ca <value...> Path to an SSL CA certificate or content of an SSL CA certificate.
--server-options-ca-reset Clear all items provided in 'server.options.ca' configuration. Path to an SSL CA certificate or content of an SSL CA certificate.
--server-options-cert <value...> Path to an SSL certificate or content of an SSL certificate.
--server-options-cert-reset Clear all items provided in 'server.options.cert' configuration. Path to an SSL certificate or content of an SSL certificate.
--server-options-crl <value...> Path to PEM formatted CRLs (Certificate Revocation Lists) or content of PEM formatted CRLs (Certificate Revocation Lists).
--server-options-crl-reset Clear all items provided in 'server.options.crl' configuration. Path to PEM formatted CRLs (Certificate Revocation Lists) or content of PEM formatted CRLs (Certificate Revocation Lists).
--server-options-key <value...> Path to an SSL key or content of an SSL key.
--server-options-key-reset Clear all items provided in 'server.options.key' configuration. Path to an SSL key or content of an SSL key.
--server-options-pfx <value...> Path to an SSL pfx file or content of an SSL pfx file.
--server-options-pfx-reset Clear all items provided in 'server.options.pfx' configuration. Path to an SSL pfx file or content of an SSL pfx file.
--static [value...] Allows to configure options for serving static files from directory (by default 'public' directory).
--no-static Disallows to configure options for serving static files from directory.
--static-directory <value...> Directory for static contents.
--static-public-path <value...> The static files will be available in the browser under this public path.
--static-serve-index Tells dev server to use serveIndex middleware when enabled.
--no-static-serve-index Does not tell dev server to use serveIndex middleware.
--static-watch Watches for files in static content directory.
--no-static-watch Does not watch for files in static content directory.
--static-reset Clear all items provided in 'static' configuration. Allows to configure options for serving static files from directory (by default 'public' directory).
--static-public-path-reset Clear all items provided in 'static.publicPath' configuration. The static files will be available in the browser under this public path.
--watch-files <value...> Allows to configure list of globs/directories/files to watch for file changes.
--watch-files-reset Clear all items provided in 'watchFiles' configuration. Allows to configure list of globs/directories/files to watch for file changes.
--no-web-socket-server Disallows to set web socket server and options.
--web-socket-server-type <value> Allows to set web socket server and options (by default 'ws').
Global options:
--color Enable colors on console.
--no-color Disable colors on console.
-v, --version Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands.
-h, --help [verbose] Display help for commands and options.
To see list of all supported commands and options run 'webpack --help=verbose'.
Webpack documentation: https://webpack.js.org/.
CLI documentation: https://webpack.js.org/api/cli/.
Made with ♥ by the webpack team.
```
> [!NOTE]
>
> _Detailed documentation for above options is available on this [link](https://webpack.js.org/configuration/dev-server/)._
### With NPM Scripts
NPM package.json scripts are a convenient and useful means to run locally installed
binaries without having to be concerned about their full paths. Simply define a
script as such:
```json
{
"scripts": {
"serve": "webpack serve"
}
}
```
And run the following in your terminal/console:
```console
npm run serve
```
NPM will automatically refer to the the binary in `node_modules` for you, and
execute the file or command.
### With the API
While it's recommended to run webpack-dev-server via the CLI, you may also choose to start a server via the API.
See the related [API documentation for `webpack-dev-server`](https://webpack.js.org/api/webpack-dev-server/).
### With TypeScript
If you use TypeScript in the webpack config, you'll need to properly type `devServer` property in order to avoid TS errors (e.g. `'devServer' does not exist in type 'Configuration'`). For that use either:
```ts
/// <reference path="node_modules/webpack-dev-server/types/lib/Server.d.ts"/>
import { type Configuration } from "webpack";
// Your logic
```
Or you can import the type from `webpack-dev-server`, i.e.
```ts
import { type Configuration } from "webpack";
import { type Configuration as DevServerConfiguration } from "webpack-dev-server";
const devServer: DevServerConfiguration = {};
const config: Configuration = { devServer };
// module.exports
export default config;
```
### The Result
Either method will start a server instance and begin listening for connections
from `localhost` on port `8080`.
webpack-dev-server is configured by default to support live-reload of files as
you edit your assets while the server is running.
See [**the documentation**][docs-url] for more use cases and options.
## Browser Support
While `webpack-dev-server` transpiles the client (browser) scripts to an ES5
state, the project only officially supports the _last two versions of major
browsers_. We simply don't have the resources to support every whacky
browser out there.
If you find a bug with an obscure / old browser, we would actively welcome a
Pull Request to resolve the bug.
## Support
We do our best to keep issues in the repository focused on bugs, features, and
needed modifications to the code for the module. Because of that, we ask users
with general support, "how-to", or "why isn't this working" questions to try one
of the other support channels that are available.
Your first-stop-shop for support for webpack-dev-server should be the excellent
[documentation][docs-url] for the module. If you see an opportunity for improvement
of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
pull request.
From there, we encourage users to visit the [webpack discussions][discussion-url] and
talk to the fine folks there. If your quest for answers comes up dry in chat,
head over to [StackOverflow][stack-url] and do a quick search or open a new
question. Remember; It's always much easier to answer questions that include your
`webpack.config.js` and relevant files!
If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
and someone should be able to reach out and lend a hand.
If you have discovered a :bug:, have a feature suggestion, or would like to see
a modification, please feel free to create an issue on Github. _Note: The issue
template isn't optional, so please be sure not to remove it, and please fill it
out completely._
## Contributing
We welcome your contributions! Please have a read of [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to get involved.
## Attribution
This project is heavily inspired by [peerigon/nof5](https://github.com/peerigon/nof5).
## License
#### [MIT](./LICENSE)
[npm]: https://img.shields.io/npm/v/webpack-dev-server.svg
[npm-url]: https://npmjs.com/package/webpack-dev-server
[node]: https://img.shields.io/node/v/webpack-dev-server.svg
[node-url]: https://nodejs.org
[tests]: https://github.com/webpack/webpack-dev-server/workflows/webpack-dev-server/badge.svg
[tests-url]: https://github.com/webpack/webpack-dev-server/actions?query=workflow%3Awebpack-dev-server
[cover]: https://codecov.io/gh/webpack/webpack-dev-server/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack/webpack-dev-server
[discussion]: https://img.shields.io/github/discussions/webpack/webpack
[discussion-url]: https://github.com/webpack/webpack/discussions
[docs-url]: https://webpack.js.org/configuration/dev-server/#devserver
[hash-url]: https://twitter.com/search?q=webpack
[middleware-url]: https://github.com/webpack/webpack-dev-middleware
[stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-server
[uglify-url]: https://github.com/webpack-contrib/uglifyjs-webpack-plugin
[wjo-url]: https://github.com/webpack/webpack.js.org
[downloads]: https://img.shields.io/npm/dm/webpack-dev-server.svg
[contributors-url]: https://github.com/webpack/webpack-dev-server/graphs/contributors
[contributors]: https://img.shields.io/github/contributors/webpack/webpack-dev-server.svg
+1294
View File
File diff suppressed because it is too large Load Diff
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env node
/* Based on webpack/bin/webpack.js */
/* eslint-disable no-console */
"use strict";
/**
* @param {string} command process to run
* @param {string[]} args command line arguments
* @returns {Promise<void>} promise
*/
const runCommand = (command, args) => {
const cp = require("node:child_process");
return new Promise((resolve, reject) => {
const executedCommand = cp.spawn(command, args, {
stdio: "inherit",
shell: true,
});
executedCommand.on("error", (error) => {
reject(error);
});
executedCommand.on("exit", (code) => {
if (code === 0) {
resolve();
} else {
reject();
}
});
});
};
/**
* @param {string} packageName name of the package
* @returns {boolean} is the package installed?
*/
const isInstalled = (packageName) => {
if (process.versions.pnp) {
return true;
}
const path = require("node:path");
const fs = require("graceful-fs");
let dir = __dirname;
do {
try {
if (
fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory()
) {
return true;
}
} catch {
// Nothing
}
} while (dir !== (dir = path.dirname(dir)));
// https://github.com/nodejs/node/blob/v18.9.1/lib/internal/modules/cjs/loader.js#L1274
// @ts-expect-error
for (const internalPath of require("node:module").globalPaths) {
try {
if (fs.statSync(path.join(internalPath, packageName)).isDirectory()) {
return true;
}
} catch {
// Nothing
}
}
return false;
};
/**
* @param {CliOption} cli options
* @returns {void}
*/
const runCli = (cli) => {
if (cli.preprocess) {
cli.preprocess();
}
const path = require("node:path");
const pkgPath = require.resolve(`${cli.package}/package.json`);
const pkg = require(pkgPath);
if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
(error) => {
console.error(error);
process.exitCode = 1;
},
);
} else {
require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
}
};
/**
* @typedef {object} CliOption
* @property {string} name display name
* @property {string} package npm package name
* @property {string} binName name of the executable file
* @property {boolean} installed currently installed?
* @property {string} url homepage
* @property {() => void} preprocess preprocessor
*/
/** @type {CliOption} */
const cli = {
name: "webpack-cli",
package: "webpack-cli",
binName: "webpack-cli",
installed: isInstalled("webpack-cli"),
url: "https://github.com/webpack/webpack-cli",
preprocess() {
process.argv.splice(2, 0, "serve");
},
};
if (!cli.installed) {
const path = require("node:path");
const fs = require("graceful-fs");
const readLine = require("node:readline");
const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`;
console.error(notify);
/**
* @type {string}
*/
let packageManager;
if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
packageManager = "yarn";
} else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
packageManager = "pnpm";
} else {
packageManager = "npm";
}
const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];
console.error(
`We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
" ",
)} ${cli.package}".`,
);
const question = "Do you want to install 'webpack-cli' (yes/no): ";
const questionInterface = readLine.createInterface({
input: process.stdin,
output: process.stderr,
});
// In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
// executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
// function is responsible for clearing the exit code if the user wishes to install webpack-cli.
process.exitCode = 1;
questionInterface.question(question, (answer) => {
questionInterface.close();
const normalizedAnswer = answer.toLowerCase().startsWith("y");
if (!normalizedAnswer) {
console.error(
"You need to install 'webpack-cli' to use webpack via CLI.\n" +
"You can also install the CLI manually.",
);
return;
}
process.exitCode = 0;
console.log(
`Installing '${
cli.package
}' (running '${packageManager} ${installOptions.join(" ")} ${
cli.package
}')...`,
);
runCommand(packageManager, [...installOptions, cli.package])
.then(() => {
runCli(cli);
})
.catch((error) => {
console.error(error);
process.exitCode = 1;
});
});
} else {
runCli(cli);
}
+59
View File
@@ -0,0 +1,59 @@
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import SockJS from "../modules/sockjs-client/index.js";
import { log } from "../utils/log.js";
/** @typedef {import("../index").EXPECTED_ANY} EXPECTED_ANY */
/**
* @implements {CommunicationClient}
*/
var SockJSClient = /*#__PURE__*/function () {
/**
* @param {string} url url
*/
function SockJSClient(url) {
_classCallCheck(this, SockJSClient);
// SockJS requires `http` and `https` protocols
this.sock = new SockJS(url.replace(/^ws:/i, "http:").replace(/^wss:/i, "https:"));
this.sock.onerror = function (error) {
log.error(error);
};
}
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
return _createClass(SockJSClient, [{
key: "onOpen",
value: function onOpen(fn) {
this.sock.onopen = fn;
}
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
}, {
key: "onClose",
value: function onClose(fn) {
this.sock.onclose = fn;
}
// call f with the message string as the first argument
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
}, {
key: "onMessage",
value: function onMessage(fn) {
this.sock.onmessage = function (err) {
fn(err.data);
};
}
}]);
}();
export { SockJSClient as default };
+57
View File
@@ -0,0 +1,57 @@
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { log } from "../utils/log.js";
/** @typedef {import("../index").EXPECTED_ANY} EXPECTED_ANY */
/**
* @implements {CommunicationClient}
*/
var WebSocketClient = /*#__PURE__*/function () {
/**
* @param {string} url url to connect
*/
function WebSocketClient(url) {
_classCallCheck(this, WebSocketClient);
this.client = new WebSocket(url);
this.client.onerror = function (error) {
log.error(error);
};
}
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
return _createClass(WebSocketClient, [{
key: "onOpen",
value: function onOpen(fn) {
this.client.onopen = fn;
}
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
}, {
key: "onClose",
value: function onClose(fn) {
this.client.onclose = fn;
}
// call f with the message string as the first argument
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
}, {
key: "onMessage",
value: function onMessage(fn) {
this.client.onmessage = function (err) {
fn(err.data);
};
}
}]);
}();
export { WebSocketClient as default };
+630
View File
@@ -0,0 +1,630 @@
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
/* global __resourceQuery, __webpack_hash__ */
// @ts-expect-error
import hotEmitter from "webpack/hot/emitter.js";
// @ts-expect-error
import webpackHotLog from "webpack/hot/log.js";
import { createOverlay, formatProblem } from "./overlay.js";
import { defineProgressElement, isProgressSupported } from "./progress.js";
import socket from "./socket.js";
import { log, setLogLevel } from "./utils/log.js";
import sendMessage from "./utils/sendMessage.js";
// eslint-disable-next-line jsdoc/no-restricted-syntax
/** @typedef {any} EXPECTED_ANY */
/**
* @typedef {object} RawOverlayOptions
* @property {string=} warnings warnings
* @property {string=} errors errors
* @property {string=} runtimeErrors runtime errors
* @property {string=} trustedTypesPolicyName trusted types policy name
*/
/**
* @typedef {object} OverlayOptions
* @property {(boolean | ((error: Error) => boolean))=} warnings warnings
* @property {(boolean | ((error: Error) => boolean))=} errors errors
* @property {(boolean | ((error: Error) => boolean))=} runtimeErrors runtime errors
* @property {string=} trustedTypesPolicyName trusted types policy name
*/
/** @typedef {false | true | "none" | "error" | "warn" | "info" | "log" | "verbose"} LogLevel */
/**
* @typedef {object} Options
* @property {boolean} hot true when hot enabled, otherwise false
* @property {boolean} liveReload true when live reload enabled, otherwise false
* @property {boolean} progress true when need to show progress, otherwise false
* @property {boolean | OverlayOptions} overlay overlay options
* @property {LogLevel=} logging logging level
* @property {number=} reconnect count of allowed reconnection
*/
/**
* @typedef {object} Status
* @property {boolean} isUnloading true when unloaded, otherwise false
* @property {string} currentHash current hash
* @property {string=} previousHash previous hash
*/
/**
* @param {boolean | RawOverlayOptions | OverlayOptions} overlayOptions overlay options
*/
var decodeOverlayOptions = function decodeOverlayOptions(overlayOptions) {
if (_typeof(overlayOptions) === "object") {
var requiredOptions = ["warnings", "errors", "runtimeErrors"];
for (var i = 0; i < requiredOptions.length; i++) {
var property = /** @type {keyof Omit<RawOverlayOptions, "trustedTypesPolicyName">} */
requiredOptions[i];
if (typeof overlayOptions[property] === "string") {
var overlayFilterFunctionString = decodeURIComponent(overlayOptions[property]);
/** @type {OverlayOptions} */
overlayOptions[property] = /** @type {(error: Error) => boolean} */
// eslint-disable-next-line no-new-func
new Function("message", "var callback = ".concat(overlayFilterFunctionString, "\n return callback(message)"));
}
}
}
};
/**
* @type {Status}
*/
var status = {
isUnloading: false,
currentHash: __webpack_hash__
};
/**
* @returns {string} current script source
*/
var getCurrentScriptSource = function getCurrentScriptSource() {
// `document.currentScript` is the most accurate way to find the current script,
// but is not supported in all browsers.
if (document.currentScript) {
return /** @type {string} */document.currentScript.getAttribute("src");
}
// Fallback to getting all scripts running in the document.
var scriptElements = document.scripts || [];
var scriptElementsWithSrc = Array.prototype.filter.call(scriptElements, function (element) {
return element.getAttribute("src");
});
if (scriptElementsWithSrc.length > 0) {
var currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1];
return currentScript.getAttribute("src");
}
// Fail as there was no script to use.
throw new Error("[webpack-dev-server] Failed to get current script source.");
};
/** @typedef {{ hot?: string, ["live-reload"]?: string, progress?: string, reconnect?: string, logging?: LogLevel, overlay?: string, fromCurrentScript?: boolean }} AdditionalParsedURL */
/** @typedef {Partial<URL> & AdditionalParsedURL} ParsedURL */
/**
* @param {string} resourceQuery resource query
* @returns {ParsedURL} parsed URL
*/
var parseURL = function parseURL(resourceQuery) {
/** @type {ParsedURL} */
var result = {};
if (typeof resourceQuery === "string" && resourceQuery !== "") {
var searchParams = resourceQuery.slice(1).split("&");
for (var i = 0; i < searchParams.length; i++) {
var pair = searchParams[i].split("=");
/** @type {EXPECTED_ANY} */
result[pair[0]] = decodeURIComponent(pair[1]);
}
} else {
// Else, get the url from the <script> this file was called with.
var scriptSource = getCurrentScriptSource();
var scriptSourceURL;
try {
// The placeholder `baseURL` with `window.location.href`,
// is to allow parsing of path-relative or protocol-relative URLs,
// and will have no effect if `scriptSource` is a fully valid URL.
scriptSourceURL = new URL(scriptSource, self.location.href);
} catch (_err) {
// URL parsing failed, do nothing.
// We will still proceed to see if we can recover using `resourceQuery`
}
if (scriptSourceURL) {
result = scriptSourceURL;
result.fromCurrentScript = true;
}
}
return result;
};
var parsedResourceQuery = parseURL(__resourceQuery);
/** @typedef {{ ["Hot Module Replacement"]: boolean, ["Live Reloading"]: boolean, Progress: boolean, Overlay: boolean }} Features */
/** @type {Features} */
var enabledFeatures = {
"Hot Module Replacement": false,
"Live Reloading": false,
Progress: false,
Overlay: false
};
/** @type {Options} */
var options = {
hot: false,
liveReload: false,
progress: false,
overlay: false
};
if (parsedResourceQuery.hot === "true") {
options.hot = true;
enabledFeatures["Hot Module Replacement"] = true;
}
if (parsedResourceQuery["live-reload"] === "true") {
options.liveReload = true;
enabledFeatures["Live Reloading"] = true;
}
if (parsedResourceQuery.progress === "true") {
options.progress = true;
enabledFeatures.Progress = true;
}
if (parsedResourceQuery.overlay) {
try {
options.overlay = JSON.parse(parsedResourceQuery.overlay);
} catch (err) {
log.error("Error parsing overlay options from resource query:", err);
}
// Fill in default "true" params for partially-specified objects.
if (_typeof(options.overlay) === "object") {
options.overlay = _objectSpread({
errors: true,
warnings: true,
runtimeErrors: true
}, options.overlay);
decodeOverlayOptions(options.overlay);
}
enabledFeatures.Overlay = options.overlay !== false;
}
if (parsedResourceQuery.logging) {
options.logging = parsedResourceQuery.logging;
}
if (typeof parsedResourceQuery.reconnect !== "undefined") {
options.reconnect = Number(parsedResourceQuery.reconnect);
}
/**
* @param {false | true | "none" | "error" | "warn" | "info" | "log" | "verbose"} level level
*/
var setAllLogLevel = function setAllLogLevel(level) {
// This is needed because the HMR logger operate separately from dev server logger
webpackHotLog.setLogLevel(level === "verbose" || level === "log" ? "info" : level);
setLogLevel(level);
};
if (options.logging) {
setAllLogLevel(options.logging);
}
/**
* @param {Features} features features
*/
var logEnabledFeatures = function logEnabledFeatures(features) {
var listEnabledFeatures = Object.keys(features);
if (!features || listEnabledFeatures.length === 0) {
return;
}
var logString = "Server started:";
// Server started: Hot Module Replacement enabled, Live Reloading enabled, Overlay disabled.
for (var i = 0; i < listEnabledFeatures.length; i++) {
var key = /** @type {keyof Features} */listEnabledFeatures[i];
logString += " ".concat(key, " ").concat(features[key] ? "enabled" : "disabled", ",");
}
// replace last comma with a period
logString = logString.slice(0, -1).concat(".");
log.info(logString);
};
logEnabledFeatures(enabledFeatures);
self.addEventListener("beforeunload", function () {
status.isUnloading = true;
});
var overlay = typeof window !== "undefined" ? createOverlay(_typeof(options.overlay) === "object" ? {
trustedTypesPolicyName: options.overlay.trustedTypesPolicyName,
catchRuntimeError: options.overlay.runtimeErrors
} : {
trustedTypesPolicyName: false,
catchRuntimeError: options.overlay
}) : {
send: function send() {}
};
/**
* @param {Options} options options
* @param {Status} currentStatus current status
*/
var reloadApp = function reloadApp(_ref, currentStatus) {
var hot = _ref.hot,
liveReload = _ref.liveReload;
if (currentStatus.isUnloading) {
return;
}
var currentHash = currentStatus.currentHash,
previousHash = currentStatus.previousHash;
var isInitial = currentHash.indexOf(/** @type {string} */previousHash) >= 0;
if (isInitial) {
return;
}
/**
* @param {Window} rootWindow root window
* @param {number} intervalId interval id
*/
function applyReload(rootWindow, intervalId) {
clearInterval(intervalId);
log.info("App updated. Reloading...");
rootWindow.location.reload();
}
var search = self.location.search.toLowerCase();
var allowToHot = search.indexOf("webpack-dev-server-hot=false") === -1;
var allowToLiveReload = search.indexOf("webpack-dev-server-live-reload=false") === -1;
if (hot && allowToHot) {
log.info("App hot update...");
if (typeof EventTarget !== "undefined" && hotEmitter instanceof EventTarget) {
var event = new CustomEvent("webpackHotUpdate", {
detail: {
currentHash: currentStatus.currentHash
},
bubbles: true,
cancelable: false
});
hotEmitter.dispatchEvent(event);
} else {
hotEmitter.emit("webpackHotUpdate", currentStatus.currentHash);
}
if (typeof self !== "undefined" && self.window) {
// broadcast update to window
self.postMessage("webpackHotUpdate".concat(currentStatus.currentHash), "*");
}
}
// allow refreshing the page only if liveReload isn't disabled
else if (liveReload && allowToLiveReload) {
/** @type {Window} */
var rootWindow = self;
// use parent window for reload (in case we're in an iframe with no valid src)
var intervalId = self.setInterval(function () {
if (rootWindow.location.protocol !== "about:") {
// reload immediately if protocol is valid
applyReload(rootWindow, intervalId);
} else {
rootWindow = rootWindow.parent;
if (rootWindow.parent === rootWindow) {
// if parent equals current window we've reached the root which would continue forever, so trigger a reload anyways
applyReload(rootWindow, intervalId);
}
}
});
}
};
var ansiRegex = new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|"), "g");
/**
* Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string.
* Adapted from code originally released by Sindre Sorhus
* Licensed the MIT License
* @param {string} string string
* @returns {string} string without ansi
*/
var stripAnsi = function stripAnsi(string) {
if (typeof string !== "string") {
throw new TypeError("Expected a `string`, got `".concat(_typeof(string), "`"));
}
return string.replace(ansiRegex, "");
};
var onSocketMessage = {
hot: function hot() {
if (parsedResourceQuery.hot === "false") {
return;
}
options.hot = true;
},
liveReload: function liveReload() {
if (parsedResourceQuery["live-reload"] === "false") {
return;
}
options.liveReload = true;
},
invalid: function invalid() {
log.info("App updated. Recompiling...");
// Fixes #1042. overlay doesn't clear if errors are fixed but warnings remain.
if (options.overlay) {
overlay.send({
type: "DISMISS"
});
}
sendMessage("Invalid");
},
/**
* @param {string} hash hash
*/
hash: function hash(_hash) {
status.previousHash = status.currentHash;
status.currentHash = _hash;
},
logging: setAllLogLevel,
/**
* @param {boolean} value overlay value
*/
overlay: function overlay(value) {
if (typeof document === "undefined") {
return;
}
options.overlay = value;
decodeOverlayOptions(options.overlay);
},
/**
* @param {number} value reconnect value
*/
reconnect: function reconnect(value) {
if (parsedResourceQuery.reconnect === "false") {
return;
}
options.reconnect = value;
},
/**
* @param {boolean} value progress value
*/
progress: function progress(value) {
options.progress = value;
},
/**
* @param {{ pluginName?: string, percent: string, msg: string }} data date with progress
*/
"progress-update": function progressUpdate(data) {
if (options.progress) {
log.info("".concat(data.pluginName ? "[".concat(data.pluginName, "] ") : "").concat(data.percent, "% - ").concat(data.msg, "."));
}
if (isProgressSupported() && typeof options.progress === "string") {
var progress = document.querySelector("wds-progress");
if (!progress) {
defineProgressElement();
progress = document.createElement("wds-progress");
document.body.appendChild(progress);
}
progress.setAttribute("progress", data.percent);
progress.setAttribute("type", options.progress);
}
sendMessage("Progress", data);
},
"still-ok": function stillOk() {
log.info("Nothing changed.");
if (options.overlay) {
overlay.send({
type: "DISMISS"
});
}
sendMessage("StillOk");
},
ok: function ok() {
sendMessage("Ok");
if (options.overlay) {
overlay.send({
type: "DISMISS"
});
}
reloadApp(options, status);
},
/**
* @param {string} file changed file
*/
"static-changed": function staticChanged(file) {
log.info("".concat(file ? "\"".concat(file, "\"") : "Content", " from static directory was changed. Reloading..."));
self.location.reload();
},
/**
* @param {Error[]} warnings warnings
* @param {{ preventReloading: boolean }=} params extra params
*/
warnings: function warnings(_warnings, params) {
log.warn("Warnings while compiling.");
var printableWarnings = _warnings.map(function (error) {
var _formatProblem = formatProblem("warning", error),
header = _formatProblem.header,
body = _formatProblem.body;
return "".concat(header, "\n").concat(stripAnsi(body));
});
sendMessage("Warnings", printableWarnings);
for (var i = 0; i < printableWarnings.length; i++) {
log.warn(printableWarnings[i]);
}
var overlayWarningsSetting = typeof options.overlay === "boolean" ? options.overlay : options.overlay && options.overlay.warnings;
if (overlayWarningsSetting) {
var warningsToDisplay = typeof overlayWarningsSetting === "function" ? _warnings.filter(overlayWarningsSetting) : _warnings;
if (warningsToDisplay.length) {
overlay.send({
type: "BUILD_ERROR",
level: "warning",
messages: _warnings
});
}
}
if (params && params.preventReloading) {
return;
}
reloadApp(options, status);
},
/**
* @param {Error[]} errors errors
*/
errors: function errors(_errors) {
log.error("Errors while compiling. Reload prevented.");
var printableErrors = _errors.map(function (error) {
var _formatProblem2 = formatProblem("error", error),
header = _formatProblem2.header,
body = _formatProblem2.body;
return "".concat(header, "\n").concat(stripAnsi(body));
});
sendMessage("Errors", printableErrors);
for (var i = 0; i < printableErrors.length; i++) {
log.error(printableErrors[i]);
}
var overlayErrorsSettings = typeof options.overlay === "boolean" ? options.overlay : options.overlay && options.overlay.errors;
if (overlayErrorsSettings) {
var errorsToDisplay = typeof overlayErrorsSettings === "function" ? _errors.filter(overlayErrorsSettings) : _errors;
if (errorsToDisplay.length) {
overlay.send({
type: "BUILD_ERROR",
level: "error",
messages: _errors
});
}
}
},
/**
* @param {Error} error error
*/
error: function error(_error) {
log.error(_error);
},
close: function close() {
log.info("Disconnected!");
if (options.overlay) {
overlay.send({
type: "DISMISS"
});
}
sendMessage("Close");
}
};
/**
* @param {{ protocol?: string, auth?: string, hostname?: string, port?: string, pathname?: string, search?: string, hash?: string, slashes?: boolean }} objURL object URL
* @returns {string} formatted url
*/
var formatURL = function formatURL(objURL) {
var protocol = objURL.protocol || "";
if (protocol && protocol.slice(-1) !== ":") {
protocol += ":";
}
var auth = objURL.auth || "";
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ":");
auth += "@";
}
var host = "";
if (objURL.hostname) {
host = auth + (objURL.hostname.indexOf(":") === -1 ? objURL.hostname : "[".concat(objURL.hostname, "]"));
if (objURL.port) {
host += ":".concat(objURL.port);
}
}
var pathname = objURL.pathname || "";
if (objURL.slashes) {
host = "//".concat(host || "");
if (pathname && pathname.charAt(0) !== "/") {
pathname = "/".concat(pathname);
}
} else if (!host) {
host = "";
}
var search = objURL.search || "";
if (search && search.charAt(0) !== "?") {
search = "?".concat(search);
}
var hash = objURL.hash || "";
if (hash && hash.charAt(0) !== "#") {
hash = "#".concat(hash);
}
pathname = pathname.replace(/[?#]/g,
/**
* @param {string} match matched string
* @returns {string} encoded URI component
*/
function (match) {
return encodeURIComponent(match);
});
search = search.replace("#", "%23");
return "".concat(protocol).concat(host).concat(pathname).concat(search).concat(hash);
};
/**
* @param {ParsedURL} parsedURL parsed URL
* @returns {string} socket URL
*/
var createSocketURL = function createSocketURL(parsedURL) {
var hostname = parsedURL.hostname;
// Node.js module parses it as `::`
// `new URL(urlString, [baseURLString])` parses it as '[::]'
var isInAddrAny = hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]";
// why do we need this check?
// hostname n/a for file protocol (example, when using electron, ionic)
// see: https://github.com/webpack/webpack-dev-server/pull/384
if (isInAddrAny && self.location.hostname && self.location.protocol.indexOf("http") === 0) {
hostname = self.location.hostname;
}
var socketURLProtocol = parsedURL.protocol || self.location.protocol;
// When https is used in the app, secure web sockets are always necessary because the browser doesn't accept non-secure web sockets.
if (socketURLProtocol === "auto:" || hostname && isInAddrAny && self.location.protocol === "https:") {
socketURLProtocol = self.location.protocol;
}
socketURLProtocol = socketURLProtocol.replace(/^(?:http|.+-extension|file)/i, "ws");
var socketURLAuth = "";
// `new URL(urlString, [baseURLstring])` doesn't have `auth` property
// Parse authentication credentials in case we need them
if (parsedURL.username) {
socketURLAuth = parsedURL.username;
// Since HTTP basic authentication does not allow empty username,
// we only include password if the username is not empty.
if (parsedURL.password) {
// Result: <username>:<password>
socketURLAuth = socketURLAuth.concat(":", parsedURL.password);
}
}
// In case the host is a raw IPv6 address, it can be enclosed in
// the brackets as the brackets are needed in the final URL string.
// Need to remove those as url.format blindly adds its own set of brackets
// if the host string contains colons. That would lead to non-working
// double brackets (e.g. [[::]]) host
//
// All of these web socket url params are optionally passed in through resourceQuery,
// so we need to fall back to the default if they are not provided
var socketURLHostname = (hostname || self.location.hostname || "localhost").replace(/^\[(.*)\]$/, "$1");
var socketURLPort = parsedURL.port;
if (!socketURLPort || socketURLPort === "0") {
socketURLPort = self.location.port;
}
// If path is provided it'll be passed in via the resourceQuery as a
// query param so it has to be parsed out of the querystring in order for the
// client to open the socket to the correct location.
var socketURLPathname = "/ws";
if (parsedURL.pathname && !parsedURL.fromCurrentScript) {
socketURLPathname = parsedURL.pathname;
}
return formatURL({
protocol: socketURLProtocol,
auth: socketURLAuth,
hostname: socketURLHostname,
port: socketURLPort,
pathname: socketURLPathname,
slashes: true
});
};
var socketURL = createSocketURL(parsedResourceQuery);
socket(socketURL, onSocketMessage, options.reconnect);
export { createSocketURL, getCurrentScriptSource, parseURL };
+831
View File
@@ -0,0 +1,831 @@
/******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./client-src/modules/logger/tapable.js":
/*!**********************************************!*\
!*** ./client-src/modules/logger/tapable.js ***!
\**********************************************/
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ SyncBailHook: function() { return /* binding */ SyncBailHook; }
/* harmony export */ });
/**
* @returns {SyncBailHook} mocked sync bail hook
* @constructor
*/
function SyncBailHook() {
return {
call: function call() {}
};
}
/**
* Client stub for tapable SyncBailHook
*/
/***/ }),
/***/ "./node_modules/webpack/lib/logging/Logger.js":
/*!****************************************************!*\
!*** ./node_modules/webpack/lib/logging/Logger.js ***!
\****************************************************/
/***/ (function(module) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && "symbol" == typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }).iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && o.constructor === (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && o !== (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }).prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function _toConsumableArray(r) {
return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return _arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
}
}
function _iterableToArray(r) {
if ("undefined" != typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && null != r[(typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }).iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _arrayWithoutHoles(r) {
if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _arrayLikeToArray(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
return n;
}
function _classCallCheck(a, n) {
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(e, r) {
for (var t = 0; t < r.length; t++) {
var o = r[t];
o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
}
}
function _createClass(e, r, t) {
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
writable: !1
}), e;
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
function _toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[(typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }).toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
var LogType = Object.freeze({
error: (/** @type {"error"} */"error"),
// message, c style arguments
warn: (/** @type {"warn"} */"warn"),
// message, c style arguments
info: (/** @type {"info"} */"info"),
// message, c style arguments
log: (/** @type {"log"} */"log"),
// message, c style arguments
debug: (/** @type {"debug"} */"debug"),
// message, c style arguments
trace: (/** @type {"trace"} */"trace"),
// no arguments
group: (/** @type {"group"} */"group"),
// [label]
groupCollapsed: (/** @type {"groupCollapsed"} */"groupCollapsed"),
// [label]
groupEnd: (/** @type {"groupEnd"} */"groupEnd"),
// [label]
profile: (/** @type {"profile"} */"profile"),
// [profileName]
profileEnd: (/** @type {"profileEnd"} */"profileEnd"),
// [profileName]
time: (/** @type {"time"} */"time"),
// name, time as [seconds, nanoseconds]
clear: (/** @type {"clear"} */"clear"),
// no arguments
status: (/** @type {"status"} */"status") // message, arguments
});
module.exports.LogType = LogType;
/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */
var LOG_SYMBOL = (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; })("webpack logger raw log method");
var TIMERS_SYMBOL = (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; })("webpack logger times");
var TIMERS_AGGREGATES_SYMBOL = (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; })("webpack logger aggregated times");
/** @typedef {EXPECTED_ANY[]} Args */
var WebpackLogger = /*#__PURE__*/function () {
/**
* @param {(type: LogTypeEnum, args?: Args) => void} log log function
* @param {(name: string | (() => string)) => WebpackLogger} getChildLogger function to create child logger
*/
function WebpackLogger(log, getChildLogger) {
_classCallCheck(this, WebpackLogger);
this[LOG_SYMBOL] = log;
this.getChildLogger = getChildLogger;
}
/**
* @param {Args} args args
*/
return _createClass(WebpackLogger, [{
key: "error",
value: function error() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
this[LOG_SYMBOL](LogType.error, args);
}
/**
* @param {Args} args args
*/
}, {
key: "warn",
value: function warn() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
this[LOG_SYMBOL](LogType.warn, args);
}
/**
* @param {Args} args args
*/
}, {
key: "info",
value: function info() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
this[LOG_SYMBOL](LogType.info, args);
}
/**
* @param {Args} args args
*/
}, {
key: "log",
value: function log() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
this[LOG_SYMBOL](LogType.log, args);
}
/**
* @param {Args} args args
*/
}, {
key: "debug",
value: function debug() {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
this[LOG_SYMBOL](LogType.debug, args);
}
/**
* @param {EXPECTED_ANY} assertion assertion
* @param {Args} args args
*/
}, {
key: "assert",
value: function assert(assertion) {
if (!assertion) {
for (var _len6 = arguments.length, args = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
args[_key6 - 1] = arguments[_key6];
}
this[LOG_SYMBOL](LogType.error, args);
}
}
}, {
key: "trace",
value: function trace() {
this[LOG_SYMBOL](LogType.trace, ["Trace"]);
}
}, {
key: "clear",
value: function clear() {
this[LOG_SYMBOL](LogType.clear);
}
/**
* @param {Args} args args
*/
}, {
key: "status",
value: function status() {
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
args[_key7] = arguments[_key7];
}
this[LOG_SYMBOL](LogType.status, args);
}
/**
* @param {Args} args args
*/
}, {
key: "group",
value: function group() {
for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
args[_key8] = arguments[_key8];
}
this[LOG_SYMBOL](LogType.group, args);
}
/**
* @param {Args} args args
*/
}, {
key: "groupCollapsed",
value: function groupCollapsed() {
for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
args[_key9] = arguments[_key9];
}
this[LOG_SYMBOL](LogType.groupCollapsed, args);
}
}, {
key: "groupEnd",
value: function groupEnd() {
this[LOG_SYMBOL](LogType.groupEnd);
}
/**
* @param {string=} label label
*/
}, {
key: "profile",
value: function profile(label) {
this[LOG_SYMBOL](LogType.profile, [label]);
}
/**
* @param {string=} label label
*/
}, {
key: "profileEnd",
value: function profileEnd(label) {
this[LOG_SYMBOL](LogType.profileEnd, [label]);
}
/**
* @param {string} label label
*/
}, {
key: "time",
value: function time(label) {
/** @type {Map<string | undefined, [number, number]>} */
this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map();
this[TIMERS_SYMBOL].set(label, process.hrtime());
}
/**
* @param {string=} label label
*/
}, {
key: "timeLog",
value: function timeLog(label) {
var prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label);
if (!prev) {
throw new Error("No such label '".concat(label, "' for WebpackLogger.timeLog()"));
}
var time = process.hrtime(prev);
this[LOG_SYMBOL](LogType.time, [label].concat(_toConsumableArray(time)));
}
/**
* @param {string=} label label
*/
}, {
key: "timeEnd",
value: function timeEnd(label) {
var prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label);
if (!prev) {
throw new Error("No such label '".concat(label, "' for WebpackLogger.timeEnd()"));
}
var time = process.hrtime(prev);
/** @type {Map<string | undefined, [number, number]>} */
this[TIMERS_SYMBOL].delete(label);
this[LOG_SYMBOL](LogType.time, [label].concat(_toConsumableArray(time)));
}
/**
* @param {string=} label label
*/
}, {
key: "timeAggregate",
value: function timeAggregate(label) {
var prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label);
if (!prev) {
throw new Error("No such label '".concat(label, "' for WebpackLogger.timeAggregate()"));
}
var time = process.hrtime(prev);
/** @type {Map<string | undefined, [number, number]>} */
this[TIMERS_SYMBOL].delete(label);
/** @type {Map<string | undefined, [number, number]>} */
this[TIMERS_AGGREGATES_SYMBOL] = this[TIMERS_AGGREGATES_SYMBOL] || new Map();
var current = this[TIMERS_AGGREGATES_SYMBOL].get(label);
if (current !== undefined) {
if (time[1] + current[1] > 1e9) {
time[0] += current[0] + 1;
time[1] = time[1] - 1e9 + current[1];
} else {
time[0] += current[0];
time[1] += current[1];
}
}
this[TIMERS_AGGREGATES_SYMBOL].set(label, time);
}
/**
* @param {string=} label label
*/
}, {
key: "timeAggregateEnd",
value: function timeAggregateEnd(label) {
if (this[TIMERS_AGGREGATES_SYMBOL] === undefined) return;
var time = this[TIMERS_AGGREGATES_SYMBOL].get(label);
if (time === undefined) return;
this[TIMERS_AGGREGATES_SYMBOL].delete(label);
this[LOG_SYMBOL](LogType.time, [label].concat(_toConsumableArray(time)));
}
}]);
}();
module.exports.Logger = WebpackLogger;
/***/ }),
/***/ "./node_modules/webpack/lib/logging/createConsoleLogger.js":
/*!*****************************************************************!*\
!*** ./node_modules/webpack/lib/logging/createConsoleLogger.js ***!
\*****************************************************************/
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
function _slicedToArray(r, e) {
return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && r[(typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }).iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
function _arrayWithHoles(r) {
if (Array.isArray(r)) return r;
}
function _toConsumableArray(r) {
return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return _arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
}
}
function _iterableToArray(r) {
if ("undefined" != typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && null != r[(typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }).iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _arrayWithoutHoles(r) {
if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _arrayLikeToArray(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
return n;
}
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && "symbol" == typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }).iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && o.constructor === (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }) && o !== (typeof Symbol !== "undefined" ? Symbol : function (i) { return i; }).prototype ? "symbol" : typeof o;
}, _typeof(o);
}
var _require = __webpack_require__(/*! ./Logger */ "./node_modules/webpack/lib/logging/Logger.js"),
LogType = _require.LogType;
/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */
/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */
/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */
/** @typedef {import("./Logger").Args} Args */
/** @typedef {(item: string) => boolean} FilterFunction */
/** @typedef {(value: string, type: LogTypeEnum, args?: Args) => void} LoggingFunction */
/**
* @typedef {object} LoggerConsole
* @property {() => void} clear
* @property {() => void} trace
* @property {(...args: Args) => void} info
* @property {(...args: Args) => void} log
* @property {(...args: Args) => void} warn
* @property {(...args: Args) => void} error
* @property {(...args: Args) => void=} debug
* @property {(...args: Args) => void=} group
* @property {(...args: Args) => void=} groupCollapsed
* @property {(...args: Args) => void=} groupEnd
* @property {(...args: Args) => void=} status
* @property {(...args: Args) => void=} profile
* @property {(...args: Args) => void=} profileEnd
* @property {(...args: Args) => void=} logTime
*/
/**
* @typedef {object} LoggerOptions
* @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel
* @property {FilterTypes|boolean} debug filter for debug logging
* @property {LoggerConsole} console the console to log to
*/
/**
* @param {FilterItemTypes} item an input item
* @returns {FilterFunction | undefined} filter function
*/
var filterToFunction = function filterToFunction(item) {
if (typeof item === "string") {
var regExp = new RegExp("[\\\\/]".concat(item.replace(/[-[\]{}()*+?.\\^$|]/g, "\\$&"), "([\\\\/]|$|!|\\?)"));
return function (ident) {
return regExp.test(ident);
};
}
if (item && _typeof(item) === "object" && typeof item.test === "function") {
return function (ident) {
return item.test(ident);
};
}
if (typeof item === "function") {
return item;
}
if (typeof item === "boolean") {
return function () {
return item;
};
}
};
/**
* @enum {number}
*/
var LogLevel = {
none: 6,
false: 6,
error: 5,
warn: 4,
info: 3,
log: 2,
true: 2,
verbose: 1
};
/**
* @param {LoggerOptions} options options object
* @returns {LoggingFunction} logging function
*/
module.exports = function (_ref) {
var _ref$level = _ref.level,
level = _ref$level === void 0 ? "info" : _ref$level,
_ref$debug = _ref.debug,
debug = _ref$debug === void 0 ? false : _ref$debug,
console = _ref.console;
var debugFilters = /** @type {FilterFunction[]} */
typeof debug === "boolean" ? [function () {
return debug;
}] : /** @type {FilterItemTypes[]} */_toConsumableArray(Array.isArray(debug) ? debug : [debug]).map(filterToFunction);
var loglevel = LogLevel["".concat(level)] || 0;
/**
* @param {string} name name of the logger
* @param {LogTypeEnum} type type of the log entry
* @param {Args=} args arguments of the log entry
* @returns {void}
*/
var logger = function logger(name, type, args) {
var labeledArgs = function labeledArgs() {
if (Array.isArray(args)) {
if (args.length > 0 && typeof args[0] === "string") {
return ["[".concat(name, "] ").concat(args[0])].concat(_toConsumableArray(args.slice(1)));
}
return ["[".concat(name, "]")].concat(_toConsumableArray(args));
}
return [];
};
var debug = debugFilters.some(function (f) {
return f(name);
});
switch (type) {
case LogType.debug:
if (!debug) return;
if (typeof console.debug === "function") {
console.debug.apply(console, _toConsumableArray(labeledArgs()));
} else {
console.log.apply(console, _toConsumableArray(labeledArgs()));
}
break;
case LogType.log:
if (!debug && loglevel > LogLevel.log) return;
console.log.apply(console, _toConsumableArray(labeledArgs()));
break;
case LogType.info:
if (!debug && loglevel > LogLevel.info) return;
console.info.apply(console, _toConsumableArray(labeledArgs()));
break;
case LogType.warn:
if (!debug && loglevel > LogLevel.warn) return;
console.warn.apply(console, _toConsumableArray(labeledArgs()));
break;
case LogType.error:
if (!debug && loglevel > LogLevel.error) return;
console.error.apply(console, _toConsumableArray(labeledArgs()));
break;
case LogType.trace:
if (!debug) return;
console.trace();
break;
case LogType.groupCollapsed:
if (!debug && loglevel > LogLevel.log) return;
if (!debug && loglevel > LogLevel.verbose) {
if (typeof console.groupCollapsed === "function") {
console.groupCollapsed.apply(console, _toConsumableArray(labeledArgs()));
} else {
console.log.apply(console, _toConsumableArray(labeledArgs()));
}
break;
}
// falls through
case LogType.group:
if (!debug && loglevel > LogLevel.log) return;
if (typeof console.group === "function") {
console.group.apply(console, _toConsumableArray(labeledArgs()));
} else {
console.log.apply(console, _toConsumableArray(labeledArgs()));
}
break;
case LogType.groupEnd:
if (!debug && loglevel > LogLevel.log) return;
if (typeof console.groupEnd === "function") {
console.groupEnd();
}
break;
case LogType.time:
{
if (!debug && loglevel > LogLevel.log) return;
var _args = _slicedToArray(/** @type {[string, number, number]} */
args, 3),
label = _args[0],
start = _args[1],
end = _args[2];
var ms = start * 1000 + end / 1000000;
var msg = "[".concat(name, "] ").concat(label, ": ").concat(ms, " ms");
if (typeof console.logTime === "function") {
console.logTime(msg);
} else {
console.log(msg);
}
break;
}
case LogType.profile:
if (typeof console.profile === "function") {
console.profile.apply(console, _toConsumableArray(labeledArgs()));
}
break;
case LogType.profileEnd:
if (typeof console.profileEnd === "function") {
console.profileEnd.apply(console, _toConsumableArray(labeledArgs()));
}
break;
case LogType.clear:
if (!debug && loglevel > LogLevel.log) return;
if (typeof console.clear === "function") {
console.clear();
}
break;
case LogType.status:
if (!debug && loglevel > LogLevel.info) return;
if (typeof console.status === "function") {
if (!args || args.length === 0) {
console.status();
} else {
console.status.apply(console, _toConsumableArray(labeledArgs()));
}
} else if (args && args.length !== 0) {
console.info.apply(console, _toConsumableArray(labeledArgs()));
}
break;
default:
throw new Error("Unexpected LogType ".concat(type));
}
};
return logger;
};
/***/ }),
/***/ "./node_modules/webpack/lib/logging/runtime.js":
/*!*****************************************************!*\
!*** ./node_modules/webpack/lib/logging/runtime.js ***!
\*****************************************************/
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
var _require = __webpack_require__(/*! tapable */ "./client-src/modules/logger/tapable.js"),
SyncBailHook = _require.SyncBailHook;
var _require2 = __webpack_require__(/*! ./Logger */ "./node_modules/webpack/lib/logging/Logger.js"),
Logger = _require2.Logger;
var createConsoleLogger = __webpack_require__(/*! ./createConsoleLogger */ "./node_modules/webpack/lib/logging/createConsoleLogger.js");
/** @type {createConsoleLogger.LoggerOptions} */
var currentDefaultLoggerOptions = {
level: "info",
debug: false,
console: console
};
var currentDefaultLogger = createConsoleLogger(currentDefaultLoggerOptions);
/**
* @param {createConsoleLogger.LoggerOptions} options new options, merge with old options
* @returns {void}
*/
module.exports.configureDefaultLogger = function (options) {
_extends(currentDefaultLoggerOptions, options);
currentDefaultLogger = createConsoleLogger(currentDefaultLoggerOptions);
};
/**
* @param {string} name name of the logger
* @returns {Logger} a logger
*/
module.exports.getLogger = function (name) {
return new Logger(function (type, args) {
if (module.exports.hooks.log.call(name, type, args) === undefined) {
currentDefaultLogger(name, type, args);
}
}, function (childName) {
return module.exports.getLogger("".concat(name, "/").concat(childName));
});
};
module.exports.hooks = {
log: new SyncBailHook(["origin", "type", "args"])
};
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it needs to be isolated against other modules in the chunk.
!function() {
/*!********************************************!*\
!*** ./client-src/modules/logger/index.js ***!
\********************************************/
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": function() { return /* reexport default export from named module */ webpack_lib_logging_runtime_js__WEBPACK_IMPORTED_MODULE_0__; }
/* harmony export */ });
/* harmony import */ var webpack_lib_logging_runtime_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webpack/lib/logging/runtime.js */ "./node_modules/webpack/lib/logging/runtime.js");
// @ts-expect-error
}();
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__) __webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if(__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });
/******/ })()
;
File diff suppressed because it is too large Load Diff
+665
View File
@@ -0,0 +1,665 @@
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
// The error overlay is inspired (and mostly copied) from Create React App (https://github.com/facebookincubator/create-react-app)
// They, in turn, got inspired by webpack-hot-middleware (https://github.com/glenjamin/webpack-hot-middleware).
import ansiHTML from "ansi-html-community";
/** @typedef {import("./index").EXPECTED_ANY} EXPECTED_ANY */
/**
* @type {(input: string, position: number) => number | undefined}
*/
// @ts-expect-error
var getCodePoint = String.prototype.codePointAt ?
// @ts-expect-error
function (input, position) {
return input.codePointAt(position);
} : function (input, position) {
return (input.charCodeAt(position) - 0xd800) * 0x400 + input.charCodeAt(position + 1) - 0xdc00 + 0x10000;
};
/**
* @param {string} macroText macro text
* @param {RegExp} macroRegExp macro reg exp
* @param {(input: string) => string} macroReplacer macro replacer
* @returns {string} result
*/
var replaceUsingRegExp = function replaceUsingRegExp(macroText, macroRegExp, macroReplacer) {
macroRegExp.lastIndex = 0;
var replaceMatch = macroRegExp.exec(macroText);
var replaceResult;
if (replaceMatch) {
replaceResult = "";
var replaceLastIndex = 0;
do {
if (replaceLastIndex !== replaceMatch.index) {
replaceResult += macroText.slice(replaceLastIndex, replaceMatch.index);
}
var replaceInput = replaceMatch[0];
replaceResult += macroReplacer(replaceInput);
replaceLastIndex = replaceMatch.index + replaceInput.length;
} while (replaceMatch = macroRegExp.exec(macroText));
if (replaceLastIndex !== macroText.length) {
replaceResult += macroText.slice(replaceLastIndex);
}
} else {
replaceResult = macroText;
}
return replaceResult;
};
var references = {
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&apos;",
"&": "&amp;"
};
/**
* @param {string} text text
* @returns {string} encoded text
*/
function encode(text) {
if (!text) {
return "";
}
return replaceUsingRegExp(text, /[<>'"&]/g, function (input) {
var result = references[(/** @type {keyof typeof references} */input)];
if (!result) {
var code = input.length > 1 ? getCodePoint(input, 0) : input.charCodeAt(0);
result = "&#".concat(code, ";");
}
return result;
});
}
/**
* @typedef {object} Context
* @property {'warning' | 'error'} level level
* @property {(string | Message)[]} messages messages
* @property {'build' | 'runtime'} messageSource message source
*/
/** @typedef {{ type: string } & Record<string, EXPECTED_ANY>} Event */
/**
* @typedef {object} Options
* @property {{ [state: string]: { on: Record<string, { target: string; actions?: Array<string> }> } }} states states
* @property {Context} context context
* @property {string} initial initial
*/
/**
* @typedef {object} Implementation
* @property {{ [actionName: string]: (ctx: Context, event: Event) => Context | void }} actions actions
*/
/**
* @typedef {{ send: (event: Event) => void }} StateMachine
*/
/**
* A simplified `createMachine` from `@xstate/fsm` with the following differences:
* - the returned machine is technically a "service". No `interpret(machine).start()` is needed.
* - the state definition only support `on` and target must be declared with { target: 'nextState', actions: [] } explicitly.
* - event passed to `send` must be an object with `type` property.
* - actions implementation will be [assign action](https://xstate.js.org/docs/guides/context.html#assign-action) if you return any value.
* Do not return anything if you just want to invoke side effect.
*
* The goal of this custom function is to avoid installing the entire `'xstate/fsm'` package, while enabling modeling using
* state machine. You can copy the first parameter into the editor at https://stately.ai/viz to visualize the state machine.
* @param {Options} options options
* @param {Implementation} implementation implementation
* @returns {StateMachine} state machine
*/
function createMachine(_ref, _ref2) {
var states = _ref.states,
context = _ref.context,
initial = _ref.initial;
var actions = _ref2.actions;
var currentState = initial;
var currentContext = context;
return {
send: function send(event) {
var currentStateOn = states[currentState].on;
var transitionConfig = currentStateOn && currentStateOn[event.type];
if (transitionConfig) {
currentState = transitionConfig.target;
if (transitionConfig.actions) {
transitionConfig.actions.forEach(function (actName) {
var actionImpl = actions[actName];
var nextContextValue = actionImpl && actionImpl(currentContext, event);
if (nextContextValue) {
currentContext = _objectSpread(_objectSpread({}, currentContext), nextContextValue);
}
});
}
}
}
};
}
/**
* @typedef {object} ShowOverlayData
* @property {'warning' | 'error'} level level
* @property {(string | Message)[]} messages messages
* @property {'build' | 'runtime'} messageSource message source
*/
/**
* @typedef {object} CreateOverlayMachineOptions
* @property {(data: ShowOverlayData) => void} showOverlay show overlay
* @property {() => void} hideOverlay hide overlay
*/
/**
* @param {CreateOverlayMachineOptions} options options
* @returns {StateMachine} state machine
*/
var createOverlayMachine = function createOverlayMachine(options) {
var hideOverlay = options.hideOverlay,
showOverlay = options.showOverlay;
return createMachine({
initial: "hidden",
context: {
level: "error",
messages: [],
messageSource: "build"
},
states: {
hidden: {
on: {
BUILD_ERROR: {
target: "displayBuildError",
actions: ["setMessages", "showOverlay"]
},
RUNTIME_ERROR: {
target: "displayRuntimeError",
actions: ["setMessages", "showOverlay"]
}
}
},
displayBuildError: {
on: {
DISMISS: {
target: "hidden",
actions: ["dismissMessages", "hideOverlay"]
},
BUILD_ERROR: {
target: "displayBuildError",
actions: ["appendMessages", "showOverlay"]
}
}
},
displayRuntimeError: {
on: {
DISMISS: {
target: "hidden",
actions: ["dismissMessages", "hideOverlay"]
},
RUNTIME_ERROR: {
target: "displayRuntimeError",
actions: ["appendMessages", "showOverlay"]
},
BUILD_ERROR: {
target: "displayBuildError",
actions: ["setMessages", "showOverlay"]
}
}
}
}
}, {
actions: {
dismissMessages: function dismissMessages() {
return {
messages: [],
level: "error",
messageSource: "build"
};
},
appendMessages: function appendMessages(context, event) {
return {
messages: context.messages.concat(event.messages),
level: event.level || context.level,
messageSource: event.type === "RUNTIME_ERROR" ? "runtime" : "build"
};
},
setMessages: function setMessages(context, event) {
return {
messages: event.messages,
level: event.level || context.level,
messageSource: event.type === "RUNTIME_ERROR" ? "runtime" : "build"
};
},
hideOverlay: hideOverlay,
showOverlay: showOverlay
}
});
};
/**
* @param {Error} error error
* @returns {undefined | string[]} stack
*/
var parseErrorToStacks = function parseErrorToStacks(error) {
if (!error || !(error instanceof Error)) {
throw new Error("parseErrorToStacks expects Error object");
}
if (typeof error.stack === "string") {
return error.stack.split("\n").filter(function (stack) {
return stack !== "Error: ".concat(error.message);
});
}
};
/**
* @callback ErrorCallback
* @param {ErrorEvent} error
* @returns {void}
*/
/**
* @param {ErrorCallback} callback callback
* @returns {() => void} cleanup
*/
var listenToRuntimeError = function listenToRuntimeError(callback) {
window.addEventListener("error", callback);
return function cleanup() {
window.removeEventListener("error", callback);
};
};
/**
* @callback UnhandledRejectionCallback
* @param {PromiseRejectionEvent} rejectionEvent
* @returns {void}
*/
/**
* @param {UnhandledRejectionCallback} callback callback
* @returns {() => void} cleanup
*/
var listenToUnhandledRejection = function listenToUnhandledRejection(callback) {
window.addEventListener("unhandledrejection", callback);
return function cleanup() {
window.removeEventListener("unhandledrejection", callback);
};
};
// Styles are inspired by `react-error-overlay`
var msgStyles = {
error: {
backgroundColor: "rgba(206, 17, 38, 0.1)",
color: "#fccfcf"
},
warning: {
backgroundColor: "rgba(251, 245, 180, 0.1)",
color: "#fbf5b4"
}
};
var iframeStyle = {
position: "fixed",
top: "0px",
left: "0px",
right: "0px",
bottom: "0px",
width: "100vw",
height: "100vh",
border: "none",
"z-index": 9999999999
};
var containerStyle = {
position: "fixed",
boxSizing: "border-box",
left: "0px",
top: "0px",
right: "0px",
bottom: "0px",
width: "100vw",
height: "100vh",
fontSize: "large",
padding: "2rem 2rem 4rem 2rem",
lineHeight: "1.2",
whiteSpace: "pre-wrap",
overflow: "auto",
backgroundColor: "rgba(0, 0, 0, 0.9)",
color: "white"
};
var headerStyle = {
color: "#e83b46",
fontSize: "2em",
whiteSpace: "pre-wrap",
fontFamily: "sans-serif",
margin: "0 2rem 2rem 0",
flex: "0 0 auto",
maxHeight: "50%",
overflow: "auto"
};
var dismissButtonStyle = {
color: "#ffffff",
lineHeight: "1rem",
fontSize: "1.5rem",
padding: "1rem",
cursor: "pointer",
position: "absolute",
right: "0px",
top: "0px",
backgroundColor: "transparent",
border: "none"
};
var msgTypeStyle = {
color: "#e83b46",
fontSize: "1.2em",
marginBottom: "1rem",
fontFamily: "sans-serif"
};
var msgTextStyle = {
lineHeight: "1.5",
fontSize: "1rem",
fontFamily: "Menlo, Consolas, monospace"
};
// ANSI HTML
var colors = {
reset: ["transparent", "transparent"],
black: "181818",
red: "E36049",
green: "B3CB74",
yellow: "FFD080",
blue: "7CAFC2",
magenta: "7FACCA",
cyan: "C3C2EF",
lightgrey: "EBE7E3",
darkgrey: "6D7891"
};
ansiHTML.setColors(colors);
/** @typedef {Error & { file?: string, moduleName?: string, moduleIdentifier?: string, loc?: string, message?: string; stack?: string | string[] }} Message */
/**
* @param {string} type type
* @param {string | Message} item item
* @returns {{ header: string, body: string }} formatted problem
*/
var formatProblem = function formatProblem(type, item) {
var header = type === "warning" ? "WARNING" : "ERROR";
var body = "";
if (typeof item === "string") {
body += item;
} else {
var file = item.file || "";
var moduleName = item.moduleName ? item.moduleName.indexOf("!") !== -1 ? "".concat(item.moduleName.replace(/^(\s|\S)*!/, ""), " (").concat(item.moduleName, ")") : "".concat(item.moduleName) : "";
var loc = item.loc;
header += "".concat(moduleName || file ? " in ".concat(moduleName ? "".concat(moduleName).concat(file ? " (".concat(file, ")") : "") : file).concat(loc ? " ".concat(loc) : "") : "");
body += item.message || "";
}
if (typeof item !== "string" && Array.isArray(item.stack)) {
item.stack.forEach(function (stack) {
if (typeof stack === "string") {
body += "\r\n".concat(stack);
}
});
}
return {
header: header,
body: body
};
};
/**
* @typedef {object} CreateOverlayOptions
* @property {(false | string)=} trustedTypesPolicyName trusted types policy name
* @property {(boolean | ((error: Error) => void))=} catchRuntimeError runtime error catcher
*/
/**
* @param {CreateOverlayOptions} options options
* @returns {StateMachine} overlay
*/
var createOverlay = function createOverlay(options) {
/** @type {HTMLIFrameElement | null | undefined} */
var iframeContainerElement;
/** @type {HTMLDivElement | null | undefined} */
var containerElement;
/** @type {HTMLDivElement | null | undefined} */
var headerElement;
/** @type {Array<(element: HTMLDivElement) => void>} */
var onLoadQueue = [];
/** @type {Omit<TrustedTypePolicy, "createScript" | "createScriptURL"> | undefined} */
var overlayTrustedTypesPolicy;
/** @typedef {Extract<keyof CSSStyleDeclaration, "string">} CSSStyleDeclarationKeys */
/**
* @param {HTMLElement} element element
* @param {Partial<CSSStyleDeclaration>} style style
*/
function applyStyle(element, style) {
Object.keys(style).forEach(function (prop) {
element.style[(/** @type {CSSStyleDeclarationKeys} */prop)] = /** @type {string} */
style[(/** @type {CSSStyleDeclarationKeys} */prop)];
});
}
/**
* @param {string | false | undefined} trustedTypesPolicyName trusted types police name
*/
function createContainer(trustedTypesPolicyName) {
// Enable Trusted Types if they are available in the current browser.
if (window.trustedTypes) {
overlayTrustedTypesPolicy = window.trustedTypes.createPolicy(trustedTypesPolicyName || "webpack-dev-server#overlay", {
createHTML: function createHTML(value) {
return value;
}
});
}
iframeContainerElement = document.createElement("iframe");
iframeContainerElement.id = "webpack-dev-server-client-overlay";
iframeContainerElement.src = "about:blank";
applyStyle(iframeContainerElement, iframeStyle);
iframeContainerElement.onload = function () {
var contentElement = /** @type {Document} */
(/** @type {HTMLIFrameElement} */
iframeContainerElement.contentDocument).createElement("div");
containerElement = /** @type {Document} */
(/** @type {HTMLIFrameElement} */
iframeContainerElement.contentDocument).createElement("div");
contentElement.id = "webpack-dev-server-client-overlay-div";
applyStyle(contentElement, containerStyle);
headerElement = document.createElement("div");
headerElement.innerText = "Compiled with problems:";
applyStyle(headerElement, headerStyle);
var closeButtonElement = document.createElement("button");
applyStyle(closeButtonElement, dismissButtonStyle);
closeButtonElement.innerText = "×";
closeButtonElement.ariaLabel = "Dismiss";
closeButtonElement.addEventListener("click", function () {
// eslint-disable-next-line no-use-before-define
overlayService.send({
type: "DISMISS"
});
});
contentElement.appendChild(headerElement);
contentElement.appendChild(closeButtonElement);
contentElement.appendChild(containerElement);
/** @type {Document} */
(/** @type {HTMLIFrameElement} */
iframeContainerElement.contentDocument).body.appendChild(contentElement);
onLoadQueue.forEach(function (onLoad) {
onLoad(/** @type {HTMLDivElement} */contentElement);
});
onLoadQueue = [];
/** @type {HTMLIFrameElement} */
iframeContainerElement.onload = null;
};
document.body.appendChild(iframeContainerElement);
}
/**
* @param {(element: HTMLDivElement) => void} callback callback
* @param {string | false | undefined} trustedTypesPolicyName trusted types policy name
*/
function ensureOverlayExists(callback, trustedTypesPolicyName) {
if (containerElement) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/30024
containerElement.innerHTML = overlayTrustedTypesPolicy ? overlayTrustedTypesPolicy.createHTML("") : "";
// Everything is ready, call the callback right away.
callback(containerElement);
return;
}
onLoadQueue.push(callback);
if (iframeContainerElement) {
return;
}
createContainer(trustedTypesPolicyName);
}
// Successful compilation.
/**
* @returns {void}
*/
function hide() {
if (!iframeContainerElement) {
return;
}
// Clean up and reset internal state.
document.body.removeChild(iframeContainerElement);
iframeContainerElement = null;
containerElement = null;
}
// Compilation with errors (e.g. syntax error or missing modules).
/**
* @param {string} type type
* @param {(string | Message)[]} messages messages
* @param {undefined | false | string} trustedTypesPolicyName trusted types policy name
* @param {'build' | 'runtime'} messageSource message source
*/
function show(type, messages, trustedTypesPolicyName, messageSource) {
ensureOverlayExists(function () {
/** @type {HTMLDivElement} */
headerElement.innerText = messageSource === "runtime" ? "Uncaught runtime errors:" : "Compiled with problems:";
messages.forEach(function (message) {
var entryElement = document.createElement("div");
var msgStyle = type === "warning" ? msgStyles.warning : msgStyles.error;
applyStyle(entryElement, _objectSpread(_objectSpread({}, msgStyle), {}, {
padding: "1rem 1rem 1.5rem 1rem"
}));
var typeElement = document.createElement("div");
var _formatProblem = formatProblem(type, message),
header = _formatProblem.header,
body = _formatProblem.body;
typeElement.innerText = header;
applyStyle(typeElement, msgTypeStyle);
if (typeof message !== "string" && message.moduleIdentifier) {
applyStyle(typeElement, {
cursor: "pointer"
});
// element.dataset not supported in IE
typeElement.setAttribute("data-can-open", "true");
typeElement.addEventListener("click", function () {
fetch("/webpack-dev-server/open-editor?fileName=".concat(message.moduleIdentifier));
});
}
// Make it look similar to our terminal.
var text = ansiHTML(encode(body));
var messageTextNode = document.createElement("div");
applyStyle(messageTextNode, msgTextStyle);
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/30024
messageTextNode.innerHTML = overlayTrustedTypesPolicy ? overlayTrustedTypesPolicy.createHTML(text) : text;
entryElement.appendChild(typeElement);
entryElement.appendChild(messageTextNode);
/** @type {HTMLDivElement} */
containerElement.appendChild(entryElement);
});
}, trustedTypesPolicyName);
}
/** @type {(event: KeyboardEvent) => void} */
var handleEscapeKey;
/**
* @returns {void}
*/
var hideOverlayWithEscCleanup = function hideOverlayWithEscCleanup() {
window.removeEventListener("keydown", handleEscapeKey);
hide();
};
var overlayService = createOverlayMachine({
showOverlay: function showOverlay(_ref3) {
var _ref3$level = _ref3.level,
level = _ref3$level === void 0 ? "error" : _ref3$level,
messages = _ref3.messages,
messageSource = _ref3.messageSource;
return show(level, messages, options.trustedTypesPolicyName, messageSource);
},
hideOverlay: hideOverlayWithEscCleanup
});
/**
* ESC key press to dismiss the overlay.
* @param {KeyboardEvent} event Keydown event
*/
handleEscapeKey = function handleEscapeKey(event) {
if (event.key === "Escape" || event.key === "Esc" || event.keyCode === 27) {
overlayService.send({
type: "DISMISS"
});
}
};
window.addEventListener("keydown", handleEscapeKey);
if (options.catchRuntimeError) {
/**
* @param {Error | undefined} error error
* @param {string} fallbackMessage fallback message
*/
var handleError = function handleError(error, fallbackMessage) {
var errorObject = error instanceof Error ? error : new Error(error || fallbackMessage, {
cause: error
});
var shouldDisplay = typeof options.catchRuntimeError === "function" ? options.catchRuntimeError(errorObject) : true;
if (shouldDisplay) {
overlayService.send({
type: "RUNTIME_ERROR",
messages: [{
message: errorObject.message,
stack: parseErrorToStacks(errorObject)
}]
});
}
};
listenToRuntimeError(function (errorEvent) {
// error property may be empty in older browser like IE
var error = errorEvent.error,
message = errorEvent.message;
if (!error && !message) {
return;
}
// if error stack indicates a React error boundary caught the error, do not show overlay.
if (error && error.stack && error.stack.includes("invokeGuardedCallbackDev")) {
return;
}
handleError(error, message);
});
listenToUnhandledRejection(function (promiseRejectionEvent) {
var reason = promiseRejectionEvent.reason;
handleError(reason, "Unknown promise rejection reason");
});
}
return overlayService;
};
export { createOverlay, formatProblem };
+152
View File
@@ -0,0 +1,152 @@
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }
function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
/**
* @returns {boolean} true when custom elements supported, otherwise false
*/
export function isProgressSupported() {
return "customElements" in self && Boolean(HTMLElement.prototype.attachShadow);
}
/**
* @returns {void}
*/
export function defineProgressElement() {
var _WebpackDevServerProgress;
if (customElements.get("wds-progress")) {
return;
}
var _WebpackDevServerProgress_brand = /*#__PURE__*/new WeakSet();
var WebpackDevServerProgress = /*#__PURE__*/function (_HTMLElement) {
function WebpackDevServerProgress() {
var _this;
_classCallCheck(this, WebpackDevServerProgress);
_this = _callSuper(this, WebpackDevServerProgress);
_classPrivateMethodInitSpec(_this, _WebpackDevServerProgress_brand);
_this.attachShadow({
mode: "open"
});
_this.maxDashOffset = -219.99078369140625;
_this.animationTimer = null;
return _this;
}
_inherits(WebpackDevServerProgress, _HTMLElement);
return _createClass(WebpackDevServerProgress, [{
key: "connectedCallback",
value: function connectedCallback() {
_assertClassBrand(_WebpackDevServerProgress_brand, this, _reset).call(this);
}
}, {
key: "attributeChangedCallback",
value:
/**
* @param {string} name name
* @param {string} oldValue old value
* @param {string} newValue new value
*/
function attributeChangedCallback(name, oldValue, newValue) {
if (name === "progress") {
_assertClassBrand(_WebpackDevServerProgress_brand, this, _update).call(this, Number(newValue));
} else if (name === "type") {
_assertClassBrand(_WebpackDevServerProgress_brand, this, _reset).call(this);
}
}
/**
* @param {number} percent percent
*/
}], [{
key: "observedAttributes",
get: function get() {
return ["progress", "type"];
}
}]);
}(/*#__PURE__*/_wrapNativeSuper(HTMLElement));
_WebpackDevServerProgress = WebpackDevServerProgress;
function _reset() {
var _this$getAttribute;
clearTimeout(this.animationTimer);
this.animationTimer = null;
var typeAttr = (_this$getAttribute = this.getAttribute("type")) === null || _this$getAttribute === void 0 ? void 0 : _this$getAttribute.toLowerCase();
this.type = typeAttr === "circular" ? "circular" : "linear";
var innerHTML = this.type === "circular" ? _circularTemplate.call(_WebpackDevServerProgress) : _linearTemplate.call(_WebpackDevServerProgress);
/** @type {ShadowRoot} */
this.shadowRoot.innerHTML = innerHTML;
var progressValue = this.getAttribute("progress");
this.initialProgress = progressValue ? Number(progressValue) : 0;
_assertClassBrand(_WebpackDevServerProgress_brand, this, _update).call(this, this.initialProgress);
}
function _circularTemplate() {
return "\n <style>\n :host {\n width: 200px;\n height: 200px;\n position: fixed;\n right: 5%;\n top: 5%;\n pointer-events: none;\n transition: opacity .25s ease-in-out;\n z-index: 2147483645;\n }\n\n circle {\n fill: #282d35;\n }\n\n path {\n fill: rgba(0, 0, 0, 0);\n stroke: rgb(186, 223, 172);\n stroke-dasharray: 219.99078369140625;\n stroke-dashoffset: -219.99078369140625;\n stroke-width: 10;\n transform: rotate(90deg) translate(0px, -80px);\n }\n\n text {\n font-family: 'Open Sans', sans-serif;\n font-size: 18px;\n fill: #ffffff;\n dominant-baseline: middle;\n text-anchor: middle;\n }\n\n tspan#percent-super {\n fill: #bdc3c7;\n font-size: 0.45em;\n baseline-shift: 10%;\n }\n\n @keyframes fade {\n 0% { opacity: 1; transform: scale(1); }\n 100% { opacity: 0; transform: scale(0); }\n }\n\n .disappear {\n animation: fade 0.3s;\n animation-fill-mode: forwards;\n animation-delay: 0.5s;\n }\n\n .hidden {\n display: none;\n }\n </style>\n <svg id=\"progress\" class=\"hidden noselect\" viewBox=\"0 0 80 80\">\n <circle cx=\"50%\" cy=\"50%\" r=\"35\"></circle>\n <path d=\"M5,40a35,35 0 1,0 70,0a35,35 0 1,0 -70,0\"></path>\n <text x=\"50%\" y=\"51%\">\n <tspan id=\"percent-value\">0</tspan>\n <tspan id=\"percent-super\">%</tspan>\n </text>\n </svg>\n ";
}
function _linearTemplate() {
return "\n <style>\n :host {\n position: fixed;\n top: 0;\n left: 0;\n pointer-events: none;\n height: 4px;\n width: 100vw;\n z-index: 2147483645;\n }\n\n #bar {\n width: 0%;\n height: 4px;\n background-color: rgb(186, 223, 172);\n }\n\n @keyframes fade {\n 0% { opacity: 1; }\n 100% { opacity: 0; }\n }\n\n .disappear {\n animation: fade 0.3s;\n animation-fill-mode: forwards;\n animation-delay: 0.5s;\n }\n\n .hidden {\n display: none;\n }\n </style>\n <div id=\"progress\"></div>\n ";
}
function _update(percent) {
var shadowRoot = /** @type {ShadowRoot} */this.shadowRoot;
var element = /** @type {HTMLElement} */
shadowRoot.querySelector("#progress");
if (this.type === "circular") {
var path = /** @type {SVGPathElement} */
shadowRoot.querySelector("path");
var value = /** @type {HTMLElement} */
shadowRoot.querySelector("#percent-value");
var offset = (100 - percent) / 100 * this.maxDashOffset;
path.style.strokeDashoffset = String(offset);
value.textContent = String(percent);
} else {
element.style.width = "".concat(percent, "%");
}
if (percent >= 100) {
_assertClassBrand(_WebpackDevServerProgress_brand, this, _hide).call(this);
} else if (percent > 0) {
_assertClassBrand(_WebpackDevServerProgress_brand, this, _show).call(this);
}
}
function _show() {
var shadowRoot = /** @type {ShadowRoot} */this.shadowRoot;
var element = /** @type {HTMLElement} */
shadowRoot.querySelector("#progress");
element.classList.remove("hidden");
}
function _hide() {
var _this2 = this;
var shadowRoot = /** @type {ShadowRoot} */this.shadowRoot;
var element = /** @type {HTMLElement} */
shadowRoot.querySelector("#progress");
if (this.type === "circular") {
element.classList.add("disappear");
element.addEventListener("animationend", function () {
element.classList.add("hidden");
_assertClassBrand(_WebpackDevServerProgress_brand, _this2, _update).call(_this2, 0);
}, {
once: true
});
} else if (this.type === "linear") {
element.classList.add("disappear");
this.animationTimer = setTimeout(function () {
element.classList.remove("disappear");
element.classList.add("hidden");
element.style.width = "0%";
_this2.animationTimer = null;
}, 800);
}
}
customElements.define("wds-progress", WebpackDevServerProgress);
}
+74
View File
@@ -0,0 +1,74 @@
/* global __webpack_dev_server_client__ */
import WebSocketClient from "./clients/WebSocketClient.js";
import { log } from "./utils/log.js";
/** @typedef {import("./index.js").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./clients/SockJSClient")} SockJSClient */
// this WebsocketClient is here as a default fallback, in case the client is not injected
/** @type {CommunicationClientConstructor} */
var Client = typeof __webpack_dev_server_client__ !== "undefined" ? typeof (/** @type {{ default: CommunicationClientConstructor }} */
__webpack_dev_server_client__.default) !== "undefined" ? /** @type {{ default: CommunicationClientConstructor }} */
__webpack_dev_server_client__.default : (/** @type {CommunicationClientConstructor} */
__webpack_dev_server_client__) : WebSocketClient;
var retries = 0;
var maxRetries = 10;
// Initialized client is exported so external consumers can utilize the same instance
// It is mutable to enforce singleton
/** @type {CommunicationClient | null} */
// eslint-disable-next-line import/no-mutable-exports
export var client = null;
/** @type {ReturnType<typeof setTimeout> | undefined} */
var timeout;
/**
* @param {string} url url
* @param {{ [handler: string]: (data?: EXPECTED_ANY, params?: EXPECTED_ANY) => EXPECTED_ANY }} handlers handlers
* @param {number=} reconnect count of reconnections
*/
function socket(url, handlers, reconnect) {
client = new Client(url);
client.onOpen(function () {
retries = 0;
if (timeout) {
clearTimeout(timeout);
}
if (typeof reconnect !== "undefined") {
maxRetries = reconnect;
}
});
client.onClose(function () {
if (retries === 0) {
handlers.close();
}
// Try to reconnect.
client = null;
// After 10 retries stop trying, to prevent logspam.
if (retries < maxRetries) {
// Exponentially increase timeout to reconnect.
// Respectfully copied from the package `got`.
var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
retries += 1;
log.info("Trying to reconnect...");
timeout = setTimeout(function () {
socket(url, handlers, reconnect);
}, retryInMs);
}
});
client.onMessage(
/**
* @param {EXPECTED_ANY} data data
*/
function (data) {
var message = JSON.parse(data);
if (handlers[message.type]) {
handlers[message.type](message.data, message.params);
}
});
}
export default socket;
+19
View File
@@ -0,0 +1,19 @@
import logger from "../modules/logger/index.js";
var name = "webpack-dev-server";
// default level is set on the client side, so it does not need
// to be set by the CLI or API
var defaultLevel = "info";
// options new options, merge with old options
/**
* @param {false | true | "none" | "error" | "warn" | "info" | "log" | "verbose"} level level
* @returns {void}
*/
function setLogLevel(level) {
logger.configureDefaultLogger({
level: level
});
}
setLogLevel(defaultLevel);
var log = logger.getLogger(name);
export { log, setLogLevel };
+18
View File
@@ -0,0 +1,18 @@
/* global WorkerGlobalScope */
/** @typedef {import("../index").EXPECTED_ANY} EXPECTED_ANY */
// Send messages to the outside, so plugins can consume it.
/**
* @param {string} type type
* @param {EXPECTED_ANY=} data data
*/
function sendMsg(type, data) {
if (typeof self !== "undefined" && (typeof WorkerGlobalScope === "undefined" || !(self instanceof WorkerGlobalScope))) {
self.postMessage({
type: "webpack".concat(type),
data: data
}, "*");
}
}
export default sendMsg;
+3616
View File
File diff suppressed because it is too large Load Diff
+132
View File
@@ -0,0 +1,132 @@
"use strict";
/*
* Based on the packages get-port https://www.npmjs.com/package/get-port
* and portfinder https://www.npmjs.com/package/portfinder
* The code structure is similar to get-port, but it searches
* ports deterministically like portfinder
*/
const net = require("node:net");
const os = require("node:os");
const minPort = 1024;
const maxPort = 65_535;
/**
* @returns {Set<string | undefined>} local hosts
*/
const getLocalHosts = () => {
const interfaces = os.networkInterfaces();
// Add undefined value for createServer function to use default host,
// and default IPv4 host in case createServer defaults to IPv6.
const results = new Set([undefined, "0.0.0.0"]);
for (const _interface of Object.values(interfaces)) {
if (_interface) {
for (const config of _interface) {
results.add(config.address);
}
}
}
return results;
};
/**
* @param {number} basePort base port
* @param {string | undefined} host host
* @returns {Promise<number>} resolved port
*/
const checkAvailablePort = (basePort, host) =>
new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on("error", reject);
server.listen(basePort, host, () => {
// Next line should return AddressInfo because we're calling it after listen() and before close()
const { port } = /** @type {import("net").AddressInfo} */ (
server.address()
);
server.close(() => {
resolve(port);
});
});
});
/**
* @param {number} port port
* @param {Set<string|undefined>} hosts hosts
* @returns {Promise<number>} resolved port
*/
const getAvailablePort = async (port, hosts) => {
/**
* Errors that mean that host is not available.
* @type {Set<string | undefined>}
*/
const nonExistentInterfaceErrors = new Set(["EADDRNOTAVAIL", "EINVAL"]);
/* Check if the post is available on every local host name */
for (const host of hosts) {
try {
await checkAvailablePort(port, host);
} catch (error) {
/* We throw an error only if the interface exists */
if (
!nonExistentInterfaceErrors.has(
/** @type {NodeJS.ErrnoException} */ (error).code,
)
) {
throw error;
}
}
}
return port;
};
/**
* @param {number} basePort base port
* @param {string=} host host
* @returns {Promise<number>} resolved port
*/
async function getPorts(basePort, host) {
if (basePort < minPort || basePort > maxPort) {
throw new Error(`Port number must lie between ${minPort} and ${maxPort}`);
}
let port = basePort;
const localhosts = getLocalHosts();
const hosts =
host && !localhosts.has(host)
? new Set([host])
: /* If the host is equivalent to localhost
we need to check every equivalent host
else the port might falsely appear as available
on some operating systems */
localhosts;
/** @type {Set<string | undefined>} */
const portUnavailableErrors = new Set(["EADDRINUSE", "EACCES"]);
while (port <= maxPort) {
try {
const availablePort = await getAvailablePort(port, hosts);
return availablePort;
} catch (error) {
/* Try next port if port is busy; throw for any other error */
if (
!portUnavailableErrors.has(
/** @type {NodeJS.ErrnoException} */ (error).code,
)
) {
throw error;
}
port += 1;
}
}
throw new Error("No available ports found");
}
module.exports = getPorts;
+1034
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
"use strict";
/** @typedef {import("../Server").ClientConnection} ClientConnection */
// base class that users should extend if they are making their own
// server implementation
module.exports = class BaseServer {
/**
* @param {import("../Server")} server server
*/
constructor(server) {
/** @type {import("../Server")} */
this.server = server;
/** @type {ClientConnection[]} */
this.clients = [];
}
};
+128
View File
@@ -0,0 +1,128 @@
"use strict";
const sockjs = require("sockjs");
const BaseServer = require("./BaseServer");
/** @typedef {import("../Server").WebSocketServerConfiguration} WebSocketServerConfiguration */
/** @typedef {import("../Server").ClientConnection} ClientConnection */
// Workaround for sockjs@~0.3.19
// sockjs will remove Origin header, however Origin header is required for checking host.
// See https://github.com/webpack/webpack-dev-server/issues/1604 for more information
{
// @ts-expect-error
const SockjsSession = require("sockjs/lib/transport").Session;
const { decorateConnection } = SockjsSession.prototype;
/**
* @param {import("http").IncomingMessage} req request
*/
// eslint-disable-next-line func-names
SockjsSession.prototype.decorateConnection = function (req) {
decorateConnection.call(this, req);
const { connection } = this;
if (
connection.headers &&
!("origin" in connection.headers) &&
"origin" in req.headers
) {
connection.headers.origin = req.headers.origin;
}
};
}
module.exports = class SockJSServer extends BaseServer {
// options has: error (function), debug (function), server (http/s server), path (string)
/**
* @param {import("../Server")} server server
*/
constructor(server) {
super(server);
const webSocketServerOptions =
/** @type {NonNullable<WebSocketServerConfiguration["options"]>} */
(
/** @type {WebSocketServerConfiguration} */
(this.server.options.webSocketServer).options
);
/**
* @param {NonNullable<WebSocketServerConfiguration["options"]>} options options
* @returns {string} sockjs URL
*/
const getSockjsUrl = (options) => {
if (typeof options.sockjsUrl !== "undefined") {
return options.sockjsUrl;
}
return "/__webpack_dev_server__/sockjs.bundle.js";
};
this.implementation = sockjs.createServer({
// Use provided up-to-date sockjs-client
// eslint-disable-next-line camelcase
sockjs_url: getSockjsUrl(webSocketServerOptions),
// Default logger is very annoy. Limit useless logs.
/**
* @param {string} severity severity
* @param {string} line line
*/
log: (severity, line) => {
if (severity === "error") {
this.server.logger.error(line);
} else if (severity === "info") {
this.server.logger.log(line);
} else {
this.server.logger.debug(line);
}
},
});
/**
* @param {import("sockjs").ServerOptions & { path?: string }} options options
* @returns {string | undefined} prefix
*/
const getPrefix = (options) => {
if (typeof options.prefix !== "undefined") {
return options.prefix;
}
return options.path;
};
const options = {
...webSocketServerOptions,
prefix: getPrefix(webSocketServerOptions),
};
this.implementation.installHandlers(
/** @type {import("http").Server} */ (this.server.server),
options,
);
this.implementation.on("connection", (client) => {
// @ts-expect-error
// Implement the the same API as for `ws`
client.send = client.write;
// @ts-expect-error
client.terminate = client.close;
this.clients.push(/** @type {ClientConnection} */ (client));
client.on("close", () => {
this.clients.splice(
this.clients.indexOf(/** @type {ClientConnection} */ (client)),
1,
);
});
});
// @ts-expect-error
this.implementation.close = (callback) => {
callback();
};
}
};
+111
View File
@@ -0,0 +1,111 @@
"use strict";
const WebSocket = require("ws");
const BaseServer = require("./BaseServer");
/** @typedef {import("../Server").WebSocketServerConfiguration} WebSocketServerConfiguration */
/** @typedef {import("../Server").ClientConnection} ClientConnection */
module.exports = class WebsocketServer extends BaseServer {
static heartbeatInterval = 1000;
/**
* @param {import("../Server")} server server
*/
constructor(server) {
super(server);
/** @type {import("ws").ServerOptions} */
const options = {
.../** @type {WebSocketServerConfiguration} */
(this.server.options.webSocketServer).options,
clientTracking: false,
};
const isNoServerMode =
typeof options.port === "undefined" &&
typeof options.server === "undefined";
if (isNoServerMode) {
options.noServer = true;
}
this.implementation = new WebSocket.Server(options);
/** @type {import("http").Server} */
(this.server.server).on(
"upgrade",
/**
* @param {import("http").IncomingMessage} req request
* @param {import("stream").Duplex} sock socket
* @param {Buffer} head head
*/
(req, sock, head) => {
if (!this.implementation.shouldHandle(req)) {
return;
}
this.implementation.handleUpgrade(req, sock, head, (connection) => {
this.implementation.emit("connection", connection, req);
});
},
);
this.implementation.on(
"error",
/**
* @param {Error} err error
*/
(err) => {
this.server.logger.error(err.message);
},
);
const interval = setInterval(() => {
for (const client of this.clients) {
if (client.isAlive === false) {
client.terminate();
continue;
}
client.isAlive = false;
client.ping(() => {});
}
}, WebsocketServer.heartbeatInterval);
this.implementation.on(
"connection",
/**
* @param {ClientConnection} client client
*/
(client) => {
this.clients.push(client);
client.isAlive = true;
client.on("pong", () => {
client.isAlive = true;
});
client.on("close", () => {
this.clients.splice(this.clients.indexOf(client), 1);
});
// TODO: add a test case for this - https://github.com/webpack/webpack-dev-server/issues/5018
client.on(
"error",
/**
* @param {Error} err err
*/
(err) => {
this.server.logger.error(err.message);
},
);
},
);
this.implementation.on("close", () => {
clearInterval(interval);
});
}
};
+153
View File
@@ -0,0 +1,153 @@
{
"name": "webpack-dev-server",
"version": "5.2.3",
"description": "Serves a webpack app. Updates the browser on changes.",
"homepage": "https://github.com/webpack/webpack-dev-server#readme",
"bugs": "https://github.com/webpack/webpack-dev-server/issues",
"repository": "https://github.com/webpack/webpack-dev-server",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/webpack"
},
"license": "MIT",
"author": "Tobias Koppers @sokra",
"main": "lib/Server.js",
"types": "types/lib/Server.d.ts",
"bin": "bin/webpack-dev-server.js",
"files": [
"bin",
"lib",
"client",
"types"
],
"scripts": {
"fmt:check": "prettier \"{**/*,*}.{js,json,md,yml,css,ts}\" --list-different",
"lint:prettier": "prettier --cache --list-different .",
"lint:code": "eslint --cache .",
"lint:types": "tsc --pretty --noEmit",
"lint:types-client": "tsc -p tsconfig.client.json",
"lint:spelling": "cspell --cache --no-must-find-files --quiet \"**/*.*\"",
"lint": "npm-run-all -l -p \"lint:**\"",
"fix:code": "npm run lint:code -- --fix",
"fix:prettier": "npm run lint:prettier -- --write",
"fix": "npm-run-all -l fix:code fix:prettier",
"commitlint": "commitlint --from=main",
"build:client": "rimraf -g ./client/* && babel client-src/ --out-dir client/ --ignore \"client-src/webpack.config.js\" --ignore \"client-src/modules\" && webpack --config client-src/webpack.config.js",
"build:types": "rimraf -g ./types/* && tsc --declaration --emitDeclarationOnly --outDir types && node ./scripts/extend-webpack-types.js && prettier \"types/**/*.ts\" --write && prettier \"types/**/*.ts\" --write",
"build": "npm-run-all -p \"build:**\"",
"test:only": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"test:coverage": "npm run test:only -- --coverage",
"test:watch": "npm run test:coverage --watch",
"test": "npm run test:coverage",
"pretest": "npm run lint",
"prepare": "husky && npm run build",
"release": "standard-version"
},
"dependencies": {
"@types/bonjour": "^3.5.13",
"@types/connect-history-api-fallback": "^1.5.4",
"@types/express": "^4.17.25",
"@types/express-serve-static-core": "^4.17.21",
"@types/serve-index": "^1.9.4",
"@types/serve-static": "^1.15.5",
"@types/sockjs": "^0.3.36",
"@types/ws": "^8.5.10",
"ansi-html-community": "^0.0.8",
"bonjour-service": "^1.2.1",
"chokidar": "^3.6.0",
"colorette": "^2.0.10",
"compression": "^1.8.1",
"connect-history-api-fallback": "^2.0.0",
"express": "^4.22.1",
"graceful-fs": "^4.2.6",
"http-proxy-middleware": "^2.0.9",
"ipaddr.js": "^2.1.0",
"launch-editor": "^2.6.1",
"open": "^10.0.3",
"p-retry": "^6.2.0",
"schema-utils": "^4.2.0",
"selfsigned": "^5.5.0",
"serve-index": "^1.9.1",
"sockjs": "^0.3.24",
"spdy": "^4.0.2",
"webpack-dev-middleware": "^7.4.2",
"ws": "^8.18.0"
},
"devDependencies": {
"@babel/cli": "^7.25.9",
"@babel/core": "^7.25.9",
"@babel/eslint-parser": "^7.25.9",
"@babel/plugin-transform-object-assign": "^7.25.9",
"@babel/plugin-transform-runtime": "^7.25.9",
"@babel/preset-env": "^7.25.9",
"@babel/runtime": "^7.25.9",
"@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0",
"@eslint/markdown": "^7.0.0",
"@hono/node-server": "^1.13.3",
"@types/compression": "^1.7.2",
"@types/graceful-fs": "^4.1.9",
"@types/node": "^24.0.14",
"@types/node-forge": "^1.3.1",
"@types/sockjs-client": "^1.5.1",
"@types/trusted-types": "^2.0.7",
"acorn": "^8.14.0",
"babel-jest": "^30.0.4",
"babel-loader": "^10.0.0",
"connect": "^3.7.0",
"core-js": "^3.38.1",
"cspell": "^8.15.5",
"css-loader": "^7.1.1",
"eslint": "^9.30.1",
"eslint-config-prettier": "^10.1.5",
"eslint-config-webpack": "^4.4.0",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jest": "^29.0.1",
"eslint-plugin-jsdoc": "^51.3.4",
"eslint-plugin-n": "^17.21.0",
"execa": "^5.1.1",
"hono": "^4.6.8",
"html-webpack-plugin": "^5.6.3",
"http-proxy": "^1.18.1",
"husky": "^9.1.6",
"jest": "^30.0.4",
"jest-environment-jsdom": "^29.7.0",
"klona": "^2.0.4",
"less": "^4.1.1",
"less-loader": "^12.1.0",
"lint-staged": "^15.2.10",
"marked": "^12.0.0",
"memfs": "^4.14.0",
"npm-run-all": "^4.1.5",
"prettier": "^3.2.4",
"puppeteer": "^24.10.0",
"readable-stream": "^4.5.2",
"require-from-string": "^2.0.2",
"rimraf": "^5.0.5",
"sockjs-client": "^1.6.1",
"standard-version": "^9.3.0",
"style-loader": "^4.0.0",
"supertest": "^7.2.2",
"tcp-port-used": "^1.0.2",
"typescript": "^5.7.2",
"typescript-eslint": "^8.36.0",
"wait-for-expect": "^3.0.2",
"webpack": "^5.94.0",
"webpack-cli": "^6.0.1",
"webpack-merge": "^6.0.1"
},
"peerDependencies": {
"webpack": "^5.0.0"
},
"peerDependenciesMeta": {
"webpack-cli": {
"optional": true
},
"webpack": {
"optional": true
}
},
"engines": {
"node": ">= 18.12.0"
}
}
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env node
export type CliOption = {
/**
* display name
*/
name: string;
/**
* npm package name
*/
package: string;
/**
* name of the executable file
*/
binName: string;
/**
* currently installed?
*/
installed: boolean;
/**
* homepage
*/
url: string;
/**
* preprocessor
*/
preprocess: () => void;
};
File diff suppressed because it is too large Load Diff
+10
View File
@@ -0,0 +1,10 @@
export = getPorts;
/**
* @param {number} basePort base port
* @param {string=} host host
* @returns {Promise<number>} resolved port
*/
declare function getPorts(
basePort: number,
host?: string | undefined,
): Promise<number>;
+15
View File
@@ -0,0 +1,15 @@
export = BaseServer;
declare class BaseServer {
/**
* @param {import("../Server")} server server
*/
constructor(server: import("../Server"));
/** @type {import("../Server")} */
server: import("../Server");
/** @type {ClientConnection[]} */
clients: ClientConnection[];
}
declare namespace BaseServer {
export { ClientConnection };
}
type ClientConnection = import("../Server").ClientConnection;
+12
View File
@@ -0,0 +1,12 @@
export = SockJSServer;
declare class SockJSServer extends BaseServer {
implementation: sockjs.Server;
}
declare namespace SockJSServer {
export { WebSocketServerConfiguration, ClientConnection };
}
import BaseServer = require("./BaseServer");
import sockjs = require("sockjs");
type WebSocketServerConfiguration =
import("../Server").WebSocketServerConfiguration;
type ClientConnection = import("../Server").ClientConnection;
+16
View File
@@ -0,0 +1,16 @@
export = WebsocketServer;
declare class WebsocketServer extends BaseServer {
static heartbeatInterval: number;
implementation: WebSocket.Server<
typeof WebSocket,
typeof import("http").IncomingMessage
>;
}
declare namespace WebsocketServer {
export { WebSocketServerConfiguration, ClientConnection };
}
import BaseServer = require("./BaseServer");
import WebSocket = require("ws");
type WebSocketServerConfiguration =
import("../Server").WebSocketServerConfiguration;
type ClientConnection = import("../Server").ClientConnection;