http-proxy-middleware 0.21.0-beta.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,9 +1,17 @@
1
1
  # Changelog
2
2
 
3
- ## next
3
+ ## [v1.0.0](https://github.com/chimurai/http-proxy-middleware/releases/tag/v1.0.0)
4
4
 
5
- - feat: async router ([#379](https://github.com/chimurai/http-proxy-middleware/issues/335)) ([LiranBri](https://github.com/LiranBri))
5
+ - feat(createProxyMiddleware): explicit import http-proxy-middleware (BREAKING CHANGE)([#400](https://github.com/chimurai/http-proxy-middleware/issues/400#issuecomment-587162378))
6
+ - feat(typescript): export http-proxy-middleware types ([#400](https://github.com/chimurai/http-proxy-middleware/issues/400))
7
+ - fix(typescript): ES6 target - TS1192 ([#400](https://github.com/chimurai/http-proxy-middleware/issues/400#issuecomment-587064349))
8
+
9
+ ## [v0.21.0](https://github.com/chimurai/http-proxy-middleware/releases/tag/v0.21.0)
10
+
11
+ - feat(http-proxy): bump to v1.18.0
12
+ - feat: async router ([#379](https://github.com/chimurai/http-proxy-middleware/issues/379)) ([LiranBri](https://github.com/LiranBri))
6
13
  - feat(typescript): types support ([#369](https://github.com/chimurai/http-proxy-middleware/pull/369))
14
+ - feat: async pathRewrite ([#397](https://github.com/chimurai/http-proxy-middleware/pull/397)) ([rsethc](https://github.com/rsethc))
7
15
 
8
16
  ## [v0.20.0](https://github.com/chimurai/http-proxy-middleware/releases/tag/v0.20.0)
9
17
 
package/README.md CHANGED
@@ -10,20 +10,40 @@ Node.js proxying made simple. Configure proxy middleware with ease for [connect]
10
10
 
11
11
  Powered by the popular Nodejitsu [`http-proxy`](https://github.com/nodejitsu/node-http-proxy). [![GitHub stars](https://img.shields.io/github/stars/nodejitsu/node-http-proxy.svg?style=social&label=Star)](https://github.com/nodejitsu/node-http-proxy)
12
12
 
13
+ ## ⚠️ Note
14
+
15
+ This page is showing documentation for version v1.x.x ([release notes](https://github.com/chimurai/http-proxy-middleware/releases))
16
+
17
+ If you're looking for v0.x documentation. Go to:
18
+ https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme
19
+
13
20
  ## TL;DR
14
21
 
15
22
  Proxy `/api` requests to `http://www.example.org`
16
23
 
17
24
  ```javascript
18
- var express = require('express');
19
- var proxy = require('http-proxy-middleware');
25
+ // javascript
26
+
27
+ const express = require('express');
28
+ const { createProxyMiddleware } = require('http-proxy-middleware');
29
+
30
+ const app = express();
31
+
32
+ app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
33
+ app.listen(3000);
20
34
 
21
- var app = express();
35
+ // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
36
+ ```
37
+
38
+ ```typescript
39
+ // typescript
40
+
41
+ import * as express from 'express';
42
+ import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware';
22
43
 
23
- app.use(
24
- '/api',
25
- proxy({ target: 'http://www.example.org', changeOrigin: true })
26
- );
44
+ const app = express();
45
+
46
+ app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
27
47
  app.listen(3000);
28
48
 
29
49
  // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
@@ -60,7 +80,7 @@ _All_ `http-proxy` [options](https://github.com/nodejitsu/node-http-proxy#option
60
80
 
61
81
  ## Install
62
82
 
63
- ```javascript
83
+ ```bash
64
84
  $ npm install --save-dev http-proxy-middleware
65
85
  ```
66
86
 
@@ -68,15 +88,15 @@ $ npm install --save-dev http-proxy-middleware
68
88
 
69
89
  Proxy middleware configuration.
70
90
 
71
- #### proxy([context,] config)
91
+ #### createProxyMiddleware([context,] config)
72
92
 
73
93
  ```javascript
74
- var proxy = require('http-proxy-middleware');
94
+ const { createProxyMiddleware } = require('http-proxy-middleware');
75
95
 
76
- var apiProxy = proxy('/api', { target: 'http://www.example.org' });
77
- // \____/ \_____________________________/
78
- // | |
79
- // context options
96
+ const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });
97
+ // \____/ \_____________________________/
98
+ // | |
99
+ // context options
80
100
 
81
101
  // 'apiProxy' is now ready to be used as middleware in a server.
82
102
  ```
@@ -87,11 +107,11 @@ var apiProxy = proxy('/api', { target: 'http://www.example.org' });
87
107
 
88
108
  (full list of [`http-proxy-middleware` configuration options](#options))
89
109
 
90
- #### proxy(uri [, config])
110
+ #### createProxyMiddleware(uri [, config])
91
111
 
92
112
  ```javascript
93
113
  // shorthand syntax for the example above:
94
- var apiProxy = proxy('http://www.example.org/api');
114
+ const apiProxy = createProxyMiddleware('http://www.example.org/api');
95
115
  ```
96
116
 
97
117
  More about the [shorthand configuration](#shorthand).
@@ -102,11 +122,11 @@ An example with `express` server.
102
122
 
103
123
  ```javascript
104
124
  // include dependencies
105
- var express = require('express');
106
- var proxy = require('http-proxy-middleware');
125
+ const express = require('express');
126
+ const { createProxyMiddleware } = require('http-proxy-middleware');
107
127
 
108
128
  // proxy middleware options
109
- var options = {
129
+ const options = {
110
130
  target: 'http://www.example.org', // target host
111
131
  changeOrigin: true, // needed for virtual hosted sites
112
132
  ws: true, // proxy websockets
@@ -122,10 +142,10 @@ var options = {
122
142
  };
123
143
 
124
144
  // create the proxy (without context)
125
- var exampleProxy = proxy(options);
145
+ const exampleProxy = createProxyMiddleware(options);
126
146
 
127
147
  // mount `exampleProxy` in web server
128
- var app = express();
148
+ const app = express();
129
149
  app.use('/api', exampleProxy);
130
150
  app.listen(3000);
131
151
  ```
@@ -136,7 +156,7 @@ Providing an alternative way to decide which requests should be proxied; In case
136
156
 
137
157
  [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used for context matching.
138
158
 
139
- ```
159
+ ```ascii
140
160
  foo://example.com:8042/over/there?name=ferret#nose
141
161
  \_/ \______________/\_________/ \_________/ \__/
142
162
  | | | | |
@@ -145,24 +165,24 @@ Providing an alternative way to decide which requests should be proxied; In case
145
165
 
146
166
  - **path matching**
147
167
 
148
- - `proxy({...})` - matches any path, all requests will be proxied.
149
- - `proxy('/', {...})` - matches any path, all requests will be proxied.
150
- - `proxy('/api', {...})` - matches paths starting with `/api`
168
+ - `createProxyMiddleware({...})` - matches any path, all requests will be proxied.
169
+ - `createProxyMiddleware('/', {...})` - matches any path, all requests will be proxied.
170
+ - `createProxyMiddleware('/api', {...})` - matches paths starting with `/api`
151
171
 
152
172
  - **multiple path matching**
153
173
 
154
- - `proxy(['/api', '/ajax', '/someotherpath'], {...})`
174
+ - `createProxyMiddleware(['/api', '/ajax', '/someotherpath'], {...})`
155
175
 
156
176
  - **wildcard path matching**
157
177
 
158
178
  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.
159
179
 
160
- - `proxy('**', {...})` matches any path, all requests will be proxied.
161
- - `proxy('**/*.html', {...})` matches any path which ends with `.html`
162
- - `proxy('/*.html', {...})` matches paths directly under path-absolute
163
- - `proxy('/api/**/*.html', {...})` matches requests ending with `.html` in the path of `/api`
164
- - `proxy(['/api/**', '/ajax/**'], {...})` combine multiple patterns
165
- - `proxy(['/api/**', '!**/bad.json'], {...})` exclusion
180
+ - `createProxyMiddleware('**', {...})` matches any path, all requests will be proxied.
181
+ - `createProxyMiddleware('**/*.html', {...})` matches any path which ends with `.html`
182
+ - `createProxyMiddleware('/*.html', {...})` matches paths directly under path-absolute
183
+ - `createProxyMiddleware('/api/**/*.html', {...})` matches requests ending with `.html` in the path of `/api`
184
+ - `createProxyMiddleware(['/api/**', '/ajax/**'], {...})` combine multiple patterns
185
+ - `createProxyMiddleware(['/api/**', '!**/bad.json'], {...})` exclusion
166
186
 
167
187
  **Note**: In multiple path matching, you cannot use string paths and wildcard paths together.
168
188
 
@@ -174,11 +194,13 @@ Providing an alternative way to decide which requests should be proxied; In case
174
194
  /**
175
195
  * @return {Boolean}
176
196
  */
177
- var filter = function(pathname, req) {
197
+ const filter = function(pathname, req) {
178
198
  return pathname.match('^/api') && req.method === 'GET';
179
199
  };
180
200
 
181
- var apiProxy = proxy(filter, { target: 'http://www.example.org' });
201
+ const apiProxy = createProxyMiddleware(filter, {
202
+ target: 'http://www.example.org'
203
+ });
182
204
  ```
183
205
 
184
206
  ## Options
@@ -199,6 +221,14 @@ Providing an alternative way to decide which requests should be proxied; In case
199
221
 
200
222
  // custom rewriting
201
223
  pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
224
+
225
+ // custom rewriting, returning Promise
226
+ pathRewrite: async function (path, req) {
227
+ const should_add_something = await httpRequestToDecideSomething(path);
228
+ if (should_add_something) path += "something";
229
+ return path;
230
+ }
231
+
202
232
  ```
203
233
 
204
234
  - **option.router**: object/function, re-target `option.target` for specific requests.
@@ -240,9 +270,9 @@ Providing an alternative way to decide which requests should be proxied; In case
240
270
  ```javascript
241
271
  // verbose replacement
242
272
  function logProvider(provider) {
243
- var logger = new (require('winston')).Logger();
273
+ const logger = new (require('winston').Logger)();
244
274
 
245
- var myCustomProvider = {
275
+ const myCustomProvider = {
246
276
  log: logger.log,
247
277
  debug: logger.debug,
248
278
  info: logger.info,
@@ -264,9 +294,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
264
294
  res.writeHead(500, {
265
295
  'Content-Type': 'text/plain'
266
296
  });
267
- res.end(
268
- 'Something went wrong. And we are reporting a custom error message.'
269
- );
297
+ res.end('Something went wrong. And we are reporting a custom error message.');
270
298
  }
271
299
  ```
272
300
 
@@ -308,6 +336,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
308
336
  ```
309
337
 
310
338
  - **option.onClose**: function, subscribe to http-proxy's `close` event.
339
+
311
340
  ```javascript
312
341
  function onClose(res, socket, head) {
313
342
  // view disconnected websocket connections
@@ -341,7 +370,7 @@ The following options are provided by the underlying [http-proxy](https://github
341
370
  - String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
342
371
  - Object: mapping of domains to new domains, use `"*"` to match all domains.
343
372
  For example keep one domain unchanged, rewrite one domain and remove other domains:
344
- ```
373
+ ```json
345
374
  cookieDomainRewrite: {
346
375
  "unchanged.domain": "unchanged.domain",
347
376
  "old.domain": "new.domain",
@@ -353,7 +382,7 @@ The following options are provided by the underlying [http-proxy](https://github
353
382
  - String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
354
383
  - Object: mapping of paths to new paths, use `"*"` to match all paths.
355
384
  For example, to keep one path unchanged, rewrite one path and remove other paths:
356
- ```
385
+ ```json
357
386
  cookiePathRewrite: {
358
387
  "/unchanged.path/": "/unchanged.path/",
359
388
  "/old.path/": "/new.path/",
@@ -367,7 +396,7 @@ The following options are provided by the underlying [http-proxy](https://github
367
396
  - **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
368
397
  - **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:
369
398
 
370
- ```
399
+ ```javascript
371
400
  'use strict';
372
401
 
373
402
  const streamify = require('stream-array');
@@ -375,12 +404,15 @@ The following options are provided by the underlying [http-proxy](https://github
375
404
  const proxy = new HttpProxy();
376
405
 
377
406
  module.exports = (req, res, next) => {
378
-
379
- proxy.web(req, res, {
380
- target: 'http://localhost:4003/',
381
- buffer: streamify(req.rawBody)
382
- }, next);
383
-
407
+ proxy.web(
408
+ req,
409
+ res,
410
+ {
411
+ target: 'http://localhost:4003/',
412
+ buffer: streamify(req.rawBody)
413
+ },
414
+ next
415
+ );
384
416
  };
385
417
  ```
386
418
 
@@ -389,14 +421,14 @@ The following options are provided by the underlying [http-proxy](https://github
389
421
  Use the shorthand syntax when verbose configuration is not needed. The `context` and `option.target` will be automatically configured when shorthand is used. Options can still be used if needed.
390
422
 
391
423
  ```javascript
392
- proxy('http://www.example.org:8000/api');
393
- // proxy('/api', {target: 'http://www.example.org:8000'});
424
+ createProxyMiddleware('http://www.example.org:8000/api');
425
+ // createProxyMiddleware('/api', {target: 'http://www.example.org:8000'});
394
426
 
395
- proxy('http://www.example.org:8000/api/books/*/**.json');
396
- // proxy('/api/books/*/**.json', {target: 'http://www.example.org:8000'});
427
+ createProxyMiddleware('http://www.example.org:8000/api/books/*/**.json');
428
+ // createProxyMiddleware('/api/books/*/**.json', {target: 'http://www.example.org:8000'});
397
429
 
398
- proxy('http://www.example.org:8000/api', { changeOrigin: true });
399
- // proxy('/api', {target: 'http://www.example.org:8000', changeOrigin: true});
430
+ createProxyMiddleware('http://www.example.org:8000/api', { changeOrigin: true });
431
+ // createProxyMiddleware('/api', {target: 'http://www.example.org:8000', changeOrigin: true});
400
432
  ```
401
433
 
402
434
  ### app.use(path, proxy)
@@ -405,28 +437,26 @@ If you want to use the server's `app.use` `path` parameter to match requests;
405
437
  Create and mount the proxy without the http-proxy-middleware `context` parameter:
406
438
 
407
439
  ```javascript
408
- app.use(
409
- '/api',
410
- proxy({ target: 'http://www.example.org', changeOrigin: true })
411
- );
440
+ app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
412
441
  ```
413
442
 
414
443
  `app.use` documentation:
415
444
 
416
445
  - express: http://expressjs.com/en/4x/api.html#app.use
417
446
  - connect: https://github.com/senchalabs/connect#mount-middleware
447
+ - polka: https://github.com/lukeed/polka#usebase-fn
418
448
 
419
449
  ## WebSocket
420
450
 
421
451
  ```javascript
422
452
  // verbose api
423
- proxy('/', { target: 'http://echo.websocket.org', ws: true });
453
+ createProxyMiddleware('/', { target: 'http://echo.websocket.org', ws: true });
424
454
 
425
455
  // shorthand
426
- proxy('http://echo.websocket.org', { ws: true });
456
+ createProxyMiddleware('http://echo.websocket.org', { ws: true });
427
457
 
428
458
  // shorter shorthand
429
- proxy('ws://echo.websocket.org');
459
+ createProxyMiddleware('ws://echo.websocket.org');
430
460
  ```
431
461
 
432
462
  ### External WebSocket upgrade
@@ -434,12 +464,12 @@ proxy('ws://echo.websocket.org');
434
464
  In the previous WebSocket examples, http-proxy-middleware relies on a 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.
435
465
 
436
466
  ```javascript
437
- var wsProxy = proxy('ws://echo.websocket.org', { changeOrigin: true });
467
+ const wsProxy = createProxyMiddleware('ws://echo.websocket.org', { changeOrigin: true });
438
468
 
439
- var app = express();
469
+ const app = express();
440
470
  app.use(wsProxy);
441
471
 
442
- var server = app.listen(3000);
472
+ const server = app.listen(3000);
443
473
  server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade'
444
474
  ```
445
475
 
@@ -464,6 +494,7 @@ View the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master
464
494
  - [express](https://www.npmjs.com/package/express)
465
495
  - [browser-sync](https://www.npmjs.com/package/browser-sync)
466
496
  - [lite-server](https://www.npmjs.com/package/lite-server)
497
+ - [polka](https://github.com/lukeed/polka)
467
498
  - [grunt-contrib-connect](https://www.npmjs.com/package/grunt-contrib-connect)
468
499
  - [grunt-browser-sync](https://www.npmjs.com/package/grunt-browser-sync)
469
500
  - [gulp-connect](https://www.npmjs.com/package/gulp-connect)
@@ -501,4 +532,4 @@ $ yarn cover
501
532
 
502
533
  The MIT License (MIT)
503
534
 
504
- Copyright (c) 2015-2019 Steven Chim
535
+ Copyright (c) 2015-2020 Steven Chim
@@ -1,10 +1,7 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const lodash_1 = __importDefault(require("lodash"));
7
- const url_1 = __importDefault(require("url"));
3
+ const _ = require("lodash");
4
+ const url = require("url");
8
5
  const errors_1 = require("./errors");
9
6
  const logger_1 = require("./logger");
10
7
  const logger = logger_1.getInstance();
@@ -17,15 +14,15 @@ function createConfig(context, opts) {
17
14
  // app.use('/api', proxy({target:'http://localhost:9000'}));
18
15
  if (isContextless(context, opts)) {
19
16
  config.context = '/';
20
- config.options = lodash_1.default.assign(config.options, context);
17
+ config.options = _.assign(config.options, context);
21
18
  // app.use('/api', proxy('http://localhost:9000'));
22
19
  // app.use(proxy('http://localhost:9000/api'));
23
20
  }
24
21
  else if (isStringShortHand(context)) {
25
- const oUrl = url_1.default.parse(context);
22
+ const oUrl = url.parse(context);
26
23
  const target = [oUrl.protocol, '//', oUrl.host].join('');
27
24
  config.context = oUrl.pathname || '/';
28
- config.options = lodash_1.default.assign(config.options, { target }, opts);
25
+ config.options = _.assign(config.options, { target }, opts);
29
26
  if (oUrl.protocol === 'ws:' || oUrl.protocol === 'wss:') {
30
27
  config.options.ws = true;
31
28
  }
@@ -33,7 +30,7 @@ function createConfig(context, opts) {
33
30
  }
34
31
  else {
35
32
  config.context = context;
36
- config.options = lodash_1.default.assign(config.options, opts);
33
+ config.options = _.assign(config.options, opts);
37
34
  }
38
35
  configureLogger(config.options);
39
36
  if (!config.options.target) {
@@ -54,8 +51,8 @@ exports.createConfig = createConfig;
54
51
  * @return {Boolean} [description]
55
52
  */
56
53
  function isStringShortHand(context) {
57
- if (lodash_1.default.isString(context)) {
58
- return !!url_1.default.parse(context).host;
54
+ if (_.isString(context)) {
55
+ return !!url.parse(context).host;
59
56
  }
60
57
  }
61
58
  /**
@@ -70,7 +67,7 @@ function isStringShortHand(context) {
70
67
  * @return {Boolean} [description]
71
68
  */
72
69
  function isContextless(context, opts) {
73
- return lodash_1.default.isPlainObject(context) && lodash_1.default.isEmpty(opts);
70
+ return _.isPlainObject(context) && _.isEmpty(opts);
74
71
  }
75
72
  function configureLogger(options) {
76
73
  if (options.logLevel) {
@@ -1,12 +1,9 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const is_glob_1 = __importDefault(require("is-glob"));
7
- const lodash_1 = __importDefault(require("lodash"));
8
- const micromatch_1 = __importDefault(require("micromatch"));
9
- const url_1 = __importDefault(require("url"));
3
+ const isGlob = require("is-glob");
4
+ const _ = require("lodash");
5
+ const micromatch = require("micromatch");
6
+ const url = require("url");
10
7
  const errors_1 = require("./errors");
11
8
  function match(context, uri, req) {
12
9
  // single path
@@ -28,7 +25,7 @@ function match(context, uri, req) {
28
25
  throw new Error(errors_1.ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY);
29
26
  }
30
27
  // custom matching
31
- if (lodash_1.default.isFunction(context)) {
28
+ if (_.isFunction(context)) {
32
29
  const pathname = getUrlPathName(uri);
33
30
  return context(pathname, req);
34
31
  }
@@ -46,7 +43,7 @@ function matchSingleStringPath(context, uri) {
46
43
  }
47
44
  function matchSingleGlobPath(pattern, uri) {
48
45
  const pathname = getUrlPathName(uri);
49
- const matches = micromatch_1.default([pathname], pattern);
46
+ const matches = micromatch([pathname], pattern);
50
47
  return matches && matches.length > 0;
51
48
  }
52
49
  function matchMultiGlobPath(patternList, uri) {
@@ -74,11 +71,11 @@ function matchMultiPath(contextList, uri) {
74
71
  * @return {String} RFC 3986 path
75
72
  */
76
73
  function getUrlPathName(uri) {
77
- return uri && url_1.default.parse(uri).pathname;
74
+ return uri && url.parse(uri).pathname;
78
75
  }
79
76
  function isStringPath(context) {
80
- return lodash_1.default.isString(context) && !is_glob_1.default(context);
77
+ return _.isString(context) && !isGlob(context);
81
78
  }
82
79
  function isGlobPath(context) {
83
- return is_glob_1.default(context);
80
+ return isGlob(context);
84
81
  }
package/dist/handlers.js CHANGED
@@ -1,9 +1,6 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const lodash_1 = __importDefault(require("lodash"));
3
+ const _ = require("lodash");
7
4
  const logger_1 = require("./logger");
8
5
  const logger = logger_1.getInstance();
9
6
  function init(proxy, option) {
@@ -16,31 +13,24 @@ function init(proxy, option) {
16
13
  exports.init = init;
17
14
  function getHandlers(options) {
18
15
  // https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events
19
- const proxyEvents = [
20
- 'error',
21
- 'proxyReq',
22
- 'proxyReqWs',
23
- 'proxyRes',
24
- 'open',
25
- 'close'
26
- ];
16
+ const proxyEvents = ['error', 'proxyReq', 'proxyReqWs', 'proxyRes', 'open', 'close'];
27
17
  const handlers = {};
28
18
  for (const event of proxyEvents) {
29
19
  // all handlers for the http-proxy events are prefixed with 'on'.
30
20
  // loop through options and try to find these handlers
31
21
  // and add them to the handlers object for subscription in init().
32
- const eventName = lodash_1.default.camelCase('on ' + event);
33
- const fnHandler = lodash_1.default.get(options, eventName);
34
- if (lodash_1.default.isFunction(fnHandler)) {
22
+ const eventName = _.camelCase('on ' + event);
23
+ const fnHandler = _.get(options, eventName);
24
+ if (_.isFunction(fnHandler)) {
35
25
  handlers[event] = fnHandler;
36
26
  }
37
27
  }
38
28
  // add default error handler in absence of error handler
39
- if (!lodash_1.default.isFunction(handlers.error)) {
29
+ if (!_.isFunction(handlers.error)) {
40
30
  handlers.error = defaultErrorHandler;
41
31
  }
42
32
  // add default close handler in absence of close handler
43
- if (!lodash_1.default.isFunction(handlers.close)) {
33
+ if (!_.isFunction(handlers.close)) {
44
34
  handlers.close = logClose;
45
35
  }
46
36
  return handlers;
@@ -1,4 +1,4 @@
1
- import { Filter, IRequestHandler, Options } from './types';
1
+ import { Filter, RequestHandler, Options } from './types';
2
2
  export declare class HttpProxyMiddleware {
3
3
  private logger;
4
4
  private config;
@@ -7,7 +7,7 @@ export declare class HttpProxyMiddleware {
7
7
  private proxy;
8
8
  private pathRewriter;
9
9
  constructor(context: Filter | Options, opts?: Options);
10
- middleware: IRequestHandler;
10
+ middleware: RequestHandler;
11
11
  private catchUpgradeRequest;
12
12
  private handleUpgrade;
13
13
  /**
@@ -1,31 +1,22 @@
1
1
  "use strict";
2
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
4
  return new (P || (P = Promise))(function (resolve, reject) {
4
5
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
6
  function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
9
  });
9
10
  };
10
- var __importDefault = (this && this.__importDefault) || function (mod) {
11
- return (mod && mod.__esModule) ? mod : { "default": mod };
12
- };
13
- var __importStar = (this && this.__importStar) || function (mod) {
14
- if (mod && mod.__esModule) return mod;
15
- var result = {};
16
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
17
- result["default"] = mod;
18
- return result;
19
- };
20
11
  Object.defineProperty(exports, "__esModule", { value: true });
21
- const http_proxy_1 = __importDefault(require("http-proxy"));
22
- const lodash_1 = __importDefault(require("lodash"));
12
+ const httpProxy = require("http-proxy");
13
+ const _ = require("lodash");
23
14
  const config_factory_1 = require("./config-factory");
24
- const contextMatcher = __importStar(require("./context-matcher"));
25
- const handlers = __importStar(require("./handlers"));
15
+ const contextMatcher = require("./context-matcher");
16
+ const handlers = require("./handlers");
26
17
  const logger_1 = require("./logger");
27
- const PathRewriter = __importStar(require("./path-rewriter"));
28
- const Router = __importStar(require("./router"));
18
+ const PathRewriter = require("./path-rewriter");
19
+ const Router = require("./router");
29
20
  class HttpProxyMiddleware {
30
21
  constructor(context, opts) {
31
22
  this.logger = logger_1.getInstance();
@@ -85,12 +76,12 @@ class HttpProxyMiddleware {
85
76
  req.url = req.originalUrl || req.url;
86
77
  // store uri before it gets rewritten for logging
87
78
  const originalPath = req.url;
88
- const newProxyOptions = lodash_1.default.assign({}, this.proxyOptions);
79
+ const newProxyOptions = _.assign({}, this.proxyOptions);
89
80
  // Apply in order:
90
81
  // 1. option.router
91
82
  // 2. option.pathRewrite
92
83
  yield this.applyRouter(req, newProxyOptions);
93
- this.applyPathRewrite(req, this.pathRewriter);
84
+ yield this.applyPathRewrite(req, this.pathRewriter);
94
85
  // debug logging for both http(s) and websockets
95
86
  if (this.proxyOptions.logLevel === 'debug') {
96
87
  const arrow = logger_1.getArrow(originalPath, req.url, this.proxyOptions.target, newProxyOptions.target);
@@ -110,9 +101,9 @@ class HttpProxyMiddleware {
110
101
  }
111
102
  });
112
103
  // rewrite path
113
- this.applyPathRewrite = (req, pathRewriter) => {
104
+ this.applyPathRewrite = (req, pathRewriter) => __awaiter(this, void 0, void 0, function* () {
114
105
  if (pathRewriter) {
115
- const path = pathRewriter(req.url, req);
106
+ const path = yield pathRewriter(req.url, req);
116
107
  if (typeof path === 'string') {
117
108
  req.url = path;
118
109
  }
@@ -120,9 +111,9 @@ class HttpProxyMiddleware {
120
111
  this.logger.info('[HPM] pathRewrite: No rewritten path found. (%s)', req.url);
121
112
  }
122
113
  }
123
- };
114
+ });
124
115
  this.logError = (err, req, res) => {
125
- const hostname = (req.headers && req.headers.host) || (req.hostname || req.host); // (websocket) || (node0.10 || node 4/5)
116
+ const hostname = (req.headers && req.headers.host) || req.hostname || req.host; // (websocket) || (node0.10 || node 4/5)
126
117
  const target = this.proxyOptions.target.host || this.proxyOptions.target;
127
118
  const errorMessage = '[HPM] Error occurred while trying to proxy request %s from %s to %s (%s) (%s)';
128
119
  const errReference = 'https://nodejs.org/api/errors.html#errors_common_system_errors'; // link to Node Common Systems Errors page
@@ -131,7 +122,7 @@ class HttpProxyMiddleware {
131
122
  this.config = config_factory_1.createConfig(context, opts);
132
123
  this.proxyOptions = this.config.options;
133
124
  // create proxy
134
- this.proxy = http_proxy_1.default.createProxyServer({});
125
+ this.proxy = httpProxy.createProxyServer({});
135
126
  this.logger.info(`[HPM] Proxy created: ${this.config.context} -> ${this.proxyOptions.target}`);
136
127
  this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
137
128
  // attach handler to http-proxy events
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { Filter, Options } from './types';
2
- declare function middleware(context: Filter | Options, options?: Options): import("./types").IRequestHandler;
3
- export = middleware;
2
+ export declare function createProxyMiddleware(context: Filter | Options, options?: Options): import("./types").RequestHandler;
3
+ export { Filter, Options, RequestHandler } from './types';
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
2
3
  const http_proxy_middleware_1 = require("./http-proxy-middleware");
3
- function middleware(context, options) {
4
+ function createProxyMiddleware(context, options) {
4
5
  const { middleware } = new http_proxy_middleware_1.HttpProxyMiddleware(context, options);
5
6
  return middleware;
6
7
  }
7
- module.exports = middleware;
8
+ exports.createProxyMiddleware = createProxyMiddleware;
package/dist/logger.js CHANGED
@@ -1,10 +1,7 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const lodash_1 = __importDefault(require("lodash"));
7
- const util_1 = __importDefault(require("util"));
3
+ const _ = require("lodash");
4
+ const util = require("util");
8
5
  let loggerInstance;
9
6
  const defaultProvider = {
10
7
  // tslint:disable: no-console
@@ -71,7 +68,7 @@ class Logger {
71
68
  }
72
69
  isValidProvider(fnProvider) {
73
70
  const result = true;
74
- if (fnProvider && !lodash_1.default.isFunction(fnProvider)) {
71
+ if (fnProvider && !_.isFunction(fnProvider)) {
75
72
  throw new Error('[HPM] Log provider config error. Expecting a function.');
76
73
  }
77
74
  return result;
@@ -100,8 +97,8 @@ class Logger {
100
97
  // make sure logged messages and its data are return interpolated
101
98
  // make it possible for additional log data, such date/time or custom prefix.
102
99
  _interpolate() {
103
- const fn = lodash_1.default.spread(util_1.default.format);
104
- const result = fn(lodash_1.default.slice(arguments));
100
+ const fn = _.spread(util.format);
101
+ const result = fn(_.slice(arguments));
105
102
  return result;
106
103
  }
107
104
  }
@@ -1,9 +1,6 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const lodash_1 = __importDefault(require("lodash"));
3
+ const _ = require("lodash");
7
4
  const errors_1 = require("./errors");
8
5
  const logger_1 = require("./logger");
9
6
  const logger = logger_1.getInstance();
@@ -18,7 +15,7 @@ function createPathRewriter(rewriteConfig) {
18
15
  if (!isValidRewriteConfig(rewriteConfig)) {
19
16
  return;
20
17
  }
21
- if (lodash_1.default.isFunction(rewriteConfig)) {
18
+ if (_.isFunction(rewriteConfig)) {
22
19
  const customRewriteFn = rewriteConfig;
23
20
  return customRewriteFn;
24
21
  }
@@ -28,7 +25,7 @@ function createPathRewriter(rewriteConfig) {
28
25
  }
29
26
  function rewritePath(path) {
30
27
  let result = path;
31
- lodash_1.default.forEach(rulesCache, rule => {
28
+ _.forEach(rulesCache, rule => {
32
29
  if (rule.regex.test(path)) {
33
30
  result = result.replace(rule.regex, rule.value);
34
31
  logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result);
@@ -40,15 +37,15 @@ function createPathRewriter(rewriteConfig) {
40
37
  }
41
38
  exports.createPathRewriter = createPathRewriter;
42
39
  function isValidRewriteConfig(rewriteConfig) {
43
- if (lodash_1.default.isFunction(rewriteConfig)) {
40
+ if (_.isFunction(rewriteConfig)) {
44
41
  return true;
45
42
  }
46
- else if (!lodash_1.default.isEmpty(rewriteConfig) && lodash_1.default.isPlainObject(rewriteConfig)) {
43
+ else if (!_.isEmpty(rewriteConfig) && _.isPlainObject(rewriteConfig)) {
47
44
  return true;
48
45
  }
49
- else if (lodash_1.default.isUndefined(rewriteConfig) ||
50
- lodash_1.default.isNull(rewriteConfig) ||
51
- lodash_1.default.isEqual(rewriteConfig, {})) {
46
+ else if (_.isUndefined(rewriteConfig) ||
47
+ _.isNull(rewriteConfig) ||
48
+ _.isEqual(rewriteConfig, {})) {
52
49
  return false;
53
50
  }
54
51
  else {
@@ -57,8 +54,8 @@ function isValidRewriteConfig(rewriteConfig) {
57
54
  }
58
55
  function parsePathRewriteRules(rewriteConfig) {
59
56
  const rules = [];
60
- if (lodash_1.default.isPlainObject(rewriteConfig)) {
61
- lodash_1.default.forIn(rewriteConfig, (value, key) => {
57
+ if (_.isPlainObject(rewriteConfig)) {
58
+ _.forIn(rewriteConfig, (value, key) => {
62
59
  rules.push({
63
60
  regex: new RegExp(key),
64
61
  value: rewriteConfig[key]
package/dist/router.js CHANGED
@@ -1,27 +1,25 @@
1
1
  "use strict";
2
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
4
  return new (P || (P = Promise))(function (resolve, reject) {
4
5
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
6
  function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
9
  });
9
10
  };
10
- var __importDefault = (this && this.__importDefault) || function (mod) {
11
- return (mod && mod.__esModule) ? mod : { "default": mod };
12
- };
13
11
  Object.defineProperty(exports, "__esModule", { value: true });
14
- const lodash_1 = __importDefault(require("lodash"));
12
+ const _ = require("lodash");
15
13
  const logger_1 = require("./logger");
16
14
  const logger = logger_1.getInstance();
17
15
  function getTarget(req, config) {
18
16
  return __awaiter(this, void 0, void 0, function* () {
19
17
  let newTarget;
20
18
  const router = config.router;
21
- if (lodash_1.default.isPlainObject(router)) {
19
+ if (_.isPlainObject(router)) {
22
20
  newTarget = getTargetFromProxyTable(req, router);
23
21
  }
24
- else if (lodash_1.default.isFunction(router)) {
22
+ else if (_.isFunction(router)) {
25
23
  newTarget = yield router(req);
26
24
  }
27
25
  return newTarget;
@@ -33,7 +31,7 @@ function getTargetFromProxyTable(req, table) {
33
31
  const host = req.headers.host;
34
32
  const path = req.url;
35
33
  const hostAndPath = host + path;
36
- lodash_1.default.forIn(table, (value, key) => {
34
+ _.forIn(table, (value, key) => {
37
35
  if (containsPath(key)) {
38
36
  if (hostAndPath.indexOf(key) > -1) {
39
37
  // match 'localhost:3000/api'
package/dist/types.d.ts CHANGED
@@ -1,34 +1,31 @@
1
1
  /// <reference types="node" />
2
- import express from 'express';
3
- import http from 'http';
4
- import httpProxy from 'http-proxy';
5
- import net from 'net';
6
- export interface IRequest extends express.Request {
2
+ import * as express from 'express';
3
+ import * as http from 'http';
4
+ import * as httpProxy from 'http-proxy';
5
+ import * as net from 'net';
6
+ export interface Request extends express.Request {
7
7
  }
8
- export interface IResponse extends express.Response {
8
+ export interface Response extends express.Response {
9
9
  }
10
- export interface IRequestHandler extends express.RequestHandler {
11
- upgrade?: (req: IRequest, socket: net.Socket, head: any) => void;
10
+ export interface RequestHandler extends express.RequestHandler {
11
+ upgrade?: (req: Request, socket: net.Socket, head: any) => void;
12
12
  }
13
- export declare type Filter = FilterPath | FilterWildcards | FilterFn;
14
- export declare type FilterFn = (pathname: string, req: IRequest) => boolean;
15
- export declare type FilterPath = string;
16
- export declare type FilterWildcards = string[];
13
+ export declare type Filter = string | string[] | ((pathname: string, req: Request) => boolean);
17
14
  export interface Options extends httpProxy.ServerOptions {
18
15
  pathRewrite?: {
19
16
  [regexp: string]: string;
20
- } | ((path: string, req: IRequest) => string);
17
+ } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>);
21
18
  router?: {
22
19
  [hostOrPath: string]: string;
23
- } | ((req: IRequest) => string) | ((req: IRequest) => Promise<string>);
20
+ } | ((req: Request) => string) | ((req: Request) => Promise<string>);
24
21
  logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
25
22
  logProvider?(provider: LogProvider): LogProvider;
26
- onError?(err: Error, req: IRequest, res: IResponse): void;
27
- onProxyRes?(proxyRes: http.ServerResponse, req: IRequest, res: IResponse): void;
28
- onProxyReq?(proxyReq: http.ClientRequest, req: IRequest, res: IResponse): void;
29
- onProxyReqWs?(proxyReq: http.ClientRequest, req: IRequest, socket: net.Socket, options: httpProxy.ServerOptions, head: any): void;
23
+ onError?(err: Error, req: Request, res: Response): void;
24
+ onProxyRes?(proxyRes: http.ServerResponse, req: Request, res: Response): void;
25
+ onProxyReq?(proxyReq: http.ClientRequest, req: Request, res: Response): void;
26
+ onProxyReqWs?(proxyReq: http.ClientRequest, req: Request, socket: net.Socket, options: httpProxy.ServerOptions, head: any): void;
30
27
  onOpen?(proxySocket: net.Socket): void;
31
- onClose?(res: IResponse, socket: net.Socket, head: any): void;
28
+ onClose?(res: Response, socket: net.Socket, head: any): void;
32
29
  }
33
30
  interface LogProvider {
34
31
  log: Logger;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "http-proxy-middleware",
3
- "version": "0.21.0-beta.2",
3
+ "version": "1.0.0",
4
4
  "description": "The one-liner node.js proxy middleware for connect, express and browser-sync",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -35,6 +35,7 @@
35
35
  "https",
36
36
  "connect",
37
37
  "express",
38
+ "polka",
38
39
  "browser-sync",
39
40
  "gulp",
40
41
  "grunt-contrib-connect",
@@ -47,35 +48,35 @@
47
48
  "bugs": {
48
49
  "url": "https://github.com/chimurai/http-proxy-middleware/issues"
49
50
  },
50
- "homepage": "https://github.com/chimurai/http-proxy-middleware",
51
+ "homepage": "https://github.com/chimurai/http-proxy-middleware#readme",
51
52
  "devDependencies": {
52
53
  "@commitlint/cli": "^8.0.0",
53
54
  "@commitlint/config-conventional": "^8.0.0",
54
55
  "@types/express": "^4.17.0",
55
56
  "@types/is-glob": "^4.0.0",
56
- "@types/jest": "^24.0.15",
57
- "@types/lodash": "^4.14.136",
58
- "@types/micromatch": "^3.1.0",
57
+ "@types/jest": "^25.1.2",
58
+ "@types/lodash": "^4.14.149",
59
+ "@types/micromatch": "^4.0.1",
59
60
  "@types/node": "^12.6.2",
60
61
  "browser-sync": "^2.26.7",
61
62
  "connect": "^3.6.6",
62
63
  "coveralls": "^3.0.5",
63
64
  "express": "^4.16.4",
64
65
  "husky": "^3.0.0",
65
- "jest": "^24.5.0",
66
- "open": "^6.4.0",
67
- "prettier": "^1.18.2",
68
- "ts-jest": "^24.0.0",
69
- "tslint": "^5.18.0",
66
+ "jest": "^25.1.0",
67
+ "open": "^7.0.2",
68
+ "prettier": "^1.19.1",
69
+ "ts-jest": "^25.2.0",
70
+ "tslint": "^6.0.0",
70
71
  "tslint-config-prettier": "^1.18.0",
71
- "typescript": "^3.5.3",
72
+ "typescript": "^3.7.5",
72
73
  "ws": "^7.1.0"
73
74
  },
74
75
  "dependencies": {
75
- "@types/http-proxy": "^1.17.0",
76
- "http-proxy": "^1.17.0",
76
+ "@types/http-proxy": "^1.17.3",
77
+ "http-proxy": "^1.18.0",
77
78
  "is-glob": "^4.0.1",
78
- "lodash": "^4.17.14",
79
+ "lodash": "^4.17.15",
79
80
  "micromatch": "^4.0.2"
80
81
  },
81
82
  "engines": {