完成中转仓管理

This commit is contained in:
xuqiuyun
2025-12-08 15:24:43 +08:00
parent e968fcf52a
commit 620975c04d
981 changed files with 154245 additions and 83 deletions

View File

@@ -0,0 +1,6 @@
import { Plugin } from '../../types';
/**
* Subscribe to {@link https://www.npmjs.com/package/http-proxy#listening-for-proxy-events http-proxy error events} to prevent server from crashing.
* Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
*/
export declare const debugProxyErrorsPlugin: Plugin;

View File

@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.debugProxyErrorsPlugin = void 0;
const debug_1 = require("../../debug");
const debug = debug_1.Debug.extend('debug-proxy-errors-plugin');
/**
* Subscribe to {@link https://www.npmjs.com/package/http-proxy#listening-for-proxy-events http-proxy error events} to prevent server from crashing.
* Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
*/
const debugProxyErrorsPlugin = (proxyServer) => {
/**
* http-proxy doesn't handle any errors by default (https://github.com/http-party/node-http-proxy#listening-for-proxy-events)
* Prevent server from crashing when http-proxy errors (uncaught errors)
*/
proxyServer.on('error', (error, req, res, target) => {
debug(`http-proxy error event: \n%O`, error);
});
proxyServer.on('proxyReq', (proxyReq, req, socket) => {
socket.on('error', (error) => {
debug('Socket error in proxyReq event: \n%O', error);
});
});
/**
* Fix SSE close events
* @link https://github.com/chimurai/http-proxy-middleware/issues/678
* @link https://github.com/http-party/node-http-proxy/issues/1520#issue-877626125
*/
proxyServer.on('proxyRes', (proxyRes, req, res) => {
res.on('close', () => {
if (!res.writableEnded) {
debug('Destroying proxyRes in proxyRes close event');
proxyRes.destroy();
}
});
});
/**
* Fix crash when target server restarts
* https://github.com/chimurai/http-proxy-middleware/issues/476#issuecomment-746329030
* https://github.com/webpack/webpack-dev-server/issues/1642#issuecomment-790602225
*/
proxyServer.on('proxyReqWs', (proxyReq, req, socket) => {
socket.on('error', (error) => {
debug('Socket error in proxyReqWs event: \n%O', error);
});
});
proxyServer.on('open', (proxySocket) => {
proxySocket.on('error', (error) => {
debug('Socket error in open event: \n%O', error);
});
});
proxyServer.on('close', (req, socket, head) => {
socket.on('error', (error) => {
debug('Socket error in close event: \n%O', error);
});
});
// https://github.com/webpack/webpack-dev-server/issues/1642#issuecomment-1103136590
proxyServer.on('econnreset', (error, req, res, target) => {
debug(`http-proxy econnreset event: \n%O`, error);
});
};
exports.debugProxyErrorsPlugin = debugProxyErrorsPlugin;

View File

@@ -0,0 +1,2 @@
import { Plugin } from '../../types';
export declare const errorResponsePlugin: Plugin;

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorResponsePlugin = void 0;
const status_code_1 = require("../../status-code");
function isResponseLike(obj) {
return obj && typeof obj.writeHead === 'function';
}
function isSocketLike(obj) {
return obj && typeof obj.write === 'function' && !('writeHead' in obj);
}
const errorResponsePlugin = (proxyServer, options) => {
proxyServer.on('error', (err, req, res, target) => {
// Re-throw error. Not recoverable since req & res are empty.
if (!req && !res) {
throw err; // "Error: Must provide a proper URL as target"
}
if (isResponseLike(res)) {
if (!res.headersSent) {
const statusCode = (0, status_code_1.getStatusCode)(err.code);
res.writeHead(statusCode);
}
const host = req.headers && req.headers.host;
res.end(`Error occurred while trying to proxy: ${host}${req.url}`);
}
else if (isSocketLike(res)) {
res.destroy();
}
});
};
exports.errorResponsePlugin = errorResponsePlugin;

View File

@@ -0,0 +1,4 @@
export * from './debug-proxy-errors-plugin';
export * from './error-response-plugin';
export * from './logger-plugin';
export * from './proxy-events';

View File

@@ -0,0 +1,20 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./debug-proxy-errors-plugin"), exports);
__exportStar(require("./error-response-plugin"), exports);
__exportStar(require("./logger-plugin"), exports);
__exportStar(require("./proxy-events"), exports);

