express-response-middleware 1.0.0 → 2.0.1

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.
@@ -12,17 +12,31 @@ jobs:
12
12
  release-please:
13
13
  runs-on: ubuntu-latest
14
14
  steps:
15
- - uses: actions/checkout@v4
16
- - uses: actions/setup-node@v4
15
+ - name: Checkout code
16
+ uses: actions/checkout@v4
17
17
  with:
18
- node-version-file: '.node-version'
18
+ fetch-depth: 0
19
+
19
20
  - uses: pnpm/action-setup@v4
20
21
  name: Install pnpm
22
+
23
+ - uses: actions/setup-node@v4
24
+ with:
25
+ node-version-file: '.node-version'
26
+
21
27
  - uses: googleapis/release-please-action@v4
22
28
  id: release
23
29
  with:
24
30
  release-type: node
31
+
25
32
  - run: 'echo "//registry.npmjs.org/:_authToken=${{secrets.NPM_TOKEN}}" > ~/.npmrc'
26
33
  if: ${{ steps.release.outputs.release_created }}
34
+
35
+ - name: Install dependencies
36
+ run: pnpm i --frozen-lockfile
37
+
38
+ - run: pnpm build
39
+ if: ${{ steps.release.outputs.release_created }}
40
+
27
41
  - run: pnpm publish --no-git-checks
28
42
  if: ${{ steps.release.outputs.release_created }}
