@universal-middleware/express 0.6.0 → 0.6.2
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/dist/index.d.ts +4 -14
- package/dist/index.js +63 -32
- package/dist/request.d.ts +0 -2
- package/dist/request.js +1 -2
- package/package.json +6 -6
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
import { createRequestAdapter } from "./request.js";
|
|
2
1
|
import { Awaitable, EnhancedMiddleware, Get, RuntimeAdapter, RuntimeAdapterTarget, UniversalFn, UniversalHandler, UniversalMiddleware, UniversalRouter, UniversalRouterInterface } from "@universal-middleware/core";
|
|
3
|
-
import { DecoratedRequest, NodeRequestAdapterOptions, sendResponse } from "@universal-middleware/node";
|
|
4
2
|
import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
|
|
3
|
+
import { DecoratedRequest, NodeRequestAdapterOptions, sendResponse } from "@universal-middleware/node";
|
|
4
|
+
import { createRequestAdapter } from "./request.js";
|
|
5
5
|
import { Readable } from "node:stream";
|
|
6
|
-
//#region src/const.d.ts
|
|
7
6
|
declare const pendingMiddlewaresSymbol: unique symbol;
|
|
8
7
|
declare const wrappedResponseSymbol: unique symbol;
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region src/types.d.ts
|
|
11
8
|
interface DecoratedServerResponse extends ServerResponse {
|
|
12
9
|
[pendingMiddlewaresSymbol]?: ((response: Response) => Awaitable<Response | undefined>)[];
|
|
13
10
|
[wrappedResponseSymbol]?: boolean;
|
|
@@ -17,8 +14,6 @@ type NodeMiddleware<In extends Universal.Context, Out extends Universal.Context>
|
|
|
17
14
|
type NodeHandler<In extends Universal.Context> = UniversalFn<UniversalHandler<In>, <R>(req: DecoratedRequest<In>, res: DecoratedServerResponse, next?: (err?: unknown) => void) => R>;
|
|
18
15
|
interface NodeAdapterHandlerOptions extends NodeRequestAdapterOptions {}
|
|
19
16
|
interface NodeAdapterMiddlewareOptions extends NodeRequestAdapterOptions {}
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region src/common.d.ts
|
|
22
17
|
/**
|
|
23
18
|
* Creates a request handler to be passed to http.createServer() or used as a
|
|
24
19
|
* middleware in Connect-style frameworks like Express.
|
|
@@ -30,8 +25,6 @@ export declare function createHandler<T extends unknown[], InContext extends Uni
|
|
|
30
25
|
export declare function createMiddleware<T extends unknown[], InContext extends Universal.Context, OutContext extends Universal.Context>(middlewareFactory: Get<T, UniversalMiddleware<InContext, OutContext>>, options?: NodeAdapterMiddlewareOptions): Get<T, NodeMiddleware<InContext, OutContext>>;
|
|
31
26
|
export declare function getContext<InContext extends Universal.Context = Universal.Context>(req: DecoratedRequest): InContext;
|
|
32
27
|
export declare function getRuntime(request: DecoratedRequest, response: DecoratedServerResponse): RuntimeAdapter;
|
|
33
|
-
//#endregion
|
|
34
|
-
//#region src/utils.d.ts
|
|
35
28
|
type ExpressRequestHandler = (req: DecoratedRequest, res: DecoratedServerResponse, next: (err?: unknown) => void) => unknown;
|
|
36
29
|
/**
|
|
37
30
|
* The parts of an Express 4 or 5 application the adapter uses.
|
|
@@ -57,7 +50,7 @@ export declare function connectToWeb(handler: ConnectMiddleware | ConnectMiddlew
|
|
|
57
50
|
export declare function createIncomingMessage(request: Request): IncomingMessage;
|
|
58
51
|
/**
|
|
59
52
|
* Creates a `ServerResponse` whose output is captured. `onReadable`'s callback gets the output stream, the headers and
|
|
60
|
-
* the status once the response starts.
|
|
53
|
+
* the status once the response starts. Its `onError` gets the error of a response destroyed before it started.
|
|
61
54
|
* @beta
|
|
62
55
|
*/
|
|
63
56
|
export declare function createServerResponse(incomingMessage: IncomingMessage): {
|
|
@@ -67,10 +60,8 @@ export declare function createServerResponse(incomingMessage: IncomingMessage):
|
|
|
67
60
|
headers: OutgoingHttpHeaders;
|
|
68
61
|
statusCode: number;
|
|
69
62
|
statusMessage: string | undefined;
|
|
70
|
-
}) => void) => void;
|
|
63
|
+
}) => void, onError?: (error: Error) => void) => void;
|
|
71
64
|
};
|
|
72
|
-
//#endregion
|
|
73
|
-
//#region src/router.d.ts
|
|
74
65
|
type App = Express;
|
|
75
66
|
/** The options `apply` passes to every middleware and handler it adapts */
|
|
76
67
|
type ApplyOptions = NodeAdapterHandlerOptions & NodeAdapterMiddlewareOptions;
|
|
@@ -82,5 +73,4 @@ declare class UniversalExpressRouter<T extends App> extends UniversalRouter impl
|
|
|
82
73
|
applyCatchAll(): this;
|
|
83
74
|
}
|
|
84
75
|
export declare function apply(app: Express, middlewares: EnhancedMiddlewareExpress[], options?: ApplyOptions): void;
|
|
85
|
-
//#endregion
|
|
86
76
|
export { type App, type ConnectMiddleware, type ConnectMiddlewareBoolean, type DecoratedRequest, type DecoratedServerResponse, type NodeAdapterHandlerOptions, type NodeAdapterMiddlewareOptions, type NodeHandler, type NodeMiddleware, type UniversalExpressRouter, type WebHandler, createRequestAdapter, sendResponse };
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { UniversalRouter, apply as apply$1, bindUniversal, cancelReplacedBody, contextSymbol, getAdapterRuntime, getUniversal, universalSymbol } from "@universal-middleware/core";
|
|
1
|
+
import { UniversalRouter, apply as apply$1, bindUniversal, cancelReplacedBody, contextSymbol, getAdapterRuntime, getUniversal, universalSymbol, withMutableHeaders } from "@universal-middleware/core";
|
|
3
2
|
import { BadRequestError, requestSymbol, responseAdapter, sendResponse, setResponseHeaders } from "@universal-middleware/node";
|
|
3
|
+
import { createRequestAdapter, expressOrigin } from "./request.js";
|
|
4
4
|
import { EventEmitter, once } from "node:events";
|
|
5
5
|
import { ServerResponse } from "node:http";
|
|
6
6
|
import { PassThrough, Readable } from "node:stream";
|
|
7
|
-
|
|
7
|
+
// src/const.ts
|
|
8
8
|
const pendingMiddlewaresSymbol = Symbol.for("unPendingMiddlewares");
|
|
9
9
|
const wrappedResponseSymbol = Symbol.for("unWrappedResponse");
|
|
10
|
-
|
|
11
|
-
//#region src/body.ts
|
|
10
|
+
// src/body.ts
|
|
12
11
|
const MAX_LENT_BYTES = 1048576;
|
|
12
|
+
let warned = false;
|
|
13
13
|
const lentSymbol = Symbol("universal-middleware.lentBody");
|
|
14
14
|
/**
|
|
15
15
|
* Create the `Request` for `req`. Its body reads the Node request lazily and without ending it, so that
|
|
@@ -95,11 +95,14 @@ var LentBody = class {
|
|
|
95
95
|
}
|
|
96
96
|
delete req[requestSymbol];
|
|
97
97
|
if (this.held.length > 0) req.unshift(Buffer.concat(this.held));
|
|
98
|
+
else if (this.heldBytes > MAX_LENT_BYTES && !warned) {
|
|
99
|
+
console.warn("A universal middleware read more than 1 MiB of the request body, so the next Express handler gets it empty or cut short. See https://github.com/magne4000/universal-middleware/issues/463");
|
|
100
|
+
warned = true;
|
|
101
|
+
}
|
|
98
102
|
this.controller.error(/* @__PURE__ */ new Error("The request body must be read before the middleware returns."));
|
|
99
103
|
}
|
|
100
104
|
};
|
|
101
|
-
|
|
102
|
-
//#region src/head.ts
|
|
105
|
+
// src/head.ts
|
|
103
106
|
/** Sets on `res` the status, status message and headers a `res.writeHead()` call carries, without sending them */
|
|
104
107
|
function setHead(res, statusCode, statusMessage, headers) {
|
|
105
108
|
res.statusCode = statusCode;
|
|
@@ -115,8 +118,7 @@ function setHead(res, statusCode, statusMessage, headers) {
|
|
|
115
118
|
for (const [name, value] of Object.entries(headers)) if (value !== void 0) res.setHeader(name, value);
|
|
116
119
|
}
|
|
117
120
|
}
|
|
118
|
-
|
|
119
|
-
//#region src/response.ts
|
|
121
|
+
// src/response.ts
|
|
120
122
|
/** Routes the app's writes to `writer`. As a socket would, `write()` returns false once `writer` is full, then "drain" follows. */
|
|
121
123
|
function captureOutput(nodeResponse, writer) {
|
|
122
124
|
let draining = false;
|
|
@@ -200,6 +202,7 @@ function wrapResponse(nodeResponse, next) {
|
|
|
200
202
|
try {
|
|
201
203
|
response = responseAdapter(nodeResponse, captured.readable);
|
|
202
204
|
for (const middleware of middlewares) {
|
|
205
|
+
response = withMutableHeaders(response);
|
|
203
206
|
const tmp = await middleware(response);
|
|
204
207
|
cancelReplacedBody(response, tmp);
|
|
205
208
|
if (tmp) response = tmp;
|
|
@@ -250,8 +253,7 @@ function wrapResponse(nodeResponse, next) {
|
|
|
250
253
|
nodeResponse.end = original.end;
|
|
251
254
|
}
|
|
252
255
|
}
|
|
253
|
-
|
|
254
|
-
//#region src/common.ts
|
|
256
|
+
// src/common.ts
|
|
255
257
|
function nextOr404(res, next) {
|
|
256
258
|
if (next) next();
|
|
257
259
|
else {
|
|
@@ -347,8 +349,7 @@ function getRuntime(request, response) {
|
|
|
347
349
|
})
|
|
348
350
|
});
|
|
349
351
|
}
|
|
350
|
-
|
|
351
|
-
//#region src/router.ts
|
|
352
|
+
// src/router.ts
|
|
352
353
|
var UniversalExpressRouter = class extends UniversalRouter {
|
|
353
354
|
#app;
|
|
354
355
|
#options;
|
|
@@ -372,8 +373,7 @@ function apply(app, middlewares, options) {
|
|
|
372
373
|
apply$1(router, middlewares, true);
|
|
373
374
|
Promise.resolve().then(() => router.applyCatchAll());
|
|
374
375
|
}
|
|
375
|
-
|
|
376
|
-
//#region src/utils.ts
|
|
376
|
+
// src/utils.ts
|
|
377
377
|
const statusCodesWithoutBody = [
|
|
378
378
|
100,
|
|
379
379
|
101,
|
|
@@ -394,29 +394,35 @@ function connectToWeb(handler) {
|
|
|
394
394
|
const callerContext = context ?? request.context;
|
|
395
395
|
if (callerContext) req[contextSymbol] = callerContext;
|
|
396
396
|
const { res, onReadable } = createServerResponse(req);
|
|
397
|
-
const stopForwardingAbort =
|
|
397
|
+
const stopForwardingAbort = forwardAbort(request.signal, req, res, !realReq);
|
|
398
398
|
return new Promise(async (resolve, reject) => {
|
|
399
|
+
let started = false;
|
|
399
400
|
onReadable(({ readable, headers, statusCode, statusMessage }) => {
|
|
401
|
+
started = true;
|
|
400
402
|
const hasBody = !statusCodesWithoutBody.includes(statusCode);
|
|
401
|
-
if (stopForwardingAbort)
|
|
402
|
-
|
|
403
|
-
else stopForwardingAbort();
|
|
404
|
-
}
|
|
403
|
+
if (hasBody) readable.once("close", stopForwardingAbort);
|
|
404
|
+
else stopForwardingAbort();
|
|
405
405
|
resolve(new Response(hasBody ? toWebStream(readable) : null, {
|
|
406
406
|
status: statusCode,
|
|
407
407
|
statusText: statusMessage,
|
|
408
408
|
headers: flattenHeaders(headers)
|
|
409
409
|
}));
|
|
410
|
+
}, (error) => {
|
|
411
|
+
stopForwardingAbort();
|
|
412
|
+
reject(error);
|
|
410
413
|
});
|
|
411
414
|
const next = (error) => {
|
|
412
|
-
stopForwardingAbort
|
|
413
|
-
if (error)
|
|
414
|
-
|
|
415
|
+
stopForwardingAbort();
|
|
416
|
+
if (error) {
|
|
417
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
418
|
+
if (started) res.destroy(failure);
|
|
419
|
+
else reject(failure);
|
|
420
|
+
} else resolve(void 0);
|
|
415
421
|
};
|
|
416
422
|
try {
|
|
417
423
|
if (await handler(req, res, next) === false) {
|
|
418
424
|
res.destroy();
|
|
419
|
-
stopForwardingAbort
|
|
425
|
+
stopForwardingAbort();
|
|
420
426
|
resolve(void 0);
|
|
421
427
|
}
|
|
422
428
|
} catch (e) {
|
|
@@ -454,18 +460,20 @@ function createIncomingMessage(request) {
|
|
|
454
460
|
message.once("end", () => {
|
|
455
461
|
message.complete = true;
|
|
456
462
|
});
|
|
463
|
+
const destroy = message._destroy;
|
|
464
|
+
message._destroy = (error, callback) => destroy.call(message, error, (result) => callback(message.listenerCount("error") > 0 ? result : null));
|
|
457
465
|
return message;
|
|
458
466
|
}
|
|
459
467
|
/**
|
|
460
468
|
* Creates a `ServerResponse` whose output is captured. `onReadable`'s callback gets the output stream, the headers and
|
|
461
|
-
* the status once the response starts.
|
|
469
|
+
* the status once the response starts. Its `onError` gets the error of a response destroyed before it started.
|
|
462
470
|
* @beta
|
|
463
471
|
*/
|
|
464
472
|
function createServerResponse(incomingMessage) {
|
|
465
473
|
const res = new ServerResponse(incomingMessage);
|
|
466
474
|
const passThrough = new PassThrough();
|
|
467
475
|
let handled = false;
|
|
468
|
-
const onReadable = (cb) => {
|
|
476
|
+
const onReadable = (cb, onError) => {
|
|
469
477
|
const handleReadable = () => {
|
|
470
478
|
if (handled) return;
|
|
471
479
|
handled = true;
|
|
@@ -478,6 +486,11 @@ function createServerResponse(incomingMessage) {
|
|
|
478
486
|
};
|
|
479
487
|
passThrough.once("readable", handleReadable);
|
|
480
488
|
passThrough.once("end", handleReadable);
|
|
489
|
+
passThrough.once("close", () => {
|
|
490
|
+
if (handled) return;
|
|
491
|
+
handled = true;
|
|
492
|
+
onError?.(passThrough.errored ?? /* @__PURE__ */ new Error("The response was destroyed before it started"));
|
|
493
|
+
});
|
|
481
494
|
};
|
|
482
495
|
passThrough.once("finish", () => {
|
|
483
496
|
res.emit("finish");
|
|
@@ -486,12 +499,29 @@ function createServerResponse(incomingMessage) {
|
|
|
486
499
|
res.destroy();
|
|
487
500
|
res.emit("close");
|
|
488
501
|
});
|
|
502
|
+
const destroy = res.destroy;
|
|
503
|
+
res.destroy = (error) => {
|
|
504
|
+
passThrough.destroy(error);
|
|
505
|
+
return destroy.call(res, error);
|
|
506
|
+
};
|
|
507
|
+
passThrough.on("error", () => {});
|
|
489
508
|
passThrough.on("drain", () => {
|
|
490
509
|
res.emit("drain");
|
|
491
510
|
});
|
|
492
|
-
|
|
493
|
-
res.
|
|
511
|
+
let headWritten = false;
|
|
512
|
+
res.write = function write(...args) {
|
|
513
|
+
if (!headWritten) res.writeHead(res.statusCode);
|
|
514
|
+
return passThrough.write(...args);
|
|
515
|
+
};
|
|
516
|
+
res.end = function end(...args) {
|
|
517
|
+
if (!headWritten) res.writeHead(res.statusCode);
|
|
518
|
+
passThrough.end(...args);
|
|
519
|
+
return res;
|
|
520
|
+
};
|
|
521
|
+
Object.defineProperty(res, "headersSent", { get: () => headWritten });
|
|
522
|
+
Object.defineProperty(res, "writableEnded", { get: () => passThrough.writableEnded });
|
|
494
523
|
res.writeHead = function writeHead(statusCode, statusMessage, headers) {
|
|
524
|
+
headWritten = true;
|
|
495
525
|
setHead(res, statusCode, statusMessage, headers);
|
|
496
526
|
return res;
|
|
497
527
|
};
|
|
@@ -501,16 +531,18 @@ function createServerResponse(incomingMessage) {
|
|
|
501
531
|
};
|
|
502
532
|
}
|
|
503
533
|
/**
|
|
504
|
-
* Bridges a Web `AbortSignal` to
|
|
534
|
+
* Bridges a Web `AbortSignal` to `connectToWeb`'s `req`/`res`, and returns a function that stops it.
|
|
505
535
|
* The request adapter aborts `request.signal` on `res`'s "close", which a socketless `ServerResponse` never emits.
|
|
536
|
+
* A synthetic `req` with an unfinished body fails with ECONNRESET, as Node's server fails its own requests.
|
|
506
537
|
*/
|
|
507
|
-
function forwardAbort(signal, req, res) {
|
|
538
|
+
function forwardAbort(signal, req, res, synthetic) {
|
|
508
539
|
let active = true;
|
|
509
540
|
const abort = () => {
|
|
510
541
|
if (!active) return;
|
|
511
542
|
active = false;
|
|
512
543
|
res.emit("close");
|
|
513
|
-
req.
|
|
544
|
+
const cut = synthetic && !req.complete;
|
|
545
|
+
req.destroy(cut ? Object.assign(/* @__PURE__ */ new Error("aborted"), { code: "ECONNRESET" }) : void 0);
|
|
514
546
|
};
|
|
515
547
|
if (signal.aborted) queueMicrotask(abort);
|
|
516
548
|
else signal.addEventListener("abort", abort, { once: true });
|
|
@@ -546,5 +578,4 @@ function flattenHeaders(headers) {
|
|
|
546
578
|
}
|
|
547
579
|
return flatHeaders;
|
|
548
580
|
}
|
|
549
|
-
//#endregion
|
|
550
581
|
export { apply, connectToWeb, createHandler, createIncomingMessage, createMiddleware, createRequestAdapter, createServerResponse, getContext, getRuntime, sendResponse };
|
package/dist/request.d.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { DecoratedRequest, DecoratedRequest as DecoratedRequest$1, NodeRequestAdapterOptions, PossiblyEncryptedSocket, RequestOrigin, createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
|
|
2
|
-
//#region src/request.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* The host Express gives `req` under its `trust proxy` setting: the first `X-Forwarded-Host`, when the setting
|
|
5
4
|
* trusts the peer, as Express 5's `req.host` reads it. Express 4 has no such getter: its `req.host` drops the port.
|
|
6
5
|
* The protocol needs nothing: `req.protocol` follows `trust proxy` in both, and the request adapter reads it.
|
|
7
6
|
*/
|
|
8
7
|
export declare function expressOrigin(req: DecoratedRequest$1): RequestOrigin | undefined;
|
|
9
|
-
//#endregion
|
|
10
8
|
export { type DecoratedRequest, type NodeRequestAdapterOptions, type PossiblyEncryptedSocket, createRequestAdapter, env, requestSymbol };
|
package/dist/request.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequestAdapter, env, requestSymbol } from "@universal-middleware/node";
|
|
2
|
-
|
|
2
|
+
// src/request.ts
|
|
3
3
|
/**
|
|
4
4
|
* The host Express gives `req` under its `trust proxy` setting: the first `X-Forwarded-Host`, when the setting
|
|
5
5
|
* trusts the peer, as Express 5's `req.host` reads it. Express 4 has no such getter: its `req.host` drops the port.
|
|
@@ -17,5 +17,4 @@ function trustsPeer(req) {
|
|
|
17
17
|
const trust = app.get("trust proxy fn");
|
|
18
18
|
return typeof trust === "function" && trust(req.socket?.remoteAddress, 0) === true;
|
|
19
19
|
}
|
|
20
|
-
//#endregion
|
|
21
20
|
export { createRequestAdapter, env, expressOrigin, requestSymbol };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@universal-middleware/express",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Express adapter for universal middlewares",
|
|
6
6
|
"files": [
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"node": ">=22"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@universal-middleware/core": "^0.7.
|
|
23
|
+
"@universal-middleware/core": "^0.7.2",
|
|
24
24
|
"@universal-middleware/node": "^0.2.9"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
@@ -30,11 +30,11 @@
|
|
|
30
30
|
"express": "^5.3.0",
|
|
31
31
|
"express4": "npm:express@^4.22.3",
|
|
32
32
|
"helmet": "^8.3.0",
|
|
33
|
-
"tsdown": "^0.23.
|
|
33
|
+
"tsdown": "^0.23.7",
|
|
34
34
|
"tsx": "^4.23.15",
|
|
35
|
-
"typescript": "
|
|
36
|
-
"vite": "^8.3.
|
|
37
|
-
"vitest": "^5.
|
|
35
|
+
"typescript": "7.1.0-beta",
|
|
36
|
+
"vite": "^8.3.8",
|
|
37
|
+
"vitest": "^5.1.1",
|
|
38
38
|
"@universal-middleware/tests": "0.0.2",
|
|
39
39
|
"@universal-middleware/tsdown-config": "0.0.0"
|
|
40
40
|
},
|