View File

@@ -0,0 +1,2 @@
import { Plugin } from '../../types';
export declare const loggerPlugin: Plugin;

View File

@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loggerPlugin = void 0;
const url_1 = require("url");
const logger_1 = require("../../logger");
const logger_plugin_1 = require("../../utils/logger-plugin");
const loggerPlugin = (proxyServer, options) => {
const logger = (0, logger_1.getLogger)(options);
proxyServer.on('error', (err, req, res, target) => {
const hostname = req?.headers?.host;
const requestHref = `${hostname}${req?.url}`;
const targetHref = `${target?.href}`; // target is undefined when websocket errors
const errorMessage = '[HPM] Error occurred while proxying request %s to %s [%s] (%s)';
const errReference = 'https://nodejs.org/api/errors.html#errors_common_system_errors'; // link to Node Common Systems Errors page
logger.error(errorMessage, requestHref, targetHref, err.code || err, errReference);
});
/**
* Log request and response
* @example
* ```shell
* [HPM] GET /users/ -> http://jsonplaceholder.typicode.com/users/ [304]
* ```
*/
proxyServer.on('proxyRes', (proxyRes, req, res) => {
// BrowserSync uses req.originalUrl
// Next.js doesn't have req.baseUrl
const originalUrl = req.originalUrl ?? `${req.baseUrl || ''}${req.url}`;
// construct targetUrl
let target;
try {
const port = (0, logger_plugin_1.getPort)(proxyRes.req?.agent?.sockets);
const obj = {
protocol: proxyRes.req.protocol,
host: proxyRes.req.host,
pathname: proxyRes.req.path,
};
target = new url_1.URL(`${obj.protocol}//${obj.host}${obj.pathname}`);
if (port) {
target.port = port;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
}
catch (err) {
// nock issue (https://github.com/chimurai/http-proxy-middleware/issues/1035)
// fallback to old implementation (less correct - without port)
target = new url_1.URL(options.target);
target.pathname = proxyRes.req.path;
}
const targetUrl = target.toString();
const exchange = `[HPM] ${req.method} ${originalUrl} -> ${targetUrl} [${proxyRes.statusCode}]`;
logger.info(exchange);
});
/**
* When client opens WebSocket connection
*/
proxyServer.on('open', (socket) => {
logger.info('[HPM] Client connected: %o', socket.address());
});
/**
* When client closes WebSocket connection
*/
proxyServer.on('close', (req, proxySocket, proxyHead) => {
logger.info('[HPM] Client disconnected: %o', proxySocket.address());
});
};
exports.loggerPlugin = loggerPlugin;

View File

@@ -0,0 +1,22 @@
import { Plugin } from '../../types';
/**
* Implements option.on object to subscribe to http-proxy events.
*
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {},
* proxyReq: (proxyReq, req, res, options) => {},
* proxyReqWs: (proxyReq, req, socket, options) => {},
* proxyRes: (proxyRes, req, res) => {},
* open: (proxySocket) => {},
* close: (proxyRes, proxySocket, proxyHead) => {},
* start: (req, res, target) => {},
* end: (req, res, proxyRes) => {},
* econnreset: (error, req, res, target) => {},
* }
* });
* ```
*/
export declare const proxyEventsPlugin: Plugin;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.proxyEventsPlugin = void 0;
const debug_1 = require("../../debug");
const function_1 = require("../../utils/function");
const debug = debug_1.Debug.extend('proxy-events-plugin');
/**
* Implements option.on object to subscribe to http-proxy events.
*
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {},
* proxyReq: (proxyReq, req, res, options) => {},
* proxyReqWs: (proxyReq, req, socket, options) => {},
* proxyRes: (proxyRes, req, res) => {},
* open: (proxySocket) => {},
* close: (proxyRes, proxySocket, proxyHead) => {},
* start: (req, res, target) => {},
* end: (req, res, proxyRes) => {},
* econnreset: (error, req, res, target) => {},
* }
* });
* ```
*/
const proxyEventsPlugin = (proxyServer, options) => {
Object.entries(options.on || {}).forEach(([eventName, handler]) => {
debug(`register event handler: "${eventName}" -> "${(0, function_1.getFunctionName)(handler)}"`);
proxyServer.on(eventName, handler);
});
};
exports.proxyEventsPlugin = proxyEventsPlugin;