feat: Passwordless cross-device authentication

- Arkitektur: docs/auth/passwordless-architecture.md
- Backend: iom/quixzoom-auth-service/ (FastAPI + Redis)
- Webb: quixzoom-market-pages/se/login/ (QR-kod + polling)
- App: iom/quixzoom-app/src/features/auth/ (push + deep links)

Flöde: QR-kod → app-godkännande → webb-inloggad
This commit is contained in:
Bernt
2026-07-07 07:11:50 +00:00
parent 4aa984ad74
commit 6989a98d75
61843 changed files with 5491611 additions and 872231 deletions
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Steven Chim
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.
+671
View File
@@ -0,0 +1,671 @@
# http-proxy-middleware
[![GitHub Workflow Status (with branch)](https://img.shields.io/github/actions/workflow/status/chimurai/http-proxy-middleware/ci.yml?branch=master&logo=github-actions&logoColor=white&style=flat-square)](https://github.com/chimurai/http-proxy-middleware/actions/workflows/ci.yml?query=branch%3Amaster)
[![Coveralls](https://img.shields.io/coveralls/chimurai/http-proxy-middleware.svg?style=flat-square&logo=coveralls)](https://coveralls.io/r/chimurai/http-proxy-middleware)
[![Known Vulnerabilities](https://snyk.io/test/github/chimurai/http-proxy-middleware/badge.svg)](https://snyk.io/test/github/chimurai/http-proxy-middleware)
[![npm](https://img.shields.io/npm/v/http-proxy-middleware?color=%23CC3534&style=flat-square&logo=npm)](https://www.npmjs.com/package/http-proxy-middleware)
Node.js proxying made simple. Configure proxy middleware with ease for [connect](https://github.com/senchalabs/connect), [express](https://github.com/expressjs/express), [next.js](https://github.com/vercel/next.js), [hono](https://github.com/honojs/hono) and [many more](#compatible-servers).
Powered by [`httpxy`](https://github.com/unjs/httpxy). A maintained version of [http-proxy](https://github.com/http-party/node-http-proxy).
## ⚠️ Note <!-- omit in toc -->
This page is showing documentation for version **v4.x.x** ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))
For older documentation:
- [v3.0.5](https://github.com/chimurai/http-proxy-middleware/tree/v3.0.5#readme)
- [v2.0.4](https://github.com/chimurai/http-proxy-middleware/tree/v2.0.4#readme)
- [v0.21.0](https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme)
## TL;DR <!-- omit in toc -->
Proxy `/api` requests to `http://www.example.org`
:bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based).
```typescript
// typescript
import express from 'express';
import type { NextFunction, Request, Response } from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import type { Filter, Options, RequestHandler } from 'http-proxy-middleware';
const app = express();
const proxyMiddleware = createProxyMiddleware<Request, Response>({
target: 'http://www.example.org/api',
changeOrigin: true,
});
app.use('/api', proxyMiddleware);
app.listen(3000);
// proxy and keep the same base path "/api"
// http://127.0.0.1:3000/api/foo/bar -> http://www.example.org/api/foo/bar
```
_All_ `httpxy` [options](https://github.com/unjs/httpxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options).
## Table of Contents <!-- omit in toc -->
<!-- // spell-checker:disable -->
- [Install](#install)
- [Basic usage](#basic-usage)
- [Express Server Example](#express-server-example)
- [app.use(path, proxy)](#appusepath-proxy)
- [Options](#options)
- [`pathFilter` (string, \[\]string, glob, \[\]glob, function)](#pathfilter-string-string-glob-glob-function)
- [`pathRewrite` (object/function)](#pathrewrite-objectfunction)
- [`router` (object/function)](#router-objectfunction)
- [`plugins` (Array)](#plugins-array)
- [`ejectPlugins` (boolean) default: `false`](#ejectplugins-boolean-default-false)
- [`definePlugin` helper](#defineplugin-helper)
- [`logger` (Object)](#logger-object)
- [`httpxy` events](#httpxy-events)
- [`httpxy` options](#httpxy-options)
- [WebSocket](#websocket)
- [External WebSocket upgrade](#external-websocket-upgrade)
- [Intercept and manipulate requests](#intercept-and-manipulate-requests)
- [Intercept and manipulate responses](#intercept-and-manipulate-responses)
- [Node.js 17+: ECONNREFUSED issue with IPv6 and localhost (#705)](#nodejs-17-econnrefused-issue-with-ipv6-and-localhost-705)
- [Debugging](#debugging)
- [Working examples](#working-examples)
- [Recipes](#recipes)
- [Compatible servers](#compatible-servers)
- [Tests](#tests)
- [Changelog](#changelog)
- [License](#license)
<!-- // spell-checker:enable -->
## Install
```shell
npm install --save-dev http-proxy-middleware
```
## Basic usage
Create and configure a proxy middleware with: `createProxyMiddleware(config)`.
```javascript
import { createProxyMiddleware } from 'http-proxy-middleware';
const apiProxy = createProxyMiddleware({
target: 'http://www.example.org',
changeOrigin: true,
});
// 'apiProxy' is now ready to be used as middleware in a server.
```
- **options.target**: target host to proxy to. _(protocol + host)_
- **options.changeOrigin**: for virtual hosted sites
- see full list of [`http-proxy-middleware` configuration options](#options)
## Express Server Example
An example with `express` server.
```javascript
// include dependencies
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
const app = express();
// create the proxy
/** @type {import('http-proxy-middleware').RequestHandler<import('express').Request, import('express').Response>} */
const exampleProxy = createProxyMiddleware({
target: 'http://www.example.org/api', // target host with the same base path
changeOrigin: true, // needed for virtual hosted sites
});
// mount `exampleProxy` in web server
app.use('/api', exampleProxy);
app.listen(3000);
```
### app.use(path, proxy)
If you want to use the server's `app.use` `path` parameter to match requests.
Use `pathFilter` option to further include/exclude requests which you want to proxy.
```javascript
app.use(
createProxyMiddleware({
target: 'http://www.example.org/api',
changeOrigin: true,
pathFilter: '/api/proxy-only-this-path',
}),
);
```
`app.use` documentation:
- express: <http://expressjs.com/en/4x/api.html#app.use>
- connect: <https://github.com/senchalabs/connect#mount-middleware>
- polka: <https://github.com/lukeed/polka#usebase-fn>
## Options
http-proxy-middleware options:
### `pathFilter` (string, []string, glob, []glob, function)
Narrow down which requests should be proxied. The `path` used for filtering is the `request.url` pathname. In Express, this is the `path` relative to the mount-point of the proxy.
- **path matching**
- `createProxyMiddleware({...})` - matches any path, all requests will be proxied when `pathFilter` is not configured.
- `createProxyMiddleware({ pathFilter: '/api', ...})` - matches paths starting with `/api`
- **multiple path matching**
- `createProxyMiddleware({ pathFilter: ['/api', '/ajax', '/someotherpath'], ...})`
- **wildcard path matching**
For fine-grained control you can use wildcard matching. Glob pattern matching is done by _micromatch_. Visit [micromatch](https://www.npmjs.com/package/micromatch) or [glob](https://www.npmjs.com/package/glob) for more globbing examples.
- `createProxyMiddleware({ pathFilter: '**', ...})` matches any path, all requests will be proxied.
- `createProxyMiddleware({ pathFilter: '**/*.html', ...})` matches any path which ends with `.html`
- `createProxyMiddleware({ pathFilter: '/*.html', ...})` matches paths directly under path-absolute
- `createProxyMiddleware({ pathFilter: '/api/**/*.html', ...})` matches requests ending with `.html` in the path of `/api`
- `createProxyMiddleware({ pathFilter: ['/api/**', '/ajax/**'], ...})` combine multiple patterns
- `createProxyMiddleware({ pathFilter: ['/api/**', '!**/bad.json'], ...})` exclusion
**Note**: In multiple path matching, you cannot use string paths and wildcard paths together.
- **custom matching**
For full control you can provide a custom function to determine which requests should be proxied or not.
```javascript
/**
* @return {Boolean}
*/
const pathFilter = function (path, req) {
return path.match('^/api') && req.method === 'GET';
};
const apiProxy = createProxyMiddleware({
target: 'http://www.example.org',
pathFilter: pathFilter,
});
```
### `pathRewrite` (object/function)
Rewrite target's url path. Object-keys will be used as _RegExp_ to match paths.
```javascript
// rewrite path
pathRewrite: {'^/old/api' : '/new/api'}
// remove path
pathRewrite: {'^/remove/api' : ''}
// add base path
pathRewrite: {'^/' : '/basepath/'}
// custom rewriting
pathRewrite: function (path, req, res, options) { return path.replace('/api', '/base/api') }
// custom rewriting, returning Promise
pathRewrite: async function (path, req, res, options) {
const should_add_something = await httpRequestToDecideSomething(path);
if (should_add_something) path += "something";
return path;
}
// `res` is undefined in WebSocket upgrade flows.
```
### `router` (object/function)
Re-target `option.target` for specific requests.
```javascript
// Use `host` and/or `path` to match requests. First match will be used.
// The order of the configuration matters.
router: {
'integration.localhost:3000' : 'http://127.0.0.1:8001', // host only
'staging.localhost:3000' : 'http://127.0.0.1:8002', // host only
'localhost:3000/api' : 'http://127.0.0.1:8003', // host + path
'/rest' : 'http://127.0.0.1:8004' // path only
}
// Custom router function (string target)
router: function(req, res, options) {
return 'http://127.0.0.1:8004';
}
// Custom router function (target object)
router: function(req, res, options) {
return {
protocol: 'https:', // The : is required
host: '127.0.0.1',
port: 8004
};
}
// Asynchronous router function which returns promise
router: async function(req, res, options) {
const url = await doSomeIO();
return url;
}
// NOTE: `res` is undefined in WebSocket upgrade flows.
```
### `plugins` (Array)
```js
const simpleRequestLogger = (proxyServer, options) => {
proxyServer.on('proxyReq', (proxyReq, req, res) => {
console.log(`[HPM] [${req.method}] ${req.url}`); // outputs: [HPM] GET /users
});
},
const config = {
target: `http://example.org`,
changeOrigin: true,
plugins: [simpleRequestLogger],
};
```
### `ejectPlugins` (boolean) default: `false`
If you're not satisfied with the pre-configured plugins, you can eject them by configuring `ejectPlugins: true`.
NOTE: register your own error handlers to prevent server from crashing.
```js
// eject default plugins and manually add them back
import {
debugProxyErrorsPlugin, // subscribe to proxy errors to prevent server from crashing
errorResponsePlugin, // return 5xx response on proxy error
loggerPlugin, // log proxy events to a logger (ie. console)
proxyEventsPlugin, // implements the "on:" option
} from 'http-proxy-middleware';
createProxyMiddleware({
target: `http://example.org`,
changeOrigin: true,
ejectPlugins: true,
plugins: [debugProxyErrorsPlugin, loggerPlugin, errorResponsePlugin, proxyEventsPlugin],
});
```
## `definePlugin` helper
Create your own `http-proxy-middleware` plugin.
(Default plugins are created with `definePlugin`)
```ts
import { createProxyMiddleware, definePlugin } from 'http-proxy-middleware';
const myPlugin = definePlugin((proxyServer, options) => {
// plugin implementation
});
// use configure and use plugin
createProxyMiddleware({
target: `http://example.org`,
plugins: [myPlugin],
});
```
### `logger` (Object)
Configure a logger to output information from http-proxy-middleware: ie. `console`, `winston`, `pino`, `bunyan`, `log4js`, etc...
Only `info`, `warn`, `error` are used internally for compatibility across different loggers.
If you use `winston`, make sure to enable interpolation: <https://github.com/winstonjs/winston#string-interpolation>
See also logger recipes ([recipes/logger.md](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md)) for more details.
```javascript
createProxyMiddleware({
logger: console,
});
```
## `httpxy` events
Subscribe to [httpxy events](https://github.com/unjs/httpxy#events) with the `on` option:
```js
createProxyMiddleware({
target: 'http://www.example.org',
on: {
proxyReq: (proxyReq, req, res) => {
/* handle proxyReq */
},
proxyRes: (proxyRes, req, res) => {
/* handle proxyRes */
},
error: (err, req, res) => {
/* handle error */
},
},
});
```
- **option.on.error**: function, subscribe to httpxy's `error` event for custom error handling.
```javascript
function onError(err, req, res, target) {
res.writeHead(500, {
'Content-Type': 'text/plain',
});
res.end('Something went wrong. And we are reporting a custom error message.');
}
```
- **option.on.proxyRes**: function, subscribe to httpxy's `proxyRes` event.
```javascript
function onProxyRes(proxyRes, req, res) {
proxyRes.headers['x-added'] = 'foobar'; // add new header to response
delete proxyRes.headers['x-removed']; // remove header from response
}
```
- **option.on.proxyReq**: function, subscribe to httpxy's `proxyReq` event.
```javascript
function onProxyReq(proxyReq, req, res) {
// add custom header to request
proxyReq.setHeader('x-added', 'foobar');
// or log the req
}
```
- **option.on.proxyReqWs**: function, subscribe to httpxy's `proxyReqWs` event.
```javascript
function onProxyReqWs(proxyReq, req, socket, options, head) {
// add custom header
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
}
```
- **option.on.open**: function, subscribe to httpxy's `open` event.
```javascript
function onOpen(proxySocket) {
// listen for messages coming FROM the target here
proxySocket.on('data', hybridParseAndLogMessage);
}
```
- **option.on.close**: function, subscribe to httpxy's `close` event.
```javascript
function onClose(res, socket, head) {
// view disconnected websocket connections
console.log('Client disconnected');
}
```
## `httpxy` options
The following options are provided by the underlying [httpxy](https://github.com/unjs/httpxy#options) library.
- **option.target**: url string to be parsed with the url module
- **option.forward**: url string to be parsed with the url module
- **option.agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)
- **option.ssl**: object to be passed to https.createServer()
- **option.ws**: true/false: if you want to proxy websockets
- **option.xfwd**: true/false, adds x-forward headers
- **option.secure**: true/false, if you want to verify the SSL Certs
- **option.toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)
- **option.prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
- **option.ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
- **option.localAddress** : Local interface string to bind for outgoing connections
- **option.changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL
- **option.preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key
- **option.auth** : Basic authentication i.e. 'user:password' to compute an Authorization header.
- **option.hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects.
- **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
- **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.
- **option.cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
- `false` (default): disable cookie rewriting
- String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
- Object: mapping of domains to new domains, use `"*"` to match all domains.
For example keep one domain unchanged, rewrite one domain and remove other domains:
```jsonc
cookieDomainRewrite: {
"unchanged.domain": "unchanged.domain",
"old.domain": "new.domain",
"*": ""
}
```
- **option.cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:
- `false` (default): disable cookie rewriting
- String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
- Object: mapping of paths to new paths, use `"*"` to match all paths.
For example, to keep one path unchanged, rewrite one path and remove other paths:
```jsonc
cookiePathRewrite: {
"/unchanged.path/": "/unchanged.path/",
"/old.path/": "/new.path/",
"*": ""
}
```
- **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}`)
- **option.proxyTimeout**: timeout (in millis) when proxy receives no response from target
- **option.timeout**: timeout (in millis) for incoming requests
- **option.followRedirects**: true/false, Default: false - specify whether you want to follow redirects
- **option.selfHandleResponse** true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the `proxyRes` event
- **option.buffer**: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:
```javascript
import { createProxyServer } from 'httpxy';
import streamify from 'stream-array';
const proxy = createProxyServer();
export default function proxyWithBody(req, res, next) {
proxy.web(
req,
res,
{
target: 'http://127.0.0.1:4003/',
buffer: streamify(req.rawBody),
},
next,
);
}
```
## WebSocket
See [recipes/websocket.md](recipes/websocket.md) for more examples.
```javascript
// verbose api
createProxyMiddleware({ pathFilter: '/', target: 'http://echo.websocket.org', ws: true });
```
### External WebSocket upgrade
In the previous WebSocket examples, http-proxy-middleware relies on an initial HTTP request in order to listen to the HTTP `upgrade` event. If you need to proxy WebSockets without the initial HTTP request, you can subscribe to the server's HTTP `upgrade` event manually.
When the same middleware instance is attached to multiple servers and `ws: true` is used, each server needs its own initial HTTP request before upgrades are auto-subscribed.
```javascript
const wsProxy = createProxyMiddleware({ target: 'ws://echo.websocket.org', changeOrigin: true });
const app = express();
app.use(wsProxy);
const server = app.listen(3000);
server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade'
```
## Intercept and manipulate requests
Intercept requests from downstream by defining `onProxyReq` in `createProxyMiddleware`.
Currently the only pre-provided request interceptor is `fixRequestBody`, which is used to fix proxied POST requests when `bodyParser` is applied before this middleware.
Example:
```javascript
import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';
const proxy = createProxyMiddleware({
/**
* Fix bodyParser
**/
on: {
proxyReq: fixRequestBody,
},
});
```
## Intercept and manipulate responses
Intercept responses from upstream with `responseInterceptor`. (Make sure to set `selfHandleResponse: true`)
Responses which are compressed with `brotli`, `gzip` and `deflate` will be decompressed automatically. The response will be returned as `buffer` ([docs](https://nodejs.org/api/buffer.html)) which you can manipulate.
With `buffer`, response manipulation is not limited to text responses (html/css/js, etc...); image manipulation will be possible too. ([example](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md#manipulate-image-response))
NOTE: `responseInterceptor` disables streaming of target's response.
Example:
```javascript
import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
const proxy = createProxyMiddleware({
/**
* IMPORTANT: avoid res.end being called automatically
**/
selfHandleResponse: true, // res.end() will be called internally by responseInterceptor()
/**
* Intercept response and replace 'Hello' with 'Goodbye'
**/
on: {
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
const response = responseBuffer.toString('utf8'); // convert buffer to string
return response.replace('Hello', 'Goodbye'); // manipulate response and return the result
}),
},
});
```
Check out [interception recipes](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md) for more examples.
## Node.js 17+: ECONNREFUSED issue with IPv6 and localhost ([#705](https://github.com/chimurai/http-proxy-middleware/issues/705))
Node.js 17+ no longer prefers IPv4 over IPv6 for DNS lookups.
E.g. It's **not** guaranteed that `localhost` will be resolved to `127.0.0.1` it might just as well be `::1` (or some other IP address).
If your target server only accepts IPv4 connections, trying to proxy to `localhost` will fail if resolved to `::1` (IPv6).
Ways to solve it:
- Change `target: "http://localhost"` to `target: "http://127.0.0.1"` (IPv4).
- Change the target server to (also) accept IPv6 connections.
- Add this flag when running `node`: `node index.js --dns-result-order=ipv4first`. (Not recommended.)
Additional IPv6 notes:
- Unspecified IPv6 host `http://[::]:port` is normalized to loopback (`::1`) to reach local listeners.
> Note: Theres a thing called [Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs) which means connecting to both IPv4 and IPv6 in parallel, which Node.js doesnt have, but explains why for example `curl` can connect.
## Debugging
Configure the `DEBUG` environment variable enable debug logging.
See [`debug`](https://github.com/debug-js/debug#readme) project for more options.
```shell
DEBUG=http-proxy-middleware* node server.js
$ http-proxy-middleware proxy created +0ms
$ http-proxy-middleware proxying request to target: 'http://www.example.org' +359ms
```
## Working examples
View and play around with [working examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples).
- Browser-Sync ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/browser-sync/index.js))
- express ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/express/index.js))
- connect ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/connect/index.js))
- WebSocket ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/websocket/index.js))
- Response Manipulation ([example source](https://github.com/chimurai/http-proxy-middleware/blob/master/examples/response-interceptor/index.js))
## Recipes
View the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes) for common use cases.
## Compatible servers
`http-proxy-middleware` is compatible with the following servers:
- [connect](https://www.npmjs.com/package/connect)
- [express](https://www.npmjs.com/package/express)
- [hono](https://www.npmjs.com/package/@hono/node-server)
- [next.js](https://www.npmjs.com/package/next)
- [fastify](https://www.npmjs.com/package/fastify)
- [browser-sync](https://www.npmjs.com/package/browser-sync)
- [lite-server](https://www.npmjs.com/package/lite-server)
- [polka](https://github.com/lukeed/polka)
- [grunt-contrib-connect](https://www.npmjs.com/package/grunt-contrib-connect)
- [grunt-browser-sync](https://www.npmjs.com/package/grunt-browser-sync)
- [gulp-connect](https://www.npmjs.com/package/gulp-connect)
- [gulp-webserver](https://www.npmjs.com/package/gulp-webserver)
Sample implementations can be found in the [server recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes/servers.md).
## Tests
Run the test suite:
```bash
# install dependencies
$ yarn
# linting
$ yarn lint
$ yarn lint:fix
# building (compile typescript to js)
$ yarn build
# unit tests
$ yarn test
# code coverage
$ yarn coverage
# check spelling mistakes
$ yarn spellcheck
```
## Changelog
- [View changelog](https://github.com/chimurai/http-proxy-middleware/blob/master/CHANGELOG.md)
## License
The MIT License (MIT)
Copyright (c) 2015-2026 Steven Chim
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options } from './types.js';
export declare function verifyConfig<TReq extends http.IncomingMessage, TRes extends http.ServerResponse>(options: Options<TReq, TRes>): void;
@@ -0,0 +1,6 @@
import { HttpProxyMiddlewareError } from './errors.js';
export function verifyConfig(options) {
if (!options.target && !options.router) {
throw new HttpProxyMiddlewareError('[HPM] Missing "target" option. Example: {target: "http://www.example.org"}', 'ERR_CONFIG_FACTORY_TARGET_MISSING');
}
}
+5
View File
@@ -0,0 +1,5 @@
import createDebug from 'debug';
/**
* Debug instance with the given namespace: http-proxy-middleware
*/
export declare const Debug: createDebug.Debugger;
+5
View File
@@ -0,0 +1,5 @@
import createDebug from 'debug';
/**
* Debug instance with the given namespace: http-proxy-middleware
*/
export const Debug = createDebug('http-proxy-middleware');
+4
View File
@@ -0,0 +1,4 @@
export declare class HttpProxyMiddlewareError extends Error {
code: string;
constructor(message: string, code: string);
}
+15
View File
@@ -0,0 +1,15 @@
export class HttpProxyMiddlewareError extends Error {
code;
constructor(message, code) {
super(message);
// add custom `code` property
// so this can be used in src/plugins/default/error-response-plugin.ts to determine the status code to return
this.code = code;
// set the correct name for the error class
this.name = this.constructor.name;
// maintain proper stack trace (V8 environments)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
@@ -0,0 +1,28 @@
import type { HttpBindings } from '@hono/node-server';
import type { MiddlewareHandler } from 'hono';
import { type Options } from './index.js';
/**
* Creates a Hono middleware that proxies requests using http-proxy-middleware.
*
* @remarks
* This middleware requires Hono to be running on Node.js via `@hono/node-server`.
* It uses `c.env.incoming` and `c.env.outgoing` which are only available with `HttpBindings`.
*
* @experimental This API is experimental and may change without a major version bump.
*
* @example
* ```ts
* import { serve } from '@hono/node-server';
* import { Hono } from 'hono';
* import { createHonoProxyMiddleware } from 'http-proxy-middleware/hono';
*
* const app = new Hono();
* app.use('/api', createHonoProxyMiddleware({ target: 'http://example.com', changeOrigin: true }));
* serve(app);
* ```
*
* @since 4.0.0
*/
export declare function createHonoProxyMiddleware(options: Options): MiddlewareHandler<{
Bindings: HttpBindings;
}>;
@@ -0,0 +1,45 @@
import { createProxyMiddleware } from './index.js';
import { getLogger } from './logger.js';
/**
* Creates a Hono middleware that proxies requests using http-proxy-middleware.
*
* @remarks
* This middleware requires Hono to be running on Node.js via `@hono/node-server`.
* It uses `c.env.incoming` and `c.env.outgoing` which are only available with `HttpBindings`.
*
* @experimental This API is experimental and may change without a major version bump.
*
* @example
* ```ts
* import { serve } from '@hono/node-server';
* import { Hono } from 'hono';
* import { createHonoProxyMiddleware } from 'http-proxy-middleware/hono';
*
* const app = new Hono();
* app.use('/api', createHonoProxyMiddleware({ target: 'http://example.com', changeOrigin: true }));
* serve(app);
* ```
*
* @since 4.0.0
*/
export function createHonoProxyMiddleware(options) {
const proxy = createProxyMiddleware(options);
const logger = getLogger(options);
return (c, next) => {
return new Promise((resolve, reject) => {
proxy(c.env.incoming, c.env.outgoing, (err) => {
if (err) {
reject(err);
}
else {
resolve();
}
});
})
.then(() => next())
.catch((err) => {
logger.error('Proxy error:', err);
return c.text('Proxy Error', 500);
});
};
}
+79
View File
@@ -0,0 +1,79 @@
import type * as http from 'node:http';
import type { NextFunction, Options, RequestHandler } from './types.js';
/**
* Create proxy middleware for Express-like servers. ([list of servers with examples](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md))
*
* @example Basic proxy to a single target.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* changeOrigin: true,
* });
* ```
*
* @example Proxy only matching paths and rewrite the forwarded path.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://localhost:3000',
* pathFilter: '/api',
* pathRewrite: {
* '^/api/': '/',
* },
* });
* ```
*
* @example Native path rewrite by mounting at a route (alternative to `pathRewrite`).
* ```ts
* import express from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const app = express();
* app.use(
* '/users',
* createProxyMiddleware({
* target: 'http://jsonplaceholder.typicode.com/users',
* changeOrigin: true,
* }),
* );
* ```
*
* @example Use framework-specific request/response types (Express).
* ```ts
* import type { Request, Response } from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware<Request, Response>({
* target: 'http://www.example.org/api',
* changeOrigin: true,
* });
* ```
*
* @example Intercept and modify a proxied response body.
* ```ts
* import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* selfHandleResponse: true,
* on: {
* proxyRes: responseInterceptor(async (responseBuffer) => {
* const response = responseBuffer.toString('utf8');
* return response.replace('Hello', 'Goodbye');
* }),
* },
* });
* ```
*
* @see https://github.com/chimurai/http-proxy-middleware/
* @see https://github.com/chimurai/http-proxy-middleware/#basic-usage
* @see https://github.com/chimurai/http-proxy-middleware/#intercept-and-manipulate-responses
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md
*/
export declare function createProxyMiddleware<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse, TNext = NextFunction>(options: Options<TReq, TRes>): RequestHandler<TReq, TRes, TNext>;
+81
View File
@@ -0,0 +1,81 @@
import { HttpProxyMiddleware } from './http-proxy-middleware.js';
/**
* Create proxy middleware for Express-like servers. ([list of servers with examples](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md))
*
* @example Basic proxy to a single target.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* changeOrigin: true,
* });
* ```
*
* @example Proxy only matching paths and rewrite the forwarded path.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://localhost:3000',
* pathFilter: '/api',
* pathRewrite: {
* '^/api/': '/',
* },
* });
* ```
*
* @example Native path rewrite by mounting at a route (alternative to `pathRewrite`).
* ```ts
* import express from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const app = express();
* app.use(
* '/users',
* createProxyMiddleware({
* target: 'http://jsonplaceholder.typicode.com/users',
* changeOrigin: true,
* }),
* );
* ```
*
* @example Use framework-specific request/response types (Express).
* ```ts
* import type { Request, Response } from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware<Request, Response>({
* target: 'http://www.example.org/api',
* changeOrigin: true,
* });
* ```
*
* @example Intercept and modify a proxied response body.
* ```ts
* import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* selfHandleResponse: true,
* on: {
* proxyRes: responseInterceptor(async (responseBuffer) => {
* const response = responseBuffer.toString('utf8');
* return response.replace('Hello', 'Goodbye');
* }),
* },
* });
* ```
*
* @see https://github.com/chimurai/http-proxy-middleware/
* @see https://github.com/chimurai/http-proxy-middleware/#basic-usage
* @see https://github.com/chimurai/http-proxy-middleware/#intercept-and-manipulate-responses
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md
*/
export function createProxyMiddleware(options) {
const { middleware } = new HttpProxyMiddleware(options);
return middleware;
}
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options, Plugin } from './types.js';
export declare function getPlugins<TReq extends http.IncomingMessage, TRes extends http.ServerResponse>(options: Options<TReq, TRes>): Plugin<TReq, TRes>[];
@@ -0,0 +1,10 @@
import { debugProxyErrorsPlugin, errorResponsePlugin, loggerPlugin, proxyEventsPlugin, } from './plugins/default/index.js';
export function getPlugins(options) {
// don't load default errorResponsePlugin if user has specified their own
const maybeErrorResponsePlugin = options.on?.error ? [] : [errorResponsePlugin];
const defaultPlugins = options.ejectPlugins
? [] // no default plugins when ejecting
: [debugProxyErrorsPlugin, proxyEventsPlugin, loggerPlugin, ...maybeErrorResponsePlugin];
const userPlugins = options.plugins ?? [];
return [...defaultPlugins, ...userPlugins];
}
@@ -0,0 +1,12 @@
/**
* HPM_ERR_INVALID_MULTIPART prefixed error code will be used in
* [status-code.ts]({@link ../../status-code.ts}) to return status code 400.
*/
export declare const HPM_ERR_INVALID_MULTIPART = "HPM_ERR_INVALID_MULTIPART";
/**
* stringify FormData data
* @param contentType
* @param data
* @returns
*/
export declare function stringifyFormData(contentType: string, data: object): string;
@@ -0,0 +1,46 @@
import { HttpProxyMiddlewareError } from '../../errors.js';
const CR_OR_LF = /[\r\n]/;
/**
* HPM_ERR_INVALID_MULTIPART prefixed error code will be used in
* [status-code.ts]({@link ../../status-code.ts}) to return status code 400.
*/
export const HPM_ERR_INVALID_MULTIPART = 'HPM_ERR_INVALID_MULTIPART';
/**
* stringify FormData data
* @param contentType
* @param data
* @returns
*/
export function stringifyFormData(contentType, data) {
const boundary = getMultipartBoundary(contentType);
let str = '';
for (const [key, value] of Object.entries(data)) {
const normalizedKey = String(key);
const normalizedValue = String(value);
// Reject potentially dangerous sequences to prevent multipart header/body injection.
validateMultipartField(normalizedKey, normalizedValue, boundary);
str += `--${boundary}\r\nContent-Disposition: form-data; name="${escapeMultipartFieldName(normalizedKey)}"\r\n\r\n${normalizedValue}\r\n`;
}
return str;
}
function getMultipartBoundary(contentType) {
const boundaryMatch = /(?:^|;)\s*boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
// Keep backward-compatible behavior when boundary is omitted: fall back to legacy extraction.
const boundary = (boundaryMatch?.[1] ?? boundaryMatch?.[2] ?? contentType).trim();
if (!boundary || CR_OR_LF.test(boundary)) {
throw new HttpProxyMiddlewareError('[HPM] invalid multipart boundary detected.', `${HPM_ERR_INVALID_MULTIPART}_BOUNDARY`);
}
return boundary;
}
function validateMultipartField(fieldName, fieldValue, boundary) {
const boundaryDelimiter = `--${boundary}`;
if (CR_OR_LF.test(fieldName)) {
throw new HttpProxyMiddlewareError(`[HPM] invalid multipart field name "${fieldName}" detected.`, `${HPM_ERR_INVALID_MULTIPART}_FIELD_NAME`);
}
if (CR_OR_LF.test(fieldValue) || fieldValue.includes(boundaryDelimiter)) {
throw new HttpProxyMiddlewareError(`[HPM] invalid multipart field value for "${fieldName}" detected.`, `${HPM_ERR_INVALID_MULTIPART}_FIELD_VALUE`);
}
}
function escapeMultipartFieldName(fieldName) {
return fieldName.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
@@ -0,0 +1,22 @@
import type * as http from 'node:http';
export type BodyParserLikeRequest = http.IncomingMessage & {
body?: any;
};
/**
* Fix proxied body if bodyParser is involved.
*
* @example
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* on: {
* proxyReq: fixRequestBody,
* }
* });
* ```
*
* Alternative solution without using `fixRequestBody()`: put `http-proxy-middleware` before `bodyParser` in the middleware stack.
*
* @see {@link https://github.com/chimurai/http-proxy-middleware/issues/40 Github issue #40 - POST request body is not proxied}
*/
export declare function fixRequestBody<TReq extends BodyParserLikeRequest = BodyParserLikeRequest>(proxyReq: http.ClientRequest, req: TReq): void;
@@ -0,0 +1,78 @@
import * as querystring from 'node:querystring';
import * as zlib from 'node:zlib';
import { stringifyFormData } from './fix-request-body-utils/stringify-form-data.js';
/**
* Fix proxied body if bodyParser is involved.
*
* @example
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* on: {
* proxyReq: fixRequestBody,
* }
* });
* ```
*
* Alternative solution without using `fixRequestBody()`: put `http-proxy-middleware` before `bodyParser` in the middleware stack.
*
* @see {@link https://github.com/chimurai/http-proxy-middleware/issues/40 Github issue #40 - POST request body is not proxied}
*/
export function fixRequestBody(proxyReq, req) {
// skip fixRequestBody() when req.readableLength not 0 (bodyParser failure)
if (req.readableLength !== 0) {
return;
}
const requestBody = req.body;
if (!requestBody) {
return;
}
const contentType = proxyReq.getHeader('Content-Type');
if (!contentType) {
return;
}
const writeBody = (bodyData) => {
let proxyData = bodyData;
const contentEncoding = String(proxyReq.getHeader('Content-Encoding')).toLowerCase();
switch (contentEncoding) {
case 'br':
proxyData = zlib.brotliCompressSync(proxyData);
break;
case 'deflate':
proxyData = zlib.deflateSync(proxyData);
break;
case 'gzip':
proxyData = zlib.gzipSync(proxyData);
break;
case 'zstd':
proxyData = zlib.zstdCompressSync(proxyData);
break;
}
proxyReq.setHeader('Content-Length', Buffer.byteLength(proxyData));
proxyReq.write(proxyData);
};
try {
// Use if-elseif to prevent multiple writeBody/setHeader calls:
// Error: "Cannot set headers after they are sent to the client"
if (contentType.includes('application/json') || contentType.includes('+json')) {
writeBody(JSON.stringify(requestBody));
}
else if (contentType.includes('application/x-www-form-urlencoded')) {
writeBody(querystring.stringify(requestBody));
}
else if (contentType.includes('multipart/form-data')) {
writeBody(stringifyFormData(contentType, requestBody));
}
else if (contentType.includes('text/plain')) {
writeBody(requestBody);
}
}
catch (error) {
// proxyReq listeners run outside the middleware try/catch path; re-throwing here can bubble as
// an unhandled exception in consumers, so destroy() is used to fail closed through proxy error handling.
proxyReq.destroy(toError(error));
}
}
function toError(error) {
return error instanceof Error ? error : new Error(String(error));
}
@@ -0,0 +1 @@
export * from './public.js';
@@ -0,0 +1 @@
export * from './public.js';
@@ -0,0 +1,2 @@
export { responseInterceptor } from './response-interceptor.js';
export { fixRequestBody } from './fix-request-body.js';
@@ -0,0 +1,2 @@
export { responseInterceptor } from './response-interceptor.js';
export { fixRequestBody } from './fix-request-body.js';
@@ -0,0 +1,27 @@
import type * as http from 'node:http';
type Interceptor<TReq = http.IncomingMessage, TRes = http.ServerResponse> = (buffer: Buffer, proxyRes: http.IncomingMessage, req: TReq, res: TRes) => Promise<Buffer | string>;
/**
* Intercept responses from upstream.
* Automatically decompress (deflate, gzip, brotli, zstd).
* Give developer the opportunity to modify intercepted Buffer and http.ServerResponse
*
* NOTE: must set options.selfHandleResponse=true (prevent automatic call of res.end())
*
* @example
*
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* selfHandleResponse: true, // MUST set selfHandleResponse=true
* on: {
* proxyRes: responseInterceptor(async (buffer, proxyRes, req, res) => {
* // modify intercepted buffer and return modified buffer
* const modifiedBuffer = Buffer.from(buffer.toString().replace(/Example/g, 'Demo'), 'utf8');
* return modifiedBuffer;
* }),
* }
* });
* ```
*/
export declare function responseInterceptor<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(interceptor: Interceptor<TReq, TRes>): (proxyRes: http.IncomingMessage, req: TReq, res: TRes) => Promise<void>;
export {};
@@ -0,0 +1,145 @@
import * as zlib from 'node:zlib';
import { Debug } from '../debug.js';
import { getFunctionName } from '../utils/function.js';
const debug = Debug.extend('response-interceptor');
/**
* Intercept responses from upstream.
* Automatically decompress (deflate, gzip, brotli, zstd).
* Give developer the opportunity to modify intercepted Buffer and http.ServerResponse
*
* NOTE: must set options.selfHandleResponse=true (prevent automatic call of res.end())
*
* @example
*
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* selfHandleResponse: true, // MUST set selfHandleResponse=true
* on: {
* proxyRes: responseInterceptor(async (buffer, proxyRes, req, res) => {
* // modify intercepted buffer and return modified buffer
* const modifiedBuffer = Buffer.from(buffer.toString().replace(/Example/g, 'Demo'), 'utf8');
* return modifiedBuffer;
* }),
* }
* });
* ```
*/
export function responseInterceptor(interceptor) {
return async function proxyResResponseInterceptor(proxyRes, req, res) {
debug('intercept proxy response');
const originalProxyRes = proxyRes;
const chunks = [];
let bufferLength = 0;
// Bodyless responses (HEAD, 1xx, 204, 304) must not be decompressed.
const contentEncoding = isBodylessResponse(proxyRes.statusCode, req.method)
? undefined
: proxyRes.headers['content-encoding'];
// decompress proxy response
const _proxyRes = decompress(proxyRes, contentEncoding);
// collect data chunks and concatenate once on end to avoid repeated full-buffer copies
_proxyRes.on('data', (chunk) => {
const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
chunks.push(chunkBuffer);
bufferLength += chunkBuffer.length; // precalculate Buffer length for slightly better performance on Buffer.concat()
});
_proxyRes.on('end', async () => {
const buffer = Buffer.concat(chunks, bufferLength);
chunks.length = 0; // clear chunks array
bufferLength = 0;
// copy original headers
copyHeaders(proxyRes, res);
// RFC 9110: HEAD and 1xx/204/304 responses do not include content.
// End the response after headers to avoid writing an invalid body.
if (isBodylessResponse(proxyRes.statusCode, req.method)) {
res.end();
return;
}
// call interceptor with intercepted response (buffer)
debug('call interceptor function: %s', getFunctionName(interceptor));
const interceptedBuffer = Buffer.from(await interceptor(buffer, originalProxyRes, req, res));
// set correct content-length (with double byte character support)
debug('set content-length: %s', Buffer.byteLength(interceptedBuffer));
// Buffered responses cannot preserve trailer framing.
// Remove trailer declaration (and transfer-encoding just in case) before setting content-length.
res.removeHeader('trailer');
res.removeHeader('transfer-encoding');
res.setHeader('content-length', Buffer.byteLength(interceptedBuffer));
debug('write intercepted response');
res.write(interceptedBuffer);
res.end();
});
_proxyRes.on('error', (error) => {
chunks.length = 0; // clear chunks array
bufferLength = 0;
res.end(`Error fetching proxied request: ${error.message}`);
});
};
}
function isBodylessResponse(statusCode, method) {
return (method?.toUpperCase() === 'HEAD' ||
(statusCode !== undefined &&
((statusCode >= 100 && statusCode < 200) || statusCode === 204 || statusCode === 304)));
}
/**
* Streaming decompression of proxy response
* source: https://github.com/apache/superset/blob/9773aba522e957ed9423045ca153219638a85d2f/superset-frontend/webpack.proxy-config.js#L116
*/
function decompress(proxyRes, contentEncoding) {
let _proxyRes = proxyRes;
let decompress;
switch (contentEncoding) {
case 'gzip':
decompress = zlib.createGunzip();
break;
case 'br':
decompress = zlib.createBrotliDecompress();
break;
case 'deflate':
decompress = zlib.createInflate();
break;
case 'zstd':
decompress = zlib.createZstdDecompress();
break;
default:
break;
}
if (decompress) {
debug(`decompress proxy response with 'content-encoding': %s`, contentEncoding);
_proxyRes.pipe(decompress);
_proxyRes = decompress;
}
return _proxyRes;
}
/**
* Copy original headers
* https://github.com/apache/superset/blob/9773aba522e957ed9423045ca153219638a85d2f/superset-frontend/webpack.proxy-config.js#L78
*/
function copyHeaders(originalResponse, response) {
debug('copy original response headers');
if (originalResponse.statusCode) {
response.statusCode = originalResponse.statusCode;
}
if (originalResponse.statusMessage) {
response.statusMessage = originalResponse.statusMessage;
}
if (response.setHeader) {
let keys = Object.keys(originalResponse.headers);
// ignore encoding/framing headers that are incompatible with buffered interception
keys = keys.filter((key) => !['content-encoding', 'transfer-encoding', 'trailer'].includes(key));
keys.forEach((key) => {
let value = originalResponse.headers[key];
if (key === 'set-cookie' && value) {
// remove cookie domain
value = Array.isArray(value) ? value : [value];
value = value.map((x) => x.replace(/Domain=[^;]+?/i, ''));
}
response.setHeader(key, value);
});
}
else {
if ('headers' in response) {
response.headers = originalResponse.headers;
}
}
}
@@ -0,0 +1,31 @@
import type * as http from 'node:http';
import type { Options, RequestHandler } from './types.js';
export declare class HttpProxyMiddleware<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
#private;
private wsInternalSubscribedServers;
private activeServers;
private proxyOptions;
private proxy;
private pathRewriter;
private logger;
constructor(options: Options<TReq, TRes>);
middleware: RequestHandler<TReq, TRes>;
private registerPlugins;
private catchUpgradeRequest;
private handleUpgrade;
/**
* Determine whether request should be proxied.
*/
private shouldProxy;
/**
* Apply option.router and option.pathRewrite
* Order matters:
* Router uses original path for routing;
* NOT the modified path, after it has been rewritten by pathRewrite
* @param {Object} req
* @return {Object} proxy options
*/
private prepareProxyRequest;
private applyRouter;
private applyPathRewrite;
}
@@ -0,0 +1,183 @@
import { createProxyServer } from 'httpxy';
import { verifyConfig } from './configuration.js';
import { Debug as debug } from './debug.js';
import { getPlugins } from './get-plugins.js';
import { getLogger } from './logger.js';
import { matchPathFilter } from './path-filter.js';
import { createPathRewriter } from './path-rewriter.js';
import { getTarget } from './router.js';
import { getFunctionName } from './utils/function.js';
import { normalizeIPv6LiteralTargets } from './utils/ipv6.js';
export class HttpProxyMiddleware {
wsInternalSubscribedServers = new WeakSet();
activeServers = new Set();
proxyOptions;
proxy;
pathRewriter;
logger;
constructor(options) {
verifyConfig(options);
this.proxyOptions = options;
this.logger = getLogger(options);
debug(`create proxy server`);
this.proxy = createProxyServer({});
this.registerPlugins(this.proxy, this.proxyOptions);
this.pathRewriter = createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
// https://github.com/chimurai/http-proxy-middleware/issues/19
// expose function to upgrade externally
this.middleware.upgrade = (req, socket, head) => {
const server = this.#getServer(req);
if (server && !this.wsInternalSubscribedServers.has(server)) {
this.handleUpgrade(req, socket, head);
}
};
}
#getServer(req) {
return req.socket?.server;
}
// https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
middleware = (async (req, res, next) => {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
let activeProxyOptions;
try {
// Preparation Phase: Apply router and path rewriter.
activeProxyOptions = await this.prepareProxyRequest(req, res);
// [Smoking Gun] httpxy is inconsistent with error handling:
// 1. If target is missing (here), it emits 'error' but returns a boolean (bypassing our catch/next).
// 2. If a network error occurs (in proxy.web), it rejects the promise but SKIPS emitting 'error'.
// We manually throw here to force Case 1 into the catch block so next(err) is called for Express.
if (!activeProxyOptions.target && !activeProxyOptions.forward) {
throw new Error('Must provide a proper URL as target');
}
}
catch (err) {
next?.(err);
return;
}
try {
// Proxying Phase: Handle the actual web request.
debug(`proxy request to target: %O`, activeProxyOptions.target);
await this.proxy.web(req, res, activeProxyOptions);
}
catch (err) {
// Manually emit 'error' event because httpxy's promise-based API does not emit it automatically.
// This is crucial for backward compatibility with HPM plugins (like error-response-plugin)
// and custom listeners registered via the 'on: { error: ... }' option.
this.proxy.emit('error', err, req, res, activeProxyOptions.target);
next?.(err);
}
}
else {
next?.();
}
/**
* Get the server object to subscribe to server events;
* 'upgrade' for websocket and 'close' for graceful shutdown
*/
const server = this.#getServer(req);
if (server && !this.activeServers.has(server)) {
debug('registering server close listener');
this.activeServers.add(server);
server.on('close', () => {
debug('server close signal received.');
this.activeServers.delete(server);
if (this.activeServers.size > 0) {
debug(`proxy server not closed: ${this.activeServers.size} server(s) still active`);
return;
}
else {
debug('closing proxy server');
this.proxy.close(() => debug('proxy server closed'));
}
});
}
if (this.proxyOptions.ws === true && server) {
// use initial request to access the server object to subscribe to http upgrade event
this.catchUpgradeRequest(server);
}
});
registerPlugins(proxy, options) {
const plugins = getPlugins(options);
plugins.forEach((plugin) => {
debug(`register plugin: "${getFunctionName(plugin)}"`);
plugin(proxy, options);
});
}
catchUpgradeRequest = (server) => {
if (!this.wsInternalSubscribedServers.has(server)) {
debug('subscribing to server upgrade event');
server.on('upgrade', this.handleUpgrade);
this.wsInternalSubscribedServers.add(server);
}
};
handleUpgrade = async (req, socket, head) => {
try {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
// No HTTP response object exists during WebSocket upgrades, so pass undefined.
const activeProxyOptions = await this.prepareProxyRequest(req, undefined);
await this.proxy.ws(req, socket, activeProxyOptions, head);
debug('server upgrade event received. Proxying WebSocket');
}
}
catch (err) {
// This error does not include the URL as the fourth argument as we won't
// have the URL if `this.prepareProxyRequest` throws an error.
this.proxy.emit('error', err, req, socket);
}
};
/**
* Determine whether request should be proxied.
*/
shouldProxy = (pathFilter, req) => {
try {
return matchPathFilter(pathFilter, req.url, req);
}
catch (err) {
debug('Error: matchPathFilter() called with request url: ', `"${req.url}"`);
this.logger.error(err);
return false;
}
};
/**
* Apply option.router and option.pathRewrite
* Order matters:
* Router uses original path for routing;
* NOT the modified path, after it has been rewritten by pathRewrite
* @param {Object} req
* @return {Object} proxy options
*/
prepareProxyRequest = async (req, res) => {
const newProxyOptions = Object.assign({}, this.proxyOptions);
// Apply in order:
// 1. option.router
// 2. option.pathRewrite
await this.applyRouter(req, res, newProxyOptions);
normalizeIPv6LiteralTargets(newProxyOptions);
await this.applyPathRewrite(req, res, this.pathRewriter, newProxyOptions);
return newProxyOptions;
};
// Modify option.target when router present.
applyRouter = async (req, res, options) => {
let newTarget;
if (options.router) {
newTarget = await getTarget(req, res, options);
if (newTarget) {
debug('router new target: "%s"', newTarget);
options.target = newTarget;
}
}
};
// rewrite path
applyPathRewrite = async (req, res, pathRewriter, options) => {
if (req.url && pathRewriter) {
const path = await pathRewriter(req.url, req, res, options);
if (typeof path === 'string') {
debug('pathRewrite new path: %s', path);
req.url = path;
}
else {
debug('pathRewrite: no rewritten path found: %s', req.url);
}
}
};
}
@@ -0,0 +1,10 @@
/**
* Hono-specific API entrypoint.
*
* This is intentionally published as a dedicated subpath (`http-proxy-middleware/hono`)
* so the root package types do not import `hono` / `@hono/node-server`.
*
* Keeping these exports out of the root entrypoint prevents non-Hono consumers from
* getting TypeScript module-resolution errors for optional Hono dependencies.
*/
export { createHonoProxyMiddleware } from './factory-hono.js';
+10
View File
@@ -0,0 +1,10 @@
/**
* Hono-specific API entrypoint.
*
* This is intentionally published as a dedicated subpath (`http-proxy-middleware/hono`)
* so the root package types do not import `hono` / `@hono/node-server`.
*
* Keeping these exports out of the root entrypoint prevents non-Hono consumers from
* getting TypeScript module-resolution errors for optional Hono dependencies.
*/
export { createHonoProxyMiddleware } from './factory-hono.js';
+4
View File
@@ -0,0 +1,4 @@
export * from './factory.js';
export * from './handlers/index.js';
export type { Plugin, Filter, Options, RequestHandler, OnProxyEvent } from './types.js';
export * from './plugins/index.js';
+3
View File
@@ -0,0 +1,3 @@
export * from './factory.js';
export * from './handlers/index.js';
export * from './plugins/index.js';
+2
View File
@@ -0,0 +1,2 @@
import type { Logger, Options } from './types.js';
export declare function getLogger(options: Options): Logger;
+21
View File
@@ -0,0 +1,21 @@
/**
* Compatibility matrix
*
| Library | log | info | warn | error | \<interpolation\> |
|----------|:------|:-------|:------|:--------|:------------------|
| console | ✅ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| bunyan | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| pino | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| winston | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O)^1 |
| log4js | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
*
* ^1: https://github.com/winstonjs/winston#string-interpolation
*/
const noopLogger = {
info: () => { },
warn: () => { },
error: () => { },
};
export function getLogger(options) {
return options.logger || noopLogger;
}
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Filter } from './types.js';
export declare function matchPathFilter<TReq extends http.IncomingMessage = http.IncomingMessage>(pathFilter: Filter<TReq> | undefined, uri: string | undefined, req: http.IncomingMessage): boolean;
@@ -0,0 +1,76 @@
import isGlob from 'is-glob';
import micromatch from 'micromatch';
import { HttpProxyMiddlewareError } from './errors.js';
export function matchPathFilter(pathFilter = '/', uri, req) {
// single path
if (isStringPath(pathFilter)) {
return matchSingleStringPath(pathFilter, uri);
}
// single glob path
if (isGlobPath(pathFilter)) {
return matchSingleGlobPath(pathFilter, uri);
}
// multi path
if (Array.isArray(pathFilter)) {
if (pathFilter.every(isStringPath)) {
return matchMultiPath(pathFilter, uri);
}
if (pathFilter.every(isGlobPath)) {
return matchMultiGlobPath(pathFilter, uri);
}
throw new HttpProxyMiddlewareError('[HPM] Invalid pathFilter. Plain paths (e.g. "/api") can not be mixed with globs (e.g. "/api/**"). Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"].', 'HPM_INVALID_PATH_FILTER_ARRAY_CONFIG');
}
// custom matching
if (typeof pathFilter === 'function') {
const pathname = getUrlPathName(uri);
return Boolean(pathFilter(pathname, req));
}
throw new HttpProxyMiddlewareError('[HPM] Invalid pathFilter. Expecting something like: "/api" or ["/api", "/ajax"]', 'HPM_INVALID_PATH_FILTER_CONFIG');
}
/**
* @param {String} pathFilter '/api'
* @param {String} uri 'http://example.org/api/b/c/d.html'
* @return {Boolean}
*/
function matchSingleStringPath(pathFilter, uri) {
const pathname = getUrlPathName(uri);
return pathname?.indexOf(pathFilter) === 0;
}
function matchSingleGlobPath(pattern, uri) {
const pathname = getUrlPathName(uri);
const matches = micromatch([pathname], pattern);
return matches && matches.length > 0;
}
function matchMultiGlobPath(patternList, uri) {
return matchSingleGlobPath(patternList, uri);
}
/**
* @param {String} pathFilterList ['/api', '/ajax']
* @param {String} uri 'http://example.org/api/b/c/d.html'
* @return {Boolean}
*/
function matchMultiPath(pathFilterList, uri) {
let isMultiPath = false;
for (const context of pathFilterList) {
if (matchSingleStringPath(context, uri)) {
isMultiPath = true;
break;
}
}
return isMultiPath;
}
/**
* Parses URI and returns RFC 3986 path
*
* @param {String} uri from req.url
* @return {String} RFC 3986 path
*/
function getUrlPathName(uri) {
return uri && new URL(uri, 'http://0.0.0.0').pathname;
}
function isStringPath(pathFilter) {
return typeof pathFilter === 'string' && !isGlob(pathFilter);
}
function isGlobPath(pathFilter) {
return isGlob(pathFilter);
}
@@ -0,0 +1,6 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { PathRewriteConfig } from './types.js';
/**
* Create rewrite function, to cache parsed rewrite rules.
*/
export declare function createPathRewriter<TReq extends IncomingMessage = IncomingMessage, TRes extends ServerResponse = ServerResponse>(rewriteConfig: PathRewriteConfig<TReq, TRes> | undefined): ((path: string, req: TReq, res?: TRes | undefined, options?: import("./types.js").Options<TReq, TRes> | undefined) => string | undefined) | ((path: string, req: TReq, res?: TRes | undefined, options?: import("./types.js").Options<TReq, TRes> | undefined) => Promise<string | undefined>) | undefined;
@@ -0,0 +1,59 @@
import isPlainObject from 'is-plain-obj';
import { Debug } from './debug.js';
import { HttpProxyMiddlewareError } from './errors.js';
const debug = Debug.extend('path-rewriter');
/**
* Create rewrite function, to cache parsed rewrite rules.
*/
export function createPathRewriter(rewriteConfig) {
let rulesCache;
if (!isValidRewriteConfig(rewriteConfig)) {
return;
}
if (typeof rewriteConfig === 'function') {
const customRewriteFn = rewriteConfig;
return customRewriteFn;
}
else {
rulesCache = parsePathRewriteRules(rewriteConfig);
return rewritePath;
}
function rewritePath(path) {
let result = path;
for (const rule of rulesCache) {
if (rule.regex.test(path)) {
result = result.replace(rule.regex, rule.value);
debug('rewriting path from "%s" to "%s"', path, result);
break;
}
}
return result;
}
}
function isValidRewriteConfig(rewriteConfig) {
if (typeof rewriteConfig === 'function') {
return true;
}
else if (isPlainObject(rewriteConfig)) {
return Object.keys(rewriteConfig).length !== 0;
}
else if (rewriteConfig === undefined || rewriteConfig === null) {
return false;
}
else {
throw new HttpProxyMiddlewareError('[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function', 'HPM_INVALID_PATH_REWRITER_CONFIG');
}
}
function parsePathRewriteRules(rewriteConfig) {
const rules = [];
if (isPlainObject(rewriteConfig)) {
for (const [key, value] of Object.entries(rewriteConfig)) {
rules.push({
regex: new RegExp(key),
value: value,
});
debug('rewrite rule created: "%s" ~> "%s"', key, value);
}
}
return rules;
}
@@ -0,0 +1,6 @@
import type { Plugin } from '../../types.js';
/**
* Subscribe to {@link https://github.com/unjs/httpxy#events `httpxy` 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;
@@ -0,0 +1,77 @@
import { styleText } from 'node:util';
import { Debug } from '../../debug.js';
import { definePlugin } from '../define-plugin.js';
const debug = Debug.extend('debug-proxy-errors-plugin');
const BODY_PARSER_ERROR_MESSAGE = `[HPM] Connection reset (ECONNRESET) detected with non-empty "req.body" [ERR_HPM.GH40].
This usually means that the POST request body (req.body) was already parsed before reaching the proxy.
When bodyParser runs first, it consumes the request stream, leaving the proxy unable to forward the body data to the target server.
How to fix this issue:
- Option 1: Place the proxy middleware before the bodyParser middleware.
- Option 2: Use 'fixRequestBody()' helper to fix this issue.
For more details, see: https://github.com/chimurai/http-proxy-middleware/issues/40\n`;
function hasParsedBody(req) {
return Boolean(req && req.method === 'POST' && 'body' in req && req.body);
}
/**
* Subscribe to {@link https://github.com/unjs/httpxy#events `httpxy` error events} to prevent server from crashing.
* Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
*/
export const debugProxyErrorsPlugin = definePlugin((proxyServer, options) => {
/**
* The old `http-proxy` doesn't handle any errors by default (https://github.com/http-party/node-http-proxy#listening-for-proxy-events)
* > We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.
* Subscribing to error event to prevent server from crashing
*/
proxyServer.on('error', (error, req, res, target) => {
debug(`httpxy error event: \n%O`, error);
// detect request body (when bodyParser used) and log an error message to help debugging
if (error.code === 'ECONNRESET' && hasParsedBody(req)) {
console.error(styleText('red', BODY_PARSER_ERROR_MESSAGE));
}
});
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(`httpxy econnreset event: \n%O`, error);
});
});
@@ -0,0 +1,2 @@
import type { Plugin } from '../../types.js';
export declare const errorResponsePlugin: Plugin;
@@ -0,0 +1,28 @@
import { getStatusCode } from '../../status-code.js';
import { sanitize } from '../../utils/sanitize.js';
import { definePlugin } from '../define-plugin.js';
function isResponseLike(obj) {
return obj && typeof obj.writeHead === 'function';
}
function isSocketLike(obj) {
return obj && typeof obj.write === 'function' && !('writeHead' in obj);
}
export const errorResponsePlugin = definePlugin((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 = getStatusCode(err.code);
res.writeHead(statusCode);
}
const host = req.headers && req.headers.host;
res.end(`Error occurred while trying to proxy: ${sanitize(host)}${sanitize(req.url)}`);
}
else if (isSocketLike(res)) {
res.destroy();
}
});
});
@@ -0,0 +1,4 @@
export * from './debug-proxy-errors-plugin.js';
export * from './error-response-plugin.js';
export * from './logger-plugin.js';
export * from './proxy-events.js';
@@ -0,0 +1,4 @@
export * from './debug-proxy-errors-plugin.js';
export * from './error-response-plugin.js';
export * from './logger-plugin.js';
export * from './proxy-events.js';
@@ -0,0 +1,2 @@
import type { Plugin } from '../../types.js';
export declare const loggerPlugin: Plugin;
@@ -0,0 +1,57 @@
import { URL } from 'node:url';
import { getLogger } from '../../logger.js';
import { createUrl } from '../../utils/create-url.js';
import { getPort } from '../../utils/logger-plugin.js';
import { definePlugin } from '../define-plugin.js';
export const loggerPlugin = definePlugin((proxyServer, options) => {
const logger = 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 = getPort(proxyRes.req?.agent?.sockets);
const { protocol, host, path } = proxyRes.req;
target = createUrl({ protocol, host, port, path });
}
catch (err) {
// should not error. keeping fallback just in case
console.error('[HPM] Unexpected error while creating target URL', err);
// fallback to old implementation (less correct - without port)
target = new 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());
});
});
@@ -0,0 +1,22 @@
import type { Plugin } from '../../types.js';
/**
* Implements option.on object to subscribe to `httpxy` 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;
@@ -0,0 +1,42 @@
import { Debug } from '../../debug.js';
import { getFunctionName } from '../../utils/function.js';
import { definePlugin } from '../define-plugin.js';
const debug = Debug.extend('proxy-events-plugin');
/**
* Implements option.on object to subscribe to `httpxy` 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 const proxyEventsPlugin = definePlugin((proxyServer, options) => {
if (!options.on) {
return;
}
// hoist variable here for better typing
let eventName;
// for in provide better typing than Object.entries()
for (eventName in options.on) {
if (Object.prototype.hasOwnProperty.call(options.on, eventName)) {
const handler = options.on[eventName];
if (!handler) {
continue;
}
debug(`register event handler: "${eventName}" -> "${getFunctionName(handler)}"`);
proxyServer.on(eventName, handler);
}
}
});
@@ -0,0 +1,25 @@
import type * as http from 'node:http';
import type { Plugin } from '../types.js';
/**
* Helper function to define a http-proxy-middleware plugin
* @see proxyServer {@link ProxyServer} - proxy server instance to which the plugin is being applied
* @see options {@link Options} - options object passed to `createProxyMiddleware`
*
* @example defining a plugin
* ```js
* export const myPlugin = definePlugin((proxyServer, options) => {
* // plugin implementation
* });
* ```
*
* @example using a plugin
* ```js
* createProxyMiddleware({
* target: 'http://example.com',
* plugins: [myPlugin],
* });
* ```
*
* @since 4.1.0
*/
export declare function definePlugin<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(fn: Plugin<TReq, TRes>): Plugin<TReq, TRes>;
@@ -0,0 +1,25 @@
/**
* Helper function to define a http-proxy-middleware plugin
* @see proxyServer {@link ProxyServer} - proxy server instance to which the plugin is being applied
* @see options {@link Options} - options object passed to `createProxyMiddleware`
*
* @example defining a plugin
* ```js
* export const myPlugin = definePlugin((proxyServer, options) => {
* // plugin implementation
* });
* ```
*
* @example using a plugin
* ```js
* createProxyMiddleware({
* target: 'http://example.com',
* plugins: [myPlugin],
* });
* ```
*
* @since 4.1.0
*/
export function definePlugin(fn) {
return fn;
}
@@ -0,0 +1,2 @@
export * from './define-plugin.js';
export * from './default/index.js';
@@ -0,0 +1,4 @@
// definePlugin()
export * from './define-plugin.js';
// default plugins
export * from './default/index.js';
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options } from './index.js';
export declare function getTarget<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(req: TReq, res: TRes | undefined, config: Options<TReq, TRes>): Promise<import("httpxy").ProxyTarget | undefined>;
+60
View File
@@ -0,0 +1,60 @@
import isPlainObject from 'is-plain-obj';
import { Debug } from './debug.js';
const debug = Debug.extend('router');
export async function getTarget(req, res, config) {
let newTarget;
const router = config.router;
if (isPlainObject(router)) {
newTarget = getTargetFromProxyTable(req, router);
}
else if (typeof router === 'function') {
newTarget = await router(req, res, config);
}
return newTarget;
}
function getTargetFromProxyTable(req, table) {
let result;
const host = req.headers.host ?? '';
const path = req.url ?? '';
for (const [key, value] of Object.entries(table)) {
if (containsPath(key)) {
if (isHostAndPathKey(key)) {
const [keyHost, keyPath] = splitHostAndPathKey(key);
// SECURITY: host+path keys must match exact host + path prefix.
if (host === keyHost && path.startsWith(keyPath)) {
// match 'localhost:3000/api'
result = value;
debug('match: "%s" -> "%s"', key, result);
break;
}
}
else {
if (path.startsWith(key)) {
// match '/api'
result = value;
debug('match: "%s" -> "%s"', key, result);
break;
}
}
}
else {
if (key === host) {
// match 'localhost:3000'
result = value;
debug('match: "%s" -> "%s"', host, result);
break;
}
}
}
return result;
}
function containsPath(v) {
return v.indexOf('/') > -1;
}
function isHostAndPathKey(v) {
return containsPath(v) && !v.startsWith('/');
}
function splitHostAndPathKey(v) {
const firstSlash = v.indexOf('/');
return [v.slice(0, firstSlash), v.slice(firstSlash)];
}
@@ -0,0 +1 @@
export declare function getStatusCode(errorCode: string): number;
@@ -0,0 +1,23 @@
export function getStatusCode(errorCode) {
let statusCode;
if (/HPE_INVALID/.test(errorCode)) {
statusCode = 502;
return statusCode;
}
if (/HPM_ERR_INVALID_MULTIPART_/.test(errorCode)) {
statusCode = 400;
return statusCode;
}
switch (errorCode) {
case 'ECONNRESET':
case 'ENOTFOUND':
case 'ECONNREFUSED':
case 'ETIMEDOUT':
statusCode = 504;
break;
default:
statusCode = 500;
break;
}
return statusCode;
}
+139
View File
@@ -0,0 +1,139 @@
/**
* Based on definition by DefinitelyTyped:
* https://github.com/DefinitelyTyped/DefinitelyTyped/blob/6f529c6c67a447190f86bfbf894d1061e41e07b7/types/http-proxy-middleware/index.d.ts
*/
import type * as http from 'node:http';
import type * as net from 'node:net';
import type { ProxyServer, ProxyServerOptions } from 'httpxy';
export type NextFunction<T = (err?: any) => void> = T;
export interface RequestHandler<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse, TNext = NextFunction> {
(req: TReq, res: TRes, next?: TNext): Promise<void>;
upgrade: (req: TReq, socket: net.Socket, head: Buffer) => void;
}
export type Filter<TReq extends http.IncomingMessage = http.IncomingMessage> = string | string[] | ((pathname: string, req: TReq) => boolean | string | RegExpMatchArray | null);
/**
* @see {@link https://github.com/chimurai/http-proxy-middleware/tree/master#defineplugin-helper `definePlugin()`} to define a http-proxy-middleware plugin.
*/
export interface Plugin<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
(proxyServer: ProxyServer<TReq, TRes>, options: Options<TReq, TRes>): void;
}
export interface OnProxyEvent<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
error?: (err: Error, req: TReq, res: TRes | net.Socket, target?: string | Partial<URL>) => void;
proxyReq?: (proxyReq: http.ClientRequest, req: TReq, res: TRes, options: ProxyServerOptions) => void;
proxyReqWs?: (proxyReq: http.ClientRequest, req: TReq, socket: net.Socket, options: ProxyServerOptions, head: any) => void;
proxyRes?: (proxyRes: TReq, req: TReq, res: TRes) => void | Promise<void>;
open?: (proxySocket: net.Socket) => void;
close?: (proxyRes: TReq, proxySocket: net.Socket, proxyHead: any) => void;
start?: (req: TReq, res: TRes, target: string | Partial<URL>) => void;
end?: (req: TReq, res: TRes, proxyRes: TReq) => void;
econnreset?: (err: Error, req: TReq, res: TRes, target: string | Partial<URL>) => void;
}
export type Logger = Pick<Console, 'info' | 'warn' | 'error'>;
export type PathRewriteConfig<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> = {
[regexp: string]: string;
} | ((path: string, req: TReq,
/** `res` is undefined in WebSocket upgrade flows. */
res?: TRes | undefined, options?: Options<TReq, TRes>) => string | undefined) | ((path: string, req: TReq,
/** `res` is undefined in WebSocket upgrade flows. */
res?: TRes | undefined, options?: Options<TReq, TRes>) => Promise<string | undefined>);
export interface Options<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> extends ProxyServerOptions {
/**
* Narrow down requests to proxy or not.
* Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server.
* Or use the {@link http.IncomingMessage `req`} object for more complex filtering.
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @since v3.0.0
*/
pathFilter?: Filter<TReq>;
/**
* Modify request paths before requests are send to the target.
* @example
* ```js
* createProxyMiddleware({
* pathRewrite: {
* '^/api/old-path': '/api/new-path', // rewrite path
* }
* });
* ```
* @since v0.15.0
* @since v0.21.0 - support `async` function
* @since v4.1.0 - `res` and `options` parameters added to custom function
*
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
*/
pathRewrite?: PathRewriteConfig<TReq, TRes>;
/**
* Access the internal `httpxy` server instance to customize behavior
*
* @example
* ```js
* createProxyMiddleware({
* plugins: [(proxyServer, options) => {
* proxyServer.on('error', (error, req, res) => {
* console.error(error);
* });
* }]
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware#plugins-array
* @since v3.0.0
*/
plugins?: Plugin<TReq, TRes>[];
/**
* Eject pre-configured plugins.
* NOTE: register your own error handlers to prevent server from crashing.
*
* @link https://github.com/chimurai/http-proxy-middleware#ejectplugins-boolean-default-false
* @since v3.0.0
*/
ejectPlugins?: boolean;
/**
* Listen to `httpxy` events
* @see {@link OnProxyEvent} for available events
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {
* console.error(error);
* }
* }
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/proxy-events.md
* @since v3.0.0
*/
on?: OnProxyEvent<TReq, TRes>;
/**
* Dynamically set the {@link Options.target `options.target`}.
*
* @example
* ```js
* createProxyMiddleware({
* router: async (req, res, options) => {
* return 'http://127:0.0.1:3000';
* }
* });
* ```
*
* @since v0.16.0
* @since v4.1.0 - `res` and `options` parameters added to router function signature
*
* NOTE: `res` is undefined in WebSocket upgrade flows.
*
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/router.md
*/
router?: Record<string, ProxyServerOptions['target']> | ((req: TReq, res: TRes | undefined, options: Options<TReq, TRes>) => ProxyServerOptions['target']) | ((req: TReq, res: TRes | undefined, options: Options<TReq, TRes>) => Promise<ProxyServerOptions['target']>);
/**
* Log information from http-proxy-middleware
* @example
* ```js
* createProxyMiddleware({
* logger: console
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md
* @since v3.0.0
*/
logger?: Logger;
}
+1
View File
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,9 @@
import { URL } from 'url';
type CreateUrlParams = {
protocol?: string;
host?: string;
port?: string;
path?: string;
};
export declare function createUrl({ protocol, host, port, path }: CreateUrlParams): URL;
export {};
@@ -0,0 +1,17 @@
import { URL } from 'url';
export function createUrl({ protocol, host, port, path }) {
// wrap IPv6 host in brackets
const ipv6Host = host?.includes(':') ? `[${host}]` : host;
// use fallback values to create a valid URL (protocol: 'undefined:', host: '[::]')
// nock v13 issue: protocol and host are undefined (https://github.com/chimurai/http-proxy-middleware/issues/1035)
// nock v14+ seems to return protocol and host correctly
const base = `${protocol || 'undefined:'}//${ipv6Host || '[::]'}`;
const url = new URL(base);
if (port) {
url.port = port;
}
if (path) {
url.pathname = path;
}
return url;
}
@@ -0,0 +1 @@
export declare function getFunctionName(fn: Function): string;
@@ -0,0 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-function-type */
export function getFunctionName(fn) {
return fn.name || '[anonymous Function]';
}
@@ -0,0 +1,20 @@
import type * as http from 'node:http';
import type { Options } from '../types.js';
/**
* Normalize bracketed IPv6 URL targets into unbracketed host options.
*
* RFC 2732 defines the URL syntax for literal IPv6 addresses as bracketed
* host references (for example `http://[::1]:8080/path` where host is
* `[::1]`).
*
* `httpxy` resolves bracketed hostnames (for example `[::1]`) via DNS,
* which can fail for IPv6 literals. This converts string/URL `target` and
* `forward` values into object form with `hostname: ::1` (brackets removed)
* so the address can be connected directly.
*
* Reference: RFC 2732, Section 2 (Literal IPv6 Address Format in URL's)
* https://www.ietf.org/rfc/rfc2732.txt
*
* The provided options object is mutated in place.
*/
export declare function normalizeIPv6LiteralTargets<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(options: Options<TReq, TRes>): void;
+66
View File
@@ -0,0 +1,66 @@
import { Debug } from '../debug.js';
const debug = Debug.extend('ipv6');
/**
* Normalize bracketed IPv6 URL targets into unbracketed host options.
*
* RFC 2732 defines the URL syntax for literal IPv6 addresses as bracketed
* host references (for example `http://[::1]:8080/path` where host is
* `[::1]`).
*
* `httpxy` resolves bracketed hostnames (for example `[::1]`) via DNS,
* which can fail for IPv6 literals. This converts string/URL `target` and
* `forward` values into object form with `hostname: ::1` (brackets removed)
* so the address can be connected directly.
*
* Reference: RFC 2732, Section 2 (Literal IPv6 Address Format in URL's)
* https://www.ietf.org/rfc/rfc2732.txt
*
* The provided options object is mutated in place.
*/
export function normalizeIPv6LiteralTargets(options) {
options.target = normalizeIPv6ProxyTarget(options.target, 'target');
options.forward = normalizeIPv6ProxyTarget(options.forward, 'forward');
}
function normalizeIPv6ProxyTarget(target, optionName) {
const targetUrl = toTargetUrl(target);
if (targetUrl && isBracketedIPv6Hostname(targetUrl.hostname)) {
const normalizedHostname = normalizeIPv6DestinationHostname(stripBrackets(targetUrl.hostname));
debug('normalized IPv6 "%s" %s', optionName, target);
const auth = targetUrl.username || targetUrl.password
? `${targetUrl.username}:${targetUrl.password}`
: undefined;
return {
hostname: normalizedHostname,
auth,
pathname: targetUrl.pathname,
port: targetUrl.port,
protocol: targetUrl.protocol,
search: targetUrl.search,
};
}
return target;
}
function toTargetUrl(target) {
if (typeof target === 'string') {
return new URL(target);
}
if (target instanceof URL) {
return target;
}
return undefined;
}
function isBracketedIPv6Hostname(hostname) {
return hostname.startsWith('[') && hostname.endsWith(']');
}
function stripBrackets(hostname) {
return hostname.replace(/^\[|\]$/g, '');
}
function normalizeIPv6DestinationHostname(hostname) {
// The unspecified address (::) is not a routable destination for outbound client requests.
// Treat it as loopback so a target like http://[::]:port reaches local IPv6 listeners.
if (hostname === '::') {
debug('normalizing hostname unspecified IPv6 address (::) to loopback (::1)');
return '::1';
}
return hostname;
}
@@ -0,0 +1,7 @@
import type { Agent } from 'node:http';
export type Sockets = Pick<Agent, 'sockets'>;
/**
* Get port from target
* Using proxyRes.req.agent.sockets to determine the target port
*/
export declare function getPort(sockets?: Sockets): string | undefined;
@@ -0,0 +1,7 @@
/**
* Get port from target
* Using proxyRes.req.agent.sockets to determine the target port
*/
export function getPort(sockets) {
return Object.keys(sockets || {})?.[0]?.split(':')[1];
}
@@ -0,0 +1 @@
export declare function sanitize(input: string | undefined): string;
@@ -0,0 +1,3 @@
export function sanitize(input) {
return input?.replace(/[<>]/g, (i) => encodeURIComponent(i)) ?? '';
}
@@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2018-2021 Josh Junon
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.
@@ -0,0 +1,481 @@
# debug
[![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_.
<img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png">
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
`disable()`
Will disable all namespaces. The functions returns the namespaces currently
enabled (and skipped). This can be useful if you want to disable debugging
temporarily without knowing what was enabled to begin with.
For example:
```js
let debug = require('debug');
debug.enable('foo:*,-foo:bar');
let namespaces = debug.disable();
debug.enable(namespaces);
```
Note: There is no guarantee that the string will be identical to the initial
enable string, but semantically they will be identical.
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Usage in child processes
Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process.
For example:
```javascript
worker = fork(WORKER_WRAP_PATH, [workerPath], {
stdio: [
/* stdin: */ 0,
/* stdout: */ 'pipe',
/* stderr: */ 'pipe',
'ipc',
],
env: Object.assign({}, process.env, {
DEBUG_COLORS: 1 // without this settings, colors won't be shown
}),
});
worker.stderr.pipe(process.stderr, { end: false });
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
- Josh Junon
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Copyright (c) 2018-2021 Josh Junon
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.
@@ -0,0 +1,64 @@
{
"name": "debug",
"version": "4.4.3",
"repository": {
"type": "git",
"url": "git://github.com/debug-js/debug.git"
},
"description": "Lightweight debugging utility for Node.js and the browser",
"keywords": [
"debug",
"log",
"debugger"
],
"files": [
"src",
"LICENSE",
"README.md"
],
"author": "Josh Junon (https://github.com/qix-)",
"contributors": [
"TJ Holowaychuk <tj@vision-media.ca>",
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"scripts": {
"lint": "xo",
"test": "npm run test:node && npm run test:browser && npm run lint",
"test:node": "mocha test.js test.node.js",
"test:browser": "karma start --single-run",
"test:coverage": "cat ./coverage/lcov.info | coveralls"
},
"dependencies": {
"ms": "^2.1.3"
},
"devDependencies": {
"brfs": "^2.0.1",
"browserify": "^16.2.3",
"coveralls": "^3.0.2",
"karma": "^3.1.4",
"karma-browserify": "^6.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"sinon": "^14.0.0",
"xo": "^0.23.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"engines": {
"node": ">=6.0"
},
"xo": {
"rules": {
"import/extensions": "off"
}
}
}
@@ -0,0 +1,272 @@
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
let m;
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
// eslint-disable-next-line no-return-assign
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
@@ -0,0 +1,292 @@
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
const split = (typeof namespaces === 'string' ? namespaces : '')
.trim()
.replace(/\s+/g, ',')
.split(',')
.filter(Boolean);
for (const ns of split) {
if (ns[0] === '-') {
createDebug.skips.push(ns.slice(1));
} else {
createDebug.names.push(ns);
}
}
}
/**
* Checks if the given string matches a namespace template, honoring
* asterisks as wildcards.
*
* @param {String} search
* @param {String} template
* @return {Boolean}
*/
function matchesTemplate(search, template) {
let searchIndex = 0;
let templateIndex = 0;
let starIndex = -1;
let matchIndex = 0;
while (searchIndex < search.length) {
if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
// Match character or proceed with wildcard
if (template[templateIndex] === '*') {
starIndex = templateIndex;
matchIndex = searchIndex;
templateIndex++; // Skip the '*'
} else {
searchIndex++;
templateIndex++;
}
} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
// Backtrack to the last '*' and try to match more characters
templateIndex = starIndex + 1;
matchIndex++;
searchIndex = matchIndex;
} else {
return false; // No match
}
}
// Handle trailing '*' in template
while (templateIndex < template.length && template[templateIndex] === '*') {
templateIndex++;
}
return templateIndex === template.length;
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names,
...createDebug.skips.map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
for (const skip of createDebug.skips) {
if (matchesTemplate(name, skip)) {
return false;
}
}
for (const ns of createDebug.names) {
if (matchesTemplate(name, ns)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
@@ -0,0 +1,10 @@
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}
@@ -0,0 +1,263 @@
/**
* Module dependencies.
*/
const tty = require('tty');
const util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
@@ -0,0 +1,162 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 Vercel, Inc.
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.
@@ -0,0 +1,38 @@
{
"name": "ms",
"version": "2.1.3",
"description": "Tiny millisecond conversion utility",
"repository": "vercel/ms",
"main": "./index",
"files": [
"index.js"
],
"scripts": {
"precommit": "lint-staged",
"lint": "eslint lib/* bin/*",
"test": "mocha tests.js"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"license": "MIT",
"devDependencies": {
"eslint": "4.18.2",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1",
"prettier": "2.0.5"
}
}
@@ -0,0 +1,59 @@
# ms
![CI](https://github.com/vercel/ms/workflows/CI/badge.svg)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`
+121
View File
@@ -0,0 +1,121 @@
{
"name": "http-proxy-middleware",
"version": "4.2.0",
"description": "The one-liner node.js proxy middleware for connect, express, next.js and more",
"keywords": [
"browser-sync",
"connect",
"cors",
"express",
"fastify",
"grunt-contrib-connect",
"gulp",
"hono",
"http",
"https",
"middleware",
"next.js",
"polka",
"proxy",
"reverse",
"websocket",
"ws"
],
"homepage": "https://github.com/chimurai/http-proxy-middleware#readme",
"bugs": {
"url": "https://github.com/chimurai/http-proxy-middleware/issues"
},
"license": "MIT",
"author": "Steven Chim",
"repository": {
"type": "git",
"url": "git+https://github.com/chimurai/http-proxy-middleware.git"
},
"files": [
"dist"
],
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"./hono": {
"types": "./dist/index-hono.d.ts",
"import": "./dist/index-hono.js",
"default": "./dist/index-hono.js"
}
},
"publishConfig": {
"provenance": true
},
"scripts": {
"clean": "rm -rf dist coverage tsconfig.tsbuildinfo .eslintcache",
"install:all": "yarn && (cd examples && yarn)",
"lint": "yarn format && yarn eslint",
"lint:fix": "yarn format:fix && yarn eslint:fix",
"eslint": "eslint --cache '**/*.{js,ts,mjs,mts}'",
"eslint:fix": "yarn eslint --fix",
"format": "oxfmt --list-different \"**/*.{js,ts,mjs,mts,md,yml,json,html}\"",
"format:fix": "oxfmt --write \"**/*.{js,ts,mjs,mts,md,yml,json,html}\"",
"build": "tsc --build",
"test": "vitest run",
"test:types": "tsc --project tsconfig.test.json --noEmit",
"coverage": "vitest run --coverage",
"prepare": "husky",
"prepack": "yarn clean && yarn test && yarn build",
"spellcheck": "npx --yes cspell --show-context --show-suggestions '**/*.*'"
},
"dependencies": {
"debug": "^4.4.3",
"httpxy": "^0.5.4",
"is-glob": "^4.0.3",
"is-plain-obj": "^4.1.0",
"micromatch": "^4.0.8"
},
"devDependencies": {
"@commitlint/cli": "21.2.0",
"@commitlint/config-conventional": "21.2.0",
"@eslint/js": "10.0.1",
"@hono/node-server": "2.0.8",
"@types/debug": "4.1.13",
"@types/eslint": "9.6.1",
"@types/express": "5.0.6",
"@types/is-glob": "4.0.4",
"@types/micromatch": "4.0.10",
"@types/node": "26.1.0",
"@types/supertest": "7.2.0",
"@types/ws": "8.18.1",
"@vitest/coverage-v8": "4.1.9",
"body-parser": "2.3.0",
"eslint": "10.6.0",
"express": "5.2.1",
"get-port": "7.2.0",
"globals": "17.7.0",
"hono": "4.12.27",
"husky": "9.1.7",
"lint-staged": "17.0.8",
"mockttp": "4.4.2",
"msw": "2.14.6",
"nock": "14.0.16",
"open": "11.0.0",
"oxfmt": "0.57.0",
"pkg-pr-new": "0.0.75",
"supertest": "7.2.2",
"typescript": "6.0.3",
"typescript-eslint": "8.62.1",
"vitest": "4.1.9",
"ws": "8.21.0"
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"engines": {
"node": "^22.15.0 || ^24.0.0 || >=26.0.0"
}
}