first commit

This commit is contained in:
monjack
2025-06-20 18:01:48 +08:00
commit 6daa6d65c1
24611 changed files with 2512443 additions and 0 deletions

View File

@ -0,0 +1,121 @@
/**
* @param {{ protocol?: string, auth?: string, hostname?: string, port?: string, pathname?: string, search?: string, hash?: string, slashes?: boolean }} objURL
* @returns {string}
*/
function format(objURL) {
var protocol = objURL.protocol || "";
if (protocol && protocol.substr(-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
* @returns {string}
*/
function (match) {
return encodeURIComponent(match);
});
search = search.replace("#", "%23");
return "".concat(protocol).concat(host).concat(pathname).concat(search).concat(hash);
}
/**
* @param {URL & { fromCurrentScript?: boolean }} parsedURL
* @returns {string}
*/
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 format({
protocol: socketURLProtocol,
auth: socketURLAuth,
hostname: socketURLHostname,
port: socketURLPort,
pathname: socketURLPathname,
slashes: true
});
}
export default createSocketURL;

View File

@ -0,0 +1,24 @@
/**
* @returns {string}
*/
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 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.");
}
export default getCurrentScriptSource;

View File

@ -0,0 +1,35 @@
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
* @returns {void}
*/
function setLogLevel(level) {
logger.configureDefaultLogger({
level: level
});
}
setLogLevel(defaultLevel);
var log = logger.getLogger(name);
var logEnabledFeatures = function logEnabledFeatures(features) {
var enabledFeatures = Object.keys(features);
if (!features || enabledFeatures.length === 0) {
return;
}
var logString = "Server started:";
// Server started: Hot Module Replacement enabled, Live Reloading enabled, Overlay disabled.
for (var i = 0; i < enabledFeatures.length; i++) {
var key = enabledFeatures[i];
logString += " ".concat(key, " ").concat(features[key] ? "enabled" : "disabled", ",");
}
// replace last comma with a period
logString = logString.slice(0, -1).concat(".");
log.info(logString);
};
export { log, logEnabledFeatures, setLogLevel };

View File

@ -0,0 +1,36 @@
import getCurrentScriptSource from "./getCurrentScriptSource.js";
/**
* @param {string} resourceQuery
* @returns {{ [key: string]: string | boolean }}
*/
function parseURL(resourceQuery) {
/** @type {{ [key: string]: string }} */
var options = {};
if (typeof resourceQuery === "string" && resourceQuery !== "") {
var searchParams = resourceQuery.slice(1).split("&");
for (var i = 0; i < searchParams.length; i++) {
var pair = searchParams[i].split("=");
options[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 (error) {
// URL parsing failed, do nothing.
// We will still proceed to see if we can recover using `resourceQuery`
}
if (scriptSourceURL) {
options = scriptSourceURL;
options.fromCurrentScript = true;
}
}
return options;
}
export default parseURL;

View File

@ -0,0 +1,63 @@
import hotEmitter from "webpack/hot/emitter.js";
import { log } from "./log.js";
/** @typedef {import("../index").Options} Options
/** @typedef {import("../index").Status} Status
/**
* @param {Options} options
* @param {Status} status
*/
function reloadApp(_ref, status) {
var hot = _ref.hot,
liveReload = _ref.liveReload;
if (status.isUnloading) {
return;
}
var currentHash = status.currentHash,
previousHash = status.previousHash;
var isInitial = currentHash.indexOf( /** @type {string} */previousHash) >= 0;
if (isInitial) {
return;
}
/**
* @param {Window} rootWindow
* @param {number} intervalId
*/
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...");
hotEmitter.emit("webpackHotUpdate", status.currentHash);
if (typeof self !== "undefined" && self.window) {
// broadcast update to window
self.postMessage("webpackHotUpdate".concat(status.currentHash), "*");
}
}
// allow refreshing the page only if liveReload isn't disabled
else if (liveReload && allowToLiveReload) {
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);
}
}
});
}
}
export default reloadApp;

View File

@ -0,0 +1,16 @@
/* global __resourceQuery WorkerGlobalScope */
// Send messages to the outside, so plugins can consume it.
/**
* @param {string} type
* @param {any} [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;

View File

@ -0,0 +1,18 @@
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
* @return {string}
*/
function stripAnsi(string) {
if (typeof string !== "string") {
throw new TypeError("Expected a `string`, got `".concat(typeof string, "`"));
}
return string.replace(ansiRegex, "");
}
export default stripAnsi;