package/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.0.1](https://github.com/marklai1998/express-response-middleware/compare/v2.0.0...v2.0.1) (2025-03-15)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * build entry file ([f82450f](https://github.com/marklai1998/express-response-middleware/commit/f82450fa402ced9307bd31192ca34cfbcb9dc4a3))
9
+
10
+ ## [2.0.0](https://github.com/marklai1998/express-response-middleware/compare/v1.0.0...v2.0.0) (2025-03-15)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * rename head middleware
16
+ * merge async headers
17
+ * set min node version
18
+ * merge async json
19
+ * rename function
20
+ * remove 204 handling
21
+ * remove scalar content type handling
22
+ * remove run on error option
23
+ * esm ([#4](https://github.com/marklai1998/express-response-middleware/issues/4))
24
+
25
+ ### Features
26
+
27
+ * end handling ([f7884fd](https://github.com/marklai1998/express-response-middleware/commit/f7884fddbb6f986aa4f893cde0e8d6a1630b4cc8))
28
+ * esm ([#4](https://github.com/marklai1998/express-response-middleware/issues/4)) ([14ec0ed](https://github.com/marklai1998/express-response-middleware/commit/14ec0ed0f3792dedc6d3a9ae85b6c1f1dabb4cdf))
29
+ * jsonp support ([f724345](https://github.com/marklai1998/express-response-middleware/commit/f724345f3aa76c5b5631ace316fd283fecdb9933))
30
+ * merge async headers ([f7fd7c4](https://github.com/marklai1998/express-response-middleware/commit/f7fd7c4c75b57434b9eafbce18116edf94c7c36d))
31
+ * merge async json ([618b6f5](https://github.com/marklai1998/express-response-middleware/commit/618b6f5f0ba4d12b355583c5b99ff1b1ed9bec59))
32
+ * remove 204 handling ([f1c08b1](https://github.com/marklai1998/express-response-middleware/commit/f1c08b17c9f24fd7480e247508db9e7e9c0d7a96))
33
+ * remove run on error option ([ca8d1e3](https://github.com/marklai1998/express-response-middleware/commit/ca8d1e37ad25b346b7b17eeae6a193d4afa265cc))
34
+ * remove scalar content type handling ([3137434](https://github.com/marklai1998/express-response-middleware/commit/3137434c3a261f78304a449f5d7a39365f581b2d))
35
+ * rename function ([fae0ee9](https://github.com/marklai1998/express-response-middleware/commit/fae0ee9dbbf7b22216c5980d633c5640cccfb536))
36
+ * rename head middleware ([ce6c89a](https://github.com/marklai1998/express-response-middleware/commit/ce6c89a1faa234bde62315f0f9d8c364d0d0098d))
37
+ * send middleware ([d609cce](https://github.com/marklai1998/express-response-middleware/commit/d609ccee1bfd789ba75cbea6c8f09cfbb533a892))
38
+ * set min node version ([6d1a51b](https://github.com/marklai1998/express-response-middleware/commit/6d1a51b313e27095b88fbf8f3609fd518e489a5a))
39
+ * write async support ([4aef628](https://github.com/marklai1998/express-response-middleware/commit/4aef628b5e2f48efe2e4f6579841769a207767b8))
40
+
41
+
42
+ ### Bug Fixes
43
+
44
+ * async handler ([5ab900b](https://github.com/marklai1998/express-response-middleware/commit/5ab900b80a3d612cf74d5be2f215473e9ee6a327))
45
+ * async handler ([d919cb3](https://github.com/marklai1998/express-response-middleware/commit/d919cb36aea38f58e9691a9b9879797ada6fd1b4))
46
+ * calling end in json without chaining ([2160658](https://github.com/marklai1998/express-response-middleware/commit/216065829dd1d95593bc188086050c3121912468))
47
+ * end hook ([e91ad26](https://github.com/marklai1998/express-response-middleware/commit/e91ad263eb828b00f1bdb0cf96fa091849125597))
48
+ * json middeware stacking ([44d51f8](https://github.com/marklai1998/express-response-middleware/commit/44d51f8782d3a112964e48c72ad92c4222ac476f))
49
+ * json middleware stacking ([c6cd298](https://github.com/marklai1998/express-response-middleware/commit/c6cd29836c0e86ab478004a573f321f648404251))
50
+ * set express as peer ([6409ec1](https://github.com/marklai1998/express-response-middleware/commit/6409ec12ce7ba90c187f9d56d0e6935625ebdaa7))
51
+ * stop hooks from calling when header is sent ([6fff520](https://github.com/marklai1998/express-response-middleware/commit/6fff520355b82d3fe2137919c86f6c2b32ae534b))
52
+
3
53
  ## 1.0.0 (2025-03-03)
4
54
 
5
55
 
package/README.md CHANGED
@@ -1,115 +1,179 @@
1
1
  # express-response-middleware
2
2
 
3
- Middleware for express responses.
3
+ > [!NOTE]
4
+ > Come from express-mung? Checkout the [Migration Guide](docs/MIGRATE_FROM_MUNG.md)
5
+
6
+ <div align="center">
7
+
8
+ Middleware for express responses. Fork of [express-mung](https://www.npmjs.com/package/express-mung)
4
9
 
5
10
  This package allows synchronous and asynchronous transformation of an express response. This is a similar concept to the express middleware for a request but for a response. Note that the middleware is executed in LIFO order. It is implemented by monkey patching (hooking) the `res.end`, `res.json`, or `res.write` methods.
6
11
 
7
- ## Getting started [![npm version](https://badge.fury.io/js/express-response-middleware.svg)](https://badge.fury.io/js/express-response-middleware)
12
+ [Installation](#-installation) | [Quick Start](#-quick-start) | [API](#-api) | [Contributing](#-contributing)
8
13
 
9
- $ npm install express-response-middleware --save
14
+ </div>
10
15
 
11
- Then in your middleware
16
+ ## 📦 Installation
12
17
 
13
- var responseMiddleware = require('express-response-middleware');
18
+ ### NPM
19
+
20
+ ```bash
21
+ npm i express-response-middleware
22
+ ```
14
23
 
15
- module.exports = responseMiddleware.json(my_transform);
24
+ ### Yarn
25
+
26
+ ```
27
+ yarn add express-response-middleware
28
+ ```
16
29
 
17
- ## Usage
30
+ ### PNPM
31
+
32
+ ```
33
+ pnpm i express-response-middleware
34
+ ```
35
+
36
+ ## 🚀 Quick Start
18
37
 
19
38
  Sample middleware (redact.js) to remove classified information.
20
39
 
21
40
  ```javascript
22
- 'use strict'
23
- const responseMiddleware = require('express-response-middleware')
41
+ import { jsonMiddleware } from 'express-response-middleware'
24
42
 
25
43
  /* Remove any classified information from the response. */
26
- function redact(body, req, res) {
27
- if (body.secret) body.secret = '****'
28
- // ...
29
- return body
30
- }
31
-
32
- module.exports = responseMiddleware.json(redact)
44
+ export const hideSecretMiddleware = jsonMiddleware((body, req, res) => {
45
+ if (body.secret) body.secret = '****'
46
+ // ...
47
+ return body
48
+ })
33
49
  ```
34
50
 
35
51
  then add to your `app.js` file (before the route handling middleware)
36
52
 
37
53
  ```javascript
38
- app.use(require('./redact'))
54
+ app.use(hideSecretMiddleware)
39
55
  ```
40
56
 
41
- and [_That's all folks!_](https://www.youtube.com/watch?v=gBzJGckMYO4)
57
+ ## 💻 API
42
58
 
43
- See the mocha [tests](https://github.com/marklai1998/express-response-middleware/tree/master/test) for some more examples.
59
+ - [Json Middleware](#jsonmiddleware)
60
+ - [Jsonp Middleware](#jsonpmiddleware)
61
+ - [Send Middleware](#sendmiddleware)
62
+ - [End Middleware](#endMiddleware)
63
+ - [Write Middleware](#endMiddleware)
64
+ - Legacy docs
65
+ - [V1](docs/V1_README.md)
44
66
 
45
- ## Reference
67
+ ### `jsonMiddleware`
46
68
 
47
- ### responseMiddleware.json(fn, [options])
69
+ Intercept `res.json`, allow transform the JSON body of the response.
48
70
 
49
- Transform the JSON body of the response.
71
+ ```ts
72
+ import { jsonMiddleware } from 'express-response-middleware'
50
73
 
51
- `fn(json, req, res)` receives the JSON as an object, the `req` and `res`. It returns the modified body. If `undefined` is returned (i.e. nothing) then the original JSON is assumed to be modified. If `null` is returned, then a 204 No Content HTTP status is returned to client.
74
+ const myMiddleware = jsonMiddleware((json, req, res) => {
75
+ // your code here
76
+ return json
77
+ })
78
+ ```
52
79
 
53
- ### responseMiddleware.jsonAsync(fn, [options])
80
+ ### `jsonpMiddleware`
54
81
 
55
- Asynchronously transform the JSON body of the response.
82
+ Intercept `res.jsonp`, allow transform the JSON body of the response.
56
83
 
57
- `fn(json, req, res)` receives the JSON as an object, the `req` and `res`. It returns a promise to a modified body. The promise returns an `object.` If it is `null` then a 204 No Content is sent to the client.
84
+ ```ts
85
+ import { jsonpMiddleware } from 'express-response-middleware'
58
86
 
59
- ### responseMiddleware.headers(fn)
87
+ const myMiddleware = jsonpMiddleware((json, req, res) => {
88
+ // your code here
89
+ return json
90
+ })
91
+ ```
60
92
 
61
- Transform the HTTP headers of the response.
93
+ ### `sendMiddleware`
62
94
 
63
- `fn(req, res)` receives the `req` and `res`. It should modify the header(s) and then return.
95
+ Intercept `res.send`, allow transform the body of the response.
64
96
 
65
- ### responseMiddleware.headersAsync(fn)
97
+ ```ts
98
+ import { sendMiddleware } from 'express-response-middleware'
66
99
 
67
- Asynchronously transform the HTTP headers of the response.
100
+ const myMiddleware = sendMiddleware((payload, req, res) => {
101
+ // your code here
102
+ return payload
103
+ })
104
+ ```
68
105
 
69
- `fn(req, res)` receives the `req` and `res`. It returns a `promise` to modify the header(s).
106
+ ### `endMiddleware`
70
107
 
71
- ### responseMiddleware.write(fn, [options])
108
+ Intercept `end.json`, allow transform the HTTP headers of the response.
72
109
 
73
- `fn(chunk, encoding, req, res)` receives the string or buffer as `chunk`, its `encoding` if applicable (`null` otherwise), `req` and `res`. It returns the modified body. If `undefined` is returned (i.e. nothing) then the original unmodified chunk is used.
110
+ ```ts
111
+ import { endMiddleware } from 'express-response-middleware'
74
112
 
75
- ### Notes
113
+ const myMiddleware = endMiddleware((req, res) => {
114
+ // your code here
115
+ })
116
+ ```
76
117
 
77
- - when `responseMiddleware.json*` receives a scalar value then the `content-type` is switched `text-plain`.
118
+ > [!CAUTION]
119
+ > Sending a response while in `endMiddleware*` is **undefined behaviour** and will most likely result in an error
78
120
 
79
- - when `responseMiddleware.json*` detects that a response has been sent, it will abort.
121
+ ### `writeMiddleware`
80
122
 
81
- - sending a response while in `responseMiddleware.headers*` is **undefined behaviour** and will most likely result in an error.
123
+ Intercept `end.write`, allow transform buffer.
82
124
 
83
- - when `responseMiddleware.write` detects that a response has completed (i.e. if `res.end` has been called), it will abort.
125
+ ```ts
126
+ import { writeMiddleware } from 'express-response-middleware'
84
127
 
85
- - calling `res.json` or `res.send` from `responseMiddleware.write` can lead to unexpected behavior since they end the response internally.
128
+ const myMiddleware = writeMiddleware((chunk, encoding, req, res) => {
129
+ // your code here
130
+ return chunk
131
+ })
132
+ ```
86
133
 
87
- ### options
134
+ > [!CAUTION]
135
+ > Promise callback support is limited, it doesn't resolve multiple write call yet [Code](src/writeMiddleware.ts)
88
136
 
89
- - `runOnError`, when `true` the callback function is always invoked. When `false` (the default) the callback function is only invoked when the response is not in error.
137
+ - When `writeMiddleware` detects that a response has completed (i.e. if `res.end` has been called), it will abort.
138
+ - Calling `res.json` or `res.send` from `writeMiddleware` can lead to unexpected behavior since they end the response internally.
139
+ - The returned value of `res.write` will be inaccurate when using `writeMiddleware`, beware if you rely on it
140
+ - `res.end` after `res.write` would not trigger endMiddleware, as header already sent
90
141
 
91
142
  ## Exception handling
92
143
 
93
144
  `responseMiddleware` catches any exception (synchronous, asynchronous or Promise reject) and sends an HTTP 500 response with the exception message. You should handle your own error if you want different behavior
94
145
 
95
- ## Migrate from `express-mung`
146
+ ## 🤝 Contributing
147
+
148
+ ### TODO
149
+
150
+ Current state project is up to modern standard and support all of the `express-mung` use case, here is the list that I think can improve on.
96
151
 
97
- - Update the import
98
- - Rename option `mungError` to `runOnError`
99
- - Add try catch to your function body if used to override mung.onError()
152
+ - [ ] Support multiple write call with `writeMiddleware` + async handler
100
153
 
154
+ ### Development
155
+
156
+ #### Local Development
157
+
158
+ ```bash
159
+ pnpm i
160
+ pnpm test
101
161
  ```
102
- - import mung from 'express-mung'
103
- + import mung from 'express-mung'
104
-
105
- const myMiddleware = mung.json(() => {
106
- // code here
107
- },
108
- - { mungError: true }
109
- + { runOnError: true }
110
- )
162
+
163
+ #### Build
164
+
165
+ ```bash
166
+ pnpm build
111
167
  ```
112
168
 
113
- # License
169
+ ### Release
170
+
171
+ This repo uses [Release Please](https://github.com/google-github-actions/release-please-action) to release.
172
+
173
+ #### To release a new version
114
174
 
115
- The MIT license
175
+ 1. Merge your changes into the `main` branch.
176
+ 2. An automated GitHub Action will run, triggering the creation of a Release PR.
177
+ 3. Merge the release PR.
178
+ 4. Wait for the second GitHub Action to run automatically.
179
+ 5. Congratulations, you're all set!
@@ -0,0 +1,199 @@
1
+ 'use strict';
2
+
3
+ var node_async_hooks = require('node:async_hooks');
4
+
5
+ const errorHandler = (err, _req, res, _next) => {
6
+ res.status(500).set("content-language", "en").json({ message: err.message }).end();
7
+ return res;
8
+ };
9
+
10
+ const isInSend$1 = new node_async_hooks.AsyncLocalStorage();
11
+
12
+ const jsonMiddleware = (fn) => (req, res, next) => {
13
+ const originalJsonFn = res.json;
14
+ const originalSendFn = res.send;
15
+ res.send = function() {
16
+ return isInSend$1.run(
17
+ true,
18
+ () => originalSendFn.apply(this, arguments)
19
+ );
20
+ };
21
+ res.json = function(json) {
22
+ const originalEndFn = res.end;
23
+ if (res.headersSent) return res;
24
+ let mayBePromise;
25
+ try {
26
+ mayBePromise = fn(json, req, res);
27
+ } catch (e) {
28
+ res.json = originalJsonFn;
29
+ errorHandler(e, req, res);
30
+ return res;
31
+ }
32
+ if (mayBePromise instanceof Promise) {
33
+ mayBePromise.then((result) => {
34
+ if (res.headersSent) return;
35
+ res.end = originalEndFn;
36
+ originalJsonFn.call(this, result === void 0 ? json : result);
37
+ }).catch((e) => {
38
+ res.json = originalJsonFn;
39
+ res.end = originalEndFn;
40
+ errorHandler(e, req, res);
41
+ });
42
+ res.end = function() {
43
+ if (isInSend$1.getStore()) {
44
+ originalEndFn.apply(this, arguments);
45
+ }
46
+ return res;
47
+ };
48
+ } else {
49
+ const result = mayBePromise;
50
+ if (res.headersSent) return res;
51
+ originalJsonFn.call(this, result === void 0 ? json : result);
52
+ }
53
+ return res;
54
+ };
55
+ next();
56
+ };
57
+
58
+ const endMiddleware = (fn) => (req, res, next) => {
59
+ const originalEndFn = res.end;
60
+ res.end = function() {
61
+ if (res.headersSent) return originalEndFn.apply(this, arguments);
62
+ let mayBePromise;
63
+ try {
64
+ mayBePromise = fn(req, res);
65
+ } catch (e) {
66
+ res.end = originalEndFn;
67
+ errorHandler(e, req, res);
68
+ return res;
69
+ }
70
+ if (mayBePromise instanceof Promise) {
71
+ mayBePromise.then(() => {
72
+ if (res.headersSent) {
73
+ console.error(
74
+ "sending response while in endMiddleware is undefined behaviour"
75
+ );
76
+ return;
77
+ }
78
+ originalEndFn.apply(this, arguments);
79
+ }).catch((e) => {
80
+ res.end = originalEndFn;
81
+ errorHandler(e, req, res);
82
+ });
83
+ res.end = function() {
84
+ return res;
85
+ };
86
+ } else {
87
+ if (res.headersSent) {
88
+ console.error(
89
+ "sending response while in endMiddleware is undefined behaviour"
90
+ );
91
+ return res;
92
+ }
93
+ return originalEndFn.apply(this, arguments);
94
+ }
95
+ return res;
96
+ };
97
+ next();
98
+ };
99
+
100
+ const writeMiddleware = (fn) => (req, res, next) => {
101
+ const originalWrite = res.write;
102
+ const originalEndFn = res.end;
103
+ res.write = function(chunk) {
104
+ if (res.writableEnded) return false;
105
+ let mayBePromise;
106
+ try {
107
+ mayBePromise = fn(
108
+ chunk,
109
+ // Since `encoding` is an optional argument to `res.write`,
110
+ // make sure it is a string and not actually the callback.
111
+ typeof arguments[1] === "string" ? arguments[1] : null,
112
+ req,
113
+ res
114
+ );
115
+ } catch (e) {
116
+ errorHandler(e, req, res);
117
+ return false;
118
+ }
119
+ if (mayBePromise instanceof Promise) {
120
+ mayBePromise.then((result) => {
121
+ try {
122
+ res.end = originalEndFn;
123
+ if (res.writableEnded) return false;
124
+ arguments[0] = result === void 0 ? chunk : result;
125
+ const writeResponse = originalWrite.apply(res, arguments);
126
+ if (res.__isEnd) res.end();
127
+ return writeResponse;
128
+ } catch (e) {
129
+ errorHandler(e, req, res);
130
+ return false;
131
+ }
132
+ });
133
+ res.end = function() {
134
+ this.__isEnd = true;
135
+ return res;
136
+ };
137
+ return false;
138
+ } else {
139
+ const result = mayBePromise;
140
+ if (res.writableEnded) return false;
141
+ arguments[0] = result === void 0 ? chunk : result;
142
+ return originalWrite.apply(res, arguments);
143
+ }
144
+ };
145
+ next();
146
+ };
147
+
148
+ const isInSend = new node_async_hooks.AsyncLocalStorage();
149
+ const jsonpMiddleware = (fn) => (req, res, next) => {
150
+ const originalJsonpFn = res.jsonp;
151
+ const originalSendFn = res.send;
152
+ res.send = function() {
153
+ return isInSend.run(
154
+ true,
155
+ () => originalSendFn.apply(this, arguments)
156
+ );
157
+ };
158
+ res.jsonp = function(json) {
159
+ const originalEndFn = res.end;
160
+ if (res.headersSent) return res;
161
+ let mayBePromise;
162
+ try {
163
+ mayBePromise = fn(json, req, res);
164
+ } catch (e) {
165
+ res.json = originalJsonpFn;
166
+ errorHandler(e, req, res);
167
+ return res;
168
+ }
169
+ if (mayBePromise instanceof Promise) {
170
+ mayBePromise.then((result) => {
171
+ if (res.headersSent) return;
172
+ res.end = originalEndFn;
173
+ originalJsonpFn.call(this, result === void 0 ? json : result);
174
+ }).catch((e) => {
175
+ res.jsonp = originalJsonpFn;
176
+ res.end = originalEndFn;
177
+ errorHandler(e, req, res);
178
+ });
179
+ res.end = function() {
180
+ if (isInSend.getStore()) {
181
+ originalEndFn.apply(this, arguments);
182
+ }
183
+ return res;
184
+ };
185
+ } else {
186
+ const result = mayBePromise;
187
+ if (res.headersSent) return res;
188
+ originalJsonpFn.call(this, result === void 0 ? json : result);
189
+ }
190
+ return res;
191
+ };
192
+ next();
193
+ };
194
+
195
+ exports.endMiddleware = endMiddleware;
196
+ exports.jsonMiddleware = jsonMiddleware;
197
+ exports.jsonpMiddleware = jsonpMiddleware;
198
+ exports.writeMiddleware = writeMiddleware;
199
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../../src/utils/errorHandler.ts","../../src/utils/asyncLocalStorage.ts","../../src/jsonMiddleware.ts","../../src/endMiddleware.ts","../../src/writeMiddleware.ts","../../src/jsonpMiddleware.ts"],"sourcesContent":["import { ErrorRequestHandler } from 'express'\n\nexport const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {\n res\n .status(500)\n .set('content-language', 'en')\n .json({ message: err.message })\n .end()\n return res\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nexport const isInSend = new AsyncLocalStorage<boolean>()\n","import { Request, RequestHandler, Response } from 'express'\nimport { errorHandler } from './utils/errorHandler'\nimport { isInSend } from './utils/asyncLocalStorage'\n\nexport type TransformJson<T = {}> = (\n body: T,\n request: Request,\n response: Response\n) => unknown | Promise<unknown>\n\nexport const jsonMiddleware =\n (fn: TransformJson): RequestHandler =>\n (req, res, next) => {\n const originalJsonFn = res.json\n const originalSendFn = res.send\n\n res.send = function (this: Response) {\n return isInSend.run(true, () =>\n originalSendFn.apply(this, arguments as any)\n )\n }\n\n res.json = function (this: Response, json) {\n const originalEndFn = res.end\n\n if (res.headersSent) return res\n\n let mayBePromise\n try {\n mayBePromise = fn(json, req, res)\n } catch (e) {\n res.json = originalJsonFn\n errorHandler(e, req, res, next)\n return res\n }\n\n if (mayBePromise instanceof Promise) {\n mayBePromise\n .then(result => {\n if (res.headersSent) return\n res.end = originalEndFn\n\n originalJsonFn.call(this, result === undefined ? json : result)\n })\n .catch(e => {\n res.json = originalJsonFn\n res.end = originalEndFn\n errorHandler(e, req, res, next)\n })\n\n // Prevent end being called wile promise still running\n res.end = function (this: Response) {\n // Res.send will call Res.end, when send is call inside the middleware, do it actually\n if (isInSend.getStore()) {\n originalEndFn.apply(this, arguments as any)\n }\n return res\n }\n } else {\n const result = mayBePromise\n\n if (res.headersSent) return res\n\n originalJsonFn.call(this, result === undefined ? json : result)\n }\n\n return res\n }\n\n next()\n }\n","import { Request, RequestHandler, Response } from 'express'\nimport { errorHandler } from './utils/errorHandler'\n\nexport type TransformEnd = (\n request: Request,\n response: Response\n) => unknown | Promise<unknown>\n\nexport const endMiddleware =\n (fn: TransformEnd): RequestHandler =>\n (req, res, next) => {\n const originalEndFn = res.end\n\n res.end = function (this: Response) {\n if (res.headersSent) return originalEndFn.apply(this, arguments as any)\n\n let mayBePromise\n try {\n mayBePromise = fn(req, res)\n } catch (e) {\n res.end = originalEndFn\n errorHandler(e, req, res, next)\n return res\n }\n\n if (mayBePromise instanceof Promise) {\n mayBePromise\n .then(() => {\n if (res.headersSent) {\n console.error(\n 'sending response while in endMiddleware is undefined behaviour'\n )\n return\n }\n\n originalEndFn.apply(this, arguments as any)\n })\n .catch(e => {\n res.end = originalEndFn\n errorHandler(e, req, res, next)\n })\n\n res.end = function (this: Response) {\n return res\n }\n } else {\n if (res.headersSent) {\n console.error(\n 'sending response while in endMiddleware is undefined behaviour'\n )\n return res\n }\n\n return originalEndFn.apply(this, arguments as any)\n }\n\n return res\n }\n\n next()\n }\n","import { Request, RequestHandler, Response } from 'express'\nimport { errorHandler } from './utils/errorHandler'\n\nexport type TransformChunk = (\n chunk: string | Buffer,\n encoding: string | null,\n request: Request,\n response: Response\n) => void | string | Buffer | Promise<void> | Promise<string> | Promise<Buffer>\n\nexport const writeMiddleware =\n (fn: TransformChunk): RequestHandler =>\n (req, res, next) => {\n const originalWrite = res.write\n const originalEndFn = res.end\n\n res.write = function (this: Response, chunk) {\n if (res.writableEnded) return false\n\n let mayBePromise\n try {\n mayBePromise = fn(\n chunk,\n // Since `encoding` is an optional argument to `res.write`,\n // make sure it is a string and not actually the callback.\n typeof arguments[1] === 'string' ? arguments[1] : null,\n req,\n res\n )\n } catch (e) {\n errorHandler(e, req, res, next)\n return false\n }\n\n if (mayBePromise instanceof Promise) {\n mayBePromise.then(result => {\n try {\n res.end = originalEndFn\n\n if (res.writableEnded) return false\n\n arguments[0] = result === undefined ? chunk : result\n\n const writeResponse = originalWrite.apply(res, arguments as any)\n\n if (res.__isEnd) res.end()\n\n return writeResponse\n } catch (e) {\n errorHandler(e, req, res, next)\n return false\n }\n })\n\n res.end = function (this: Response) {\n this.__isEnd = true\n return res\n }\n return false\n } else {\n const result = mayBePromise\n if (res.writableEnded) return false\n\n arguments[0] = result === undefined ? chunk : result\n return originalWrite.apply(res, arguments as any)\n }\n }\n\n next()\n }\n","import { Request, RequestHandler, Response } from 'express'\nimport { errorHandler } from './utils/errorHandler'\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nexport type TransformJsonp<T = {}> = (\n body: T,\n request: Request,\n response: Response\n) => unknown | Promise<unknown>\n\nconst isInSend = new AsyncLocalStorage<boolean>()\n\nexport const jsonpMiddleware =\n (fn: TransformJsonp): RequestHandler =>\n (req, res, next) => {\n const originalJsonpFn = res.jsonp\n const originalSendFn = res.send\n\n res.send = function (this: Response) {\n return isInSend.run(true, () =>\n originalSendFn.apply(this, arguments as any)\n )\n }\n\n res.jsonp = function (this: Response, json) {\n const originalEndFn = res.end\n\n if (res.headersSent) return res\n\n let mayBePromise\n try {\n mayBePromise = fn(json, req, res)\n } catch (e) {\n res.json = originalJsonpFn\n errorHandler(e, req, res, next)\n return res\n }\n\n if (mayBePromise instanceof Promise) {\n mayBePromise\n .then(result => {\n if (res.headersSent) return\n res.end = originalEndFn\n\n originalJsonpFn.call(this, result === undefined ? json : result)\n })\n .catch(e => {\n res.jsonp = originalJsonpFn\n res.end = originalEndFn\n errorHandler(e, req, res, next)\n })\n\n // Prevent end being called wile promise still running\n res.end = function (this: Response) {\n // Res.send will call Res.end, when send is call inside the middleware, do it actually\n if (isInSend.getStore()) {\n originalEndFn.apply(this, arguments as any)\n }\n return res\n }\n } else {\n const result = mayBePromise\n\n if (res.headersSent) return res\n\n originalJsonpFn.call(this, result === undefined ? json : result)\n }\n\n return res\n }\n\n next()\n }\n"],"names":["isInSend","AsyncLocalStorage"],"mappings":";;;;AAEO,MAAM,YAAoC,GAAA,CAAC,GAAK,EAAA,IAAA,EAAM,KAAK,KAAU,KAAA;AAC1E,EAAA,GAAA,CACG,MAAO,CAAA,GAAG,CACV,CAAA,GAAA,CAAI,oBAAoB,IAAI,CAAA,CAC5B,IAAK,CAAA,EAAE,OAAS,EAAA,GAAA,CAAI,OAAQ,EAAC,EAC7B,GAAI,EAAA;AACP,EAAO,OAAA,GAAA;AACT,CAAA;;ACPa,MAAAA,UAAA,GAAW,IAAIC,kCAA2B,EAAA;;ACQhD,MAAM,iBACX,CAAC,EAAA,KACD,CAAC,GAAA,EAAK,KAAK,IAAS,KAAA;AAClB,EAAA,MAAM,iBAAiB,GAAI,CAAA,IAAA;AAC3B,EAAA,MAAM,iBAAiB,GAAI,CAAA,IAAA;AAE3B,EAAA,GAAA,CAAI,OAAO,WAA0B;AACnC,IAAA,OAAOD,UAAS,CAAA,GAAA;AAAA,MAAI,IAAA;AAAA,MAAM,MACxB,cAAA,CAAe,KAAM,CAAA,IAAA,EAAM,SAAgB;AAAA,KAC7C;AAAA,GACF;AAEA,EAAI,GAAA,CAAA,IAAA,GAAO,SAA0B,IAAM,EAAA;AACzC,IAAA,MAAM,gBAAgB,GAAI,CAAA,GAAA;AAE1B,IAAI,IAAA,GAAA,CAAI,aAAoB,OAAA,GAAA;AAE5B,IAAI,IAAA,YAAA;AACJ,IAAI,IAAA;AACF,MAAe,YAAA,GAAA,EAAA,CAAG,IAAM,EAAA,GAAA,EAAK,GAAG,CAAA;AAAA,aACzB,CAAG,EAAA;AACV,MAAA,GAAA,CAAI,IAAO,GAAA,cAAA;AACX,MAAa,YA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AA,CAAA,GAAY,OAAO,MAAM,CAAA;AAAA,OAChE,CACA,CAAA,KAAA,CAAM,CAAK,CAAA,KAAA;AACV,QAAA,GAAA,CAAI,KAAQ,GAAA,eAAA;AACZ,QAAA,GAAA,CAAI,GAAM,GAAA,aAAA;AACV,QAAa,YAAA,CAAA,CAAA,EAAG,GAAK,EAAA,GAAS,CAAA;AAAA,OAC/B,CAAA;AAGH,MAAA,GAAA,CAAI,MAAM,WAA0B;AAElC,QAAI,IAAA,QAAA,CAAS,UAAY,EAAA;AACvB,UAAc,aAAA,CAAA,KAAA,CAAM,MAAM,SAAgB,CAAA;AAAA;AAE5C,QAAO,OAAA,GAAA;AAAA,OACT;AAAA,KACK,MAAA;AACL,MAAA,MAAM,MAAS,GAAA,YAAA;AAEf,MAAI,IAAA,GAAA,CAAI,aAAoB,OAAA,GAAA;AAE5B,MAAA,eAAA,CAAgB,IAAK,CAAA,IAAA,EAAM,MAAW,KAAA,KAAA,CAAA,GAAY,OAAO,MAAM,CAAA;AAAA;AAGjE,IAAO,OAAA,GAAA;AAAA,GACT;AAEA,EAAK,IAAA,EAAA;AACP;;;;;;;"}
@@ -0,0 +1,24 @@
1
+ import { Request, Response, RequestHandler } from 'express';
2
+
3
+ type TransformJson<T = {}> = (body: T, request: Request, response: Response) => unknown | Promise<unknown>;
4
+ declare const jsonMiddleware: (fn: TransformJson) => RequestHandler;
5
+
6
+ type TransformEnd = (request: Request, response: Response) => unknown | Promise<unknown>;
7
+ declare const endMiddleware: (fn: TransformEnd) => RequestHandler;
8
+
9
+ type TransformChunk = (chunk: string | Buffer, encoding: string | null, request: Request, response: Response) => void | string | Buffer | Promise<void> | Promise<string> | Promise<Buffer>;
10
+ declare const writeMiddleware: (fn: TransformChunk) => RequestHandler;
11
+
12
+ type TransformJsonp<T = {}> = (body: T, request: Request, response: Response) => unknown | Promise<unknown>;
13
+ declare const jsonpMiddleware: (fn: TransformJsonp) => RequestHandler;
14
+
15
+ declare global {
16
+ namespace Express {
17
+ interface Response {
18
+ __isEnd?: boolean;
19
+ __isHooked?: boolean;
20
+ }
21
+ }
22
+ }
23
+
24
+ export { type TransformChunk, type TransformEnd, type TransformJson, type TransformJsonp, endMiddleware, jsonMiddleware, jsonpMiddleware, writeMiddleware };
@@ -0,0 +1,24 @@
1
+ import { Request, Response, RequestHandler } from 'express';
2
+
3
+ type TransformJson<T = {}> = (body: T, request: Request, response: Response) => unknown | Promise<unknown>;
4
+ declare const jsonMiddleware: (fn: TransformJson) => RequestHandler;
5
+
6
+ type TransformEnd = (request: Request, response: Response) => unknown | Promise<unknown>;
7
+ declare const endMiddleware: (fn: TransformEnd) => RequestHandler;
8
+
9
+ type TransformChunk = (chunk: string | Buffer, encoding: string | null, request: Request, response: Response) => void | string | Buffer | Promise<void> | Promise<string> | Promise<Buffer>;
10
+ declare const writeMiddleware: (fn: TransformChunk) => RequestHandler;
11
+
12
+ type TransformJsonp<T = {}> = (body: T, request: Request, response: Response) => unknown | Promise<unknown>;
13
+ declare const jsonpMiddleware: (fn: TransformJsonp) => RequestHandler;
14
+
15
+ declare global {
16
+ namespace Express {
17
+ interface Response {
18
+ __isEnd?: boolean;
19
+ __isHooked?: boolean;
20
+ }
21
+ }
22
+ }
23
+
24
+ export { type TransformChunk, type TransformEnd, type TransformJson, type TransformJsonp, endMiddleware, jsonMiddleware, jsonpMiddleware, writeMiddleware };