ultimate-express 1.3.9 → 1.3.11

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/src/response.js CHANGED
@@ -1,782 +1,786 @@
1
- /*
2
- Copyright 2024 dimden.dev
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */
16
-
17
- const cookie = require("cookie");
18
- const mime = require("mime-types");
19
- const vary = require("vary");
20
- const encodeUrl = require("encodeurl");
21
- const {
22
- normalizeType, stringify, deprecated, UP_PATH_REGEXP, decode,
23
- containsDotFile, isPreconditionFailure, isRangeFresh, NullObject
24
- } = require("./utils.js");
25
- const { Writable } = require("stream");
26
- const { isAbsolute } = require("path");
27
- const fs = require("fs");
28
- const Path = require("path");
29
- const statuses = require("statuses");
30
- const { sign } = require("cookie-signature");
31
- // events is faster at init, tseep is faster at sending events
32
- // since we create a ton of objects and dont send a ton of events, its better to use events here
33
- const { EventEmitter } = require("events");
34
- const http = require("http");
35
- const ms = require('ms');
36
- const etag = require("etag");
37
-
38
- const outgoingMessage = new http.OutgoingMessage();
39
- const symbols = Object.getOwnPropertySymbols(outgoingMessage);
40
- const kOutHeaders = symbols.find(s => s.toString() === 'Symbol(kOutHeaders)');
41
-
42
- class Socket extends EventEmitter {
43
- constructor(response) {
44
- super();
45
- this.response = response;
46
-
47
- this.on('error', (err) => {
48
- this.emit('close');
49
- });
50
- }
51
- get writable() {
52
- return !this.response.finished;
53
- }
54
-
55
- close() {
56
- if(this.response.finished) {
57
- return;
58
- }
59
- this.response.finished = true;
60
- this.emit('close');
61
- this.response._res.close();
62
- }
63
- }
64
-
65
- module.exports = class Response extends Writable {
66
- #socket = null;
67
- constructor(res, req, app) {
68
- super();
69
- this._req = req;
70
- this._res = res;
71
- this.headersSent = false;
72
- this.app = app;
73
- this.locals = new NullObject();
74
- this.finished = false;
75
- this.aborted = false;
76
- this.statusCode = 200;
77
- this.chunkedTransfer = true;
78
- this.totalSize = 0;
79
- this.headers = {
80
- 'connection': 'keep-alive',
81
- 'keep-alive': 'timeout=10'
82
- };
83
- if(this.app.get('x-powered-by')) {
84
- this.headers['x-powered-by'] = 'UltimateExpress';
85
- }
86
- // support for node internal
87
- this[kOutHeaders] = new Proxy(this.headers, {
88
- set: (obj, prop, value) => {
89
- this.set(prop, value[1]);
90
- return true;
91
- },
92
- get: (obj, prop) => {
93
- return obj[prop];
94
- }
95
- });
96
- this.body = undefined;
97
- this.on('error', (err) => {
98
- if(this.finished) {
99
- return;
100
- }
101
- this._res.cork(() => {
102
- this._res.close();
103
- this.finished = true;
104
- if(this.socketExists) this.socket.emit('close');
105
- });
106
- });
107
- }
108
-
109
- get socket() {
110
- this.socketExists = true;
111
- if(!this.#socket) {
112
- this.#socket = new Socket(this);
113
- }
114
- return this.#socket;
115
- }
116
-
117
- _write(chunk, encoding, callback) {
118
- if(this.aborted) {
119
- const err = new Error('Request aborted');
120
- err.code = 'ECONNABORTED';
121
- return this.destroy(err);
122
- }
123
- if(this.finished) {
124
- const err = new Error('Response already finished');
125
- return this.destroy(err);
126
- }
127
- this._res.cork(() => {
128
- if(!this.headersSent) {
129
- this.writeHead(this.statusCode);
130
- this._res.writeStatus(this.statusCode.toString());
131
- this.writeHeaders(typeof chunk === 'string');
132
- }
133
- if(!Buffer.isBuffer(chunk) && !(chunk instanceof ArrayBuffer)) {
134
- chunk = Buffer.from(chunk);
135
- chunk = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
136
- }
137
- if(this.chunkedTransfer) {
138
- // chunked transfer encoding
139
- this._res.write(chunk);
140
- callback();
141
- } else {
142
- // fixed size transfer encoding
143
- const lastOffset = this._res.getWriteOffset();
144
- const [ok, done] = this._res.tryEnd(chunk, this.totalSize);
145
- if(done) {
146
- this.destroy();
147
- this.finished = true;
148
- if(this.socketExists) this.socket.emit('close');
149
- callback();
150
- } else {
151
- // still writing
152
- if(!ok) {
153
- // wait until uWS is ready to accept more data
154
- this._res.onWritable((offset) => {
155
- if(this.finished) {
156
- return true;
157
- }
158
- const [ok, done] = this._res.tryEnd(chunk.slice(offset - lastOffset), this.totalSize);
159
- if(done) {
160
- this.destroy();
161
- this.finished = true;
162
- if(this.socketExists) this.socket.emit('close');
163
- callback();
164
- } else if(ok) {
165
- callback();
166
- }
167
-
168
- return ok;
169
- });
170
- } else {
171
- callback();
172
- }
173
- }
174
- }
175
- });
176
- }
177
- writeHead(statusCode, statusMessage, headers) {
178
- this.statusCode = statusCode;
179
- if(!headers) {
180
- if(!statusMessage) return;
181
- headers = statusMessage;
182
- }
183
- for(let header in headers) {
184
- this.set(header, headers[header]);
185
- }
186
- }
187
- writeHeaders(utf8) {
188
- for(const header in this.headers) {
189
- if(header === 'content-length') {
190
- // if content-length is set, disable chunked transfer encoding, since size is known
191
- this.chunkedTransfer = false;
192
- this.totalSize = parseInt(this.headers[header]);
193
- continue;
194
- }
195
- if(Array.isArray(this.headers[header])) {
196
- for(let value of this.headers[header]) {
197
- this._res.writeHeader(header, value);
198
- }
199
- } else {
200
- this._res.writeHeader(header, this.headers[header]);
201
- }
202
- }
203
- if(!this.headers['content-type']) {
204
- this._res.writeHeader('content-type', 'text/html' + (utf8 ? `; charset=utf-8` : ''));
205
- }
206
- this.headersSent = true;
207
- }
208
- _implicitHeader() {
209
- // compatibility function
210
- // usually should send headers but this is useless for us
211
- this.writeHead(this.statusCode);
212
- }
213
- status(code) {
214
- this.statusCode = parseInt(code);
215
- return this;
216
- }
217
- sendStatus(code) {
218
- return this.status(code).send(statuses.message[+code] ?? code.toString());
219
- }
220
- end(data) {
221
- if(this.finished) {
222
- return;
223
- }
224
- this.writeHead(this.statusCode);
225
- this._res.cork(() => {
226
- if(!this.headersSent) {
227
- const etagFn = this.app.get('etag fn');
228
- if(etagFn && data && !this.headers['etag'] && !this.req.noEtag) {
229
- this.headers['etag'] = etagFn(data);
230
- }
231
- const fresh = this.req.fresh;
232
- this._res.writeStatus(fresh ? '304' : this.statusCode.toString());
233
- this.writeHeaders(true);
234
- if(fresh) {
235
- this._res.end();
236
- this.finished = true;
237
- if(this.socketExists) this.socket.emit('close');
238
- return;
239
- }
240
- }
241
- const contentLength = this.headers['content-length'];
242
- if(!data && contentLength) {
243
- this._res.endWithoutBody(contentLength.toString());
244
- } else {
245
- if(data instanceof Buffer) {
246
- data = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
247
- }
248
- if(this.req.method === 'HEAD') {
249
- const length = Buffer.byteLength(data ?? '');
250
- this._res.endWithoutBody(length.toString());
251
- } else {
252
- this._res.end(data);
253
- }
254
- }
255
- this.finished = true;
256
- if(this.socketExists) this.socket.emit('close');
257
- });
258
-
259
- return this;
260
- }
261
- send(body) {
262
- if(this.headersSent) {
263
- throw new Error('Can\'t write body: Response was already sent');
264
- }
265
- const isBuffer = Buffer.isBuffer(body);
266
- if(body === null || body === undefined) {
267
- body = '';
268
- } else if(typeof body === 'object' && !isBuffer) {
269
- return this.json(body);
270
- } else if(typeof body === 'number') {
271
- if(arguments[1]) {
272
- deprecated('res.send(status, body)', 'res.status(status).send(body)');
273
- return this.status(body).send(arguments[1]);
274
- } else {
275
- deprecated('res.send(status)', 'res.sendStatus(status)');
276
- return this.sendStatus(body);
277
- }
278
- } else if(!isBuffer) {
279
- body = String(body);
280
- }
281
- if(typeof body === 'string') {
282
- const contentType = this.headers['content-type'];
283
- if(!contentType) {
284
- this.headers['content-type'] = 'text/html; charset=utf-8';
285
- } else if(!contentType.includes(';')) {
286
- this.headers['content-type'] += '; charset=utf-8';
287
- }
288
- }
289
- return this.end(body);
290
- }
291
- sendFile(path, options = new NullObject(), callback) {
292
- if(typeof path !== 'string') {
293
- throw new TypeError('path argument is required to res.sendFile');
294
- }
295
- if(typeof options === 'function') {
296
- callback = options;
297
- options = new NullObject();
298
- }
299
- if(!options) options = new NullObject();
300
- let done = callback;
301
- if(!done) done = this.req.next;
302
- // default options
303
- if(typeof options.maxAge === 'string') {
304
- options.maxAge = ms(options.maxAge);
305
- }
306
- if(typeof options.maxAge === 'undefined') {
307
- options.maxAge = 0;
308
- }
309
- if(typeof options.lastModified === 'undefined') {
310
- options.lastModified = true;
311
- }
312
- if(typeof options.cacheControl === 'undefined') {
313
- options.cacheControl = true;
314
- }
315
- if(typeof options.acceptRanges === 'undefined') {
316
- options.acceptRanges = true;
317
- }
318
- if(typeof options.etag === 'undefined') {
319
- options.etag = this.app.get('etag') !== false;
320
- }
321
- let etagFn = this.app.get('etag fn');
322
- if(options.etag && !etagFn) {
323
- etagFn = stat => {
324
- return etag(stat, { weak: true });
325
- }
326
- }
327
-
328
- // path checks
329
- if(!options.root && !isAbsolute(path)) {
330
- this.status(500);
331
- return done(new Error('path must be absolute or specify root to res.sendFile'));
332
- }
333
- if(!options.skipEncodePath) {
334
- path = encodeURI(path);
335
- }
336
- path = decode(path);
337
- if(path === -1) {
338
- this.status(400);
339
- return done(new Error('Bad Request'));
340
- }
341
- if(~path.indexOf('\0')) {
342
- this.status(400);
343
- return done(new Error('Bad Request'));
344
- }
345
- if(UP_PATH_REGEXP.test(path)) {
346
- this.status(403);
347
- return done(new Error('Forbidden'));
348
- }
349
- const parts = Path.normalize(path).split(Path.sep);
350
- const fullpath = options.root ? Path.resolve(Path.join(options.root, path)) : path;
351
- if(options.root && !fullpath.startsWith(Path.resolve(options.root))) {
352
- this.status(403);
353
- return done(new Error('Forbidden'));
354
- }
355
-
356
- // dotfile checks
357
- if(containsDotFile(parts)) {
358
- switch(options.dotfiles) {
359
- case 'allow':
360
- break;
361
- case 'deny':
362
- this.status(403);
363
- return done(new Error('Forbidden'));
364
- case 'ignore_files':
365
- const len = parts.length;
366
- if(len > 1 && parts[len - 1].startsWith('.')) {
367
- this.status(404);
368
- return done(new Error('Not found'));
369
- }
370
- break;
371
- case 'ignore':
372
- default:
373
- this.status(404);
374
- return done(new Error('Not found'));
375
- }
376
- }
377
-
378
- let stat = options._stat;
379
- if(!stat) {
380
- try {
381
- stat = fs.statSync(fullpath);
382
- } catch(err) {
383
- return done(err);
384
- }
385
- if(stat.isDirectory()) {
386
- this.status(404);
387
- return done(new Error(`Not found`));
388
- }
389
- }
390
-
391
- // headers
392
- if(!this.headers['content-type']) {
393
- const m = mime.lookup(fullpath);
394
- if(m) this.type(m);
395
- else this.type('application/octet-stream');
396
- }
397
- if(options.cacheControl) {
398
- this.headers['cache-control'] = `public, max-age=${options.maxAge / 1000}` + (options.immutable ? ', immutable' : '');
399
- }
400
- if(options.lastModified) {
401
- this.headers['last-modified'] = stat.mtime.toUTCString();
402
- }
403
- if(options.headers) {
404
- for(const header in options.headers) {
405
- this.set(header, options.headers[header]);
406
- }
407
- }
408
- if(options.setHeaders) {
409
- options.setHeaders(this, fullpath, stat);
410
- }
411
-
412
- // etag
413
- if(options.etag && etagFn && !this.headers['etag']) {
414
- this.headers['etag'] = etagFn(stat);
415
- }
416
- if(!options.etag) {
417
- this.req.noEtag = true;
418
- }
419
-
420
- // conditional requests
421
- if(isPreconditionFailure(this.req, this)) {
422
- this.status(412);
423
- return done(new Error('Precondition Failed'));
424
- }
425
-
426
- // range requests
427
- let offset = 0, len = stat.size, ranged = false;
428
- if(options.acceptRanges) {
429
- this.headers['accept-ranges'] = 'bytes';
430
- if(this.req.headers.range) {
431
- let ranges = this.req.range(stat.size, {
432
- combine: true
433
- });
434
-
435
- // if-range
436
- if(!isRangeFresh(this.req, this)) {
437
- ranges = -2;
438
- }
439
-
440
- if(ranges === -1) {
441
- this.status(416);
442
- this.headers['content-range'] = `bytes */${stat.size}`;
443
- return done(new Error('Range Not Satisfiable'));
444
- }
445
- if(ranges !== -2 && ranges.length === 1) {
446
- this.status(206);
447
- const range = ranges[0];
448
- this.headers['content-range'] = `bytes ${range.start}-${range.end}/${stat.size}`;
449
- offset = range.start;
450
- len = range.end - range.start + 1;
451
- ranged = true;
452
- }
453
- }
454
- }
455
-
456
- // if-modified-since, if-none-match
457
- if(this.req.fresh) {
458
- return this.end();
459
- }
460
-
461
- if(this.req.method === 'HEAD') {
462
- this.set('Content-Length', stat.size);
463
- return this.end();
464
- }
465
-
466
- // serve smaller files using workers
467
- if(this.app.workers.length && stat.size < 768 * 1024 && !ranged) {
468
- this.app.readFileWithWorker(fullpath).then((data) => {
469
- if(this._res.finished) {
470
- return;
471
- }
472
- this.end(data);
473
- if(callback) callback();
474
- }).catch((err) => {
475
- if(callback) callback(err);
476
- });
477
- } else {
478
- // larger files or range requests are piped over response
479
- let opts = {
480
- highWaterMark: 256 * 1024
481
- };
482
- if(ranged) {
483
- opts.start = offset;
484
- opts.end = Math.max(offset, offset + len - 1);
485
- }
486
- const file = fs.createReadStream(fullpath, opts);
487
- pipeStreamOverResponse(this, file, len, callback);
488
- }
489
- }
490
- download(path, filename, options, callback) {
491
- let done = callback;
492
- let name = filename;
493
- let opts = options || new NullObject();
494
-
495
- // support function as second or third arg
496
- if (typeof filename === 'function') {
497
- done = filename;
498
- name = null;
499
- opts = new NullObject();
500
- } else if (typeof options === 'function') {
501
- done = options;
502
- opts = new NullObject();
503
- }
504
-
505
- // support optional filename, where options may be in it's place
506
- if (typeof filename === 'object' &&
507
- (typeof options === 'function' || options === undefined)) {
508
- name = null;
509
- opts = filename;
510
- }
511
- if(!name) {
512
- name = Path.basename(path);
513
- }
514
- if(!opts.root && !isAbsolute(path)) {
515
- opts.root = process.cwd();
516
- }
517
-
518
- this.attachment(name);
519
- this.sendFile(path, opts, done);
520
- }
521
- set(field, value) {
522
- if(this.headersSent) {
523
- throw new Error('Cannot set headers after they are sent to the client');
524
- }
525
- if(typeof field === 'object') {
526
- for(const header in field) {
527
- this.set(header, field[header]);
528
- }
529
- } else {
530
- field = field.toLowerCase();
531
- if(field === 'set-cookie' && Array.isArray(value)) {
532
- value = value.join('; ');
533
- } else if(field === 'content-type') {
534
- if(!value.includes('charset=') && (value.startsWith('text/') || value === 'application/json' || value === 'application/javascript')) {
535
- value += '; charset=utf-8';
536
- }
537
- }
538
- this.headers[field] = String(value);
539
- }
540
- return this;
541
- }
542
- header(field, value) {
543
- return this.set(field, value);
544
- }
545
- setHeader(field, value) {
546
- return this.set(field, value);
547
- }
548
- get(field) {
549
- return this.headers[field.toLowerCase()];
550
- }
551
- getHeader = this.get;
552
- removeHeader(field) {
553
- delete this.headers[field.toLowerCase()];
554
- return this;
555
- }
556
- append(field, value) {
557
- field = field.toLowerCase();
558
- const old = this.headers[field];
559
- if(old) {
560
- const newVal = [];
561
- if(Array.isArray(old)) {
562
- newVal.push(...old);
563
- } else if(old) {
564
- newVal.push(old);
565
- }
566
- if(Array.isArray(value)) {
567
- newVal.push(...value);
568
- } else {
569
- newVal.push(value);
570
- }
571
- this.headers[field] = newVal;
572
- } else {
573
- this.headers[field] = value;
574
- }
575
- return this;
576
- }
577
- render(view, options, callback) {
578
- if(typeof options === 'function') {
579
- callback = options;
580
- options = new NullObject();
581
- }
582
- if(!options) {
583
- options = new NullObject();
584
- } else {
585
- options = Object.assign({}, options);
586
- }
587
- options._locals = this.locals;
588
- const done = callback || ((err, str) => {
589
- if(err) return this.req.next(err);
590
- this.send(str);
591
- });
592
-
593
- this.app.render(view, options, done);
594
- }
595
- cookie(name, value, options) {
596
- if(!options) {
597
- options = new NullObject();
598
- }
599
- let val = typeof value === 'object' ? "j:"+JSON.stringify(value) : String(value);
600
- if(options.maxAge != null) {
601
- const maxAge = options.maxAge - 0;
602
- if(!isNaN(maxAge)) {
603
- options.expires = new Date(Date.now() + maxAge);
604
- options.maxAge = Math.floor(maxAge / 1000);
605
- }
606
- }
607
- if(options.signed) {
608
- val = 's:' + sign(val, this.req.secret);
609
- }
610
-
611
- if(options.path == null) {
612
- options.path = '/';
613
- }
614
-
615
- this.append('Set-Cookie', cookie.serialize(name, val, options));
616
- return this;
617
- }
618
- clearCookie(name, options) {
619
- const opts = { path: '/', ...options, expires: new Date(1) };
620
- delete opts.maxAge;
621
- return this.cookie(name, '', opts);
622
- }
623
- attachment(filename) {
624
- this.headers['Content-Disposition'] = `attachment; filename="${filename}"`;
625
- this.type(filename.split('.').pop());
626
- return this;
627
- }
628
- format(object) {
629
- const keys = Object.keys(object).filter(v => v !== 'default');
630
- const key = keys.length > 0 ? this.req.accepts(keys) : false;
631
-
632
- this.vary('Accept');
633
-
634
- if(key) {
635
- this.set('Content-Type', normalizeType(key).value);
636
- object[key](this.req, this, this.req.next);
637
- } else if(object.default) {
638
- object.default(this.req, this, this.req.next);
639
- } else {
640
- this.status(406).send(this.app._generateErrorPage('Not Acceptable'));
641
- }
642
-
643
- return this;
644
- }
645
- json(body) {
646
- if(!this.headers['content-type']) {
647
- this.headers['content-type'] = 'application/json; charset=utf-8';
648
- }
649
- const escape = this.app.get('json escape');
650
- const replacer = this.app.get('json replacer');
651
- const spaces = this.app.get('json spaces');
652
- this.send(stringify(body, replacer, spaces, escape));
653
- }
654
- jsonp(object) {
655
- let callback = this.req.query[this.app.get('jsonp callback name')];
656
- let body = stringify(object, this.app.get('json replacer'), this.app.get('json spaces'), this.app.get('json escape'));
657
-
658
- if(!this.headers['content-type']) {
659
- this.headers['content-type'] = 'application/javascript; charset=utf-8';
660
- this.headers['X-Content-Type-Options'] = 'nosniff';
661
- }
662
-
663
- if(Array.isArray(callback)) {
664
- callback = callback[0];
665
- }
666
-
667
- if(typeof callback === 'string' && callback.length !== 0) {
668
- callback = callback.replace(/[^\[\]\w$.]/g, '');
669
-
670
- if(body === undefined) {
671
- body = '';
672
- } else if(typeof body === 'string') {
673
- // replace chars not allowed in JavaScript that are in JSON
674
- body = body
675
- .replace(/\u2028/g, '\\u2028')
676
- .replace(/\u2029/g, '\\u2029')
677
- }
678
- body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
679
- }
680
-
681
- return this.send(body);
682
- }
683
- links(links) {
684
- this.headers['link'] = Object.entries(links).map(([rel, url]) => `<${url}>; rel="${rel}"`).join(', ');
685
- return this;
686
- }
687
- location(path) {
688
- if(path === 'back') {
689
- path = this.req.get('Referrer');
690
- if(!path) path = this.req.get('Referer');
691
- if(!path) path = '/';
692
- }
693
- return this.headers['location'] = encodeUrl(path);
694
- }
695
- redirect(status, url) {
696
- if(typeof status !== 'number' && !url) {
697
- url = status;
698
- status = 302;
699
- }
700
- this.location(url);
701
- this.status(status);
702
- this.headers['content-type'] = 'text/plain; charset=utf-8';
703
- return this.send(`${statuses.message[status] ?? status}. Redirecting to ${url}`);
704
- }
705
-
706
- type(type) {
707
- let ct = type.indexOf('/') === -1
708
- ? (mime.contentType(type) || 'application/octet-stream')
709
- : type;
710
-
711
- return this.set('content-type', ct);
712
- }
713
- contentType = this.type;
714
-
715
- vary(field) {
716
- vary(this, field);
717
- return this;
718
- }
719
-
720
- get connection() {
721
- return this.socket;
722
- }
723
-
724
- get writableFinished() {
725
- return this.finished;
726
- }
727
- }
728
-
729
- function pipeStreamOverResponse(res, readStream, totalSize, callback) {
730
- readStream.on('data', (chunk) => {
731
- if(res.finished) {
732
- return readStream.destroy();
733
- }
734
- res._res.cork(() => {
735
- if(!res.headersSent) {
736
- res.writeHead(res.statusCode);
737
- res._res.writeStatus(res.statusCode.toString());
738
- res.writeHeaders(true);
739
- }
740
- const ab = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
741
-
742
- const lastOffset = res._res.getWriteOffset();
743
- const [ok, done] = res._res.tryEnd(ab, totalSize);
744
-
745
- if (done) {
746
- readStream.destroy();
747
- res.finished = true;
748
- if(res.socketExists) res.socket.emit('close');
749
- if(callback) callback();
750
- } else if (!ok) {
751
- readStream.pause();
752
-
753
- res._res.ab = ab;
754
- res._res.abOffset = lastOffset;
755
-
756
- res._res.onWritable((offset) => {
757
- if(res.finished) {
758
- return true;
759
- }
760
- const [ok, done] = res._res.tryEnd(res._res.ab.slice(offset - res._res.abOffset), totalSize);
761
- if (done) {
762
- readStream.destroy();
763
- res.finished = true;
764
- if(res.socketExists) res.socket.emit('close');
765
- if(callback) callback();
766
- } else if (ok) {
767
- readStream.resume();
768
- }
769
-
770
- return ok;
771
- });
772
- }
773
- });
774
- }).on('error', e => {
775
- if(callback) callback(e);
776
- if(!res.finished) {
777
- res._res.close();
778
- res.finished = true;
779
- if(res.socketExists) res.socket.emit('error', e);
780
- }
781
- });
782
- }
1
+ /*
2
+ Copyright 2024 dimden.dev
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ const cookie = require("cookie");
18
+ const mime = require("mime-types");
19
+ const vary = require("vary");
20
+ const encodeUrl = require("encodeurl");
21
+ const {
22
+ normalizeType, stringify, deprecated, UP_PATH_REGEXP, decode,
23
+ containsDotFile, isPreconditionFailure, isRangeFresh, NullObject
24
+ } = require("./utils.js");
25
+ const { Writable } = require("stream");
26
+ const { isAbsolute } = require("path");
27
+ const fs = require("fs");
28
+ const Path = require("path");
29
+ const statuses = require("statuses");
30
+ const { sign } = require("cookie-signature");
31
+ // events is faster at init, tseep is faster at sending events
32
+ // since we create a ton of objects and dont send a ton of events, its better to use events here
33
+ const { EventEmitter } = require("events");
34
+ const http = require("http");
35
+ const ms = require('ms');
36
+ const etag = require("etag");
37
+
38
+ const outgoingMessage = new http.OutgoingMessage();
39
+ const symbols = Object.getOwnPropertySymbols(outgoingMessage);
40
+ const kOutHeaders = symbols.find(s => s.toString() === 'Symbol(kOutHeaders)');
41
+
42
+ class Socket extends EventEmitter {
43
+ constructor(response) {
44
+ super();
45
+ this.response = response;
46
+
47
+ this.on('error', (err) => {
48
+ this.emit('close');
49
+ });
50
+ }
51
+ get writable() {
52
+ return !this.response.finished;
53
+ }
54
+
55
+ close() {
56
+ if(this.response.finished) {
57
+ return;
58
+ }
59
+ this.response.finished = true;
60
+ this.emit('close');
61
+ this.response._res.close();
62
+ }
63
+ }
64
+
65
+ module.exports = class Response extends Writable {
66
+ #socket = null;
67
+ constructor(res, req, app) {
68
+ super();
69
+ this._req = req;
70
+ this._res = res;
71
+ this.headersSent = false;
72
+ this.app = app;
73
+ this.locals = new NullObject();
74
+ this.finished = false;
75
+ this.aborted = false;
76
+ this.statusCode = 200;
77
+ this.chunkedTransfer = true;
78
+ this.totalSize = 0;
79
+ this.headers = {
80
+ 'connection': 'keep-alive',
81
+ 'keep-alive': 'timeout=10'
82
+ };
83
+ if(this.app.get('x-powered-by')) {
84
+ this.headers['x-powered-by'] = 'UltimateExpress';
85
+ }
86
+
87
+ // support for node internal
88
+ this[kOutHeaders] = new Proxy(this.headers, {
89
+ set: (obj, prop, value) => {
90
+ this.set(prop, value[1]);
91
+ return true;
92
+ },
93
+ get: (obj, prop) => {
94
+ return obj[prop];
95
+ }
96
+ });
97
+ this.body = undefined;
98
+ this.on('error', (err) => {
99
+ if(this.finished) {
100
+ return;
101
+ }
102
+ this._res.cork(() => {
103
+ this._res.close();
104
+ this.finished = true;
105
+ if(this.socketExists) this.socket.emit('close');
106
+ });
107
+ });
108
+ }
109
+
110
+ get socket() {
111
+ this.socketExists = true;
112
+ if(!this.#socket) {
113
+ this.#socket = new Socket(this);
114
+ }
115
+ return this.#socket;
116
+ }
117
+
118
+ _write(chunk, encoding, callback) {
119
+ if(this.aborted) {
120
+ const err = new Error('Request aborted');
121
+ err.code = 'ECONNABORTED';
122
+ return this.destroy(err);
123
+ }
124
+ if(this.finished) {
125
+ const err = new Error('Response already finished');
126
+ return this.destroy(err);
127
+ }
128
+ this._res.cork(() => {
129
+ if(!this.headersSent) {
130
+ this.writeHead(this.statusCode);
131
+ this._res.writeStatus(this.statusCode.toString());
132
+ this.writeHeaders(typeof chunk === 'string');
133
+ }
134
+ if(!Buffer.isBuffer(chunk) && !(chunk instanceof ArrayBuffer)) {
135
+ chunk = Buffer.from(chunk);
136
+ chunk = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
137
+ }
138
+ if(this.chunkedTransfer) {
139
+ // chunked transfer encoding
140
+ this._res.write(chunk);
141
+ callback();
142
+ } else {
143
+ // fixed size transfer encoding
144
+ const lastOffset = this._res.getWriteOffset();
145
+ const [ok, done] = this._res.tryEnd(chunk, this.totalSize);
146
+ if(done) {
147
+ this.destroy();
148
+ this.finished = true;
149
+ if(this.socketExists) this.socket.emit('close');
150
+ callback();
151
+ } else {
152
+ // still writing
153
+ if(!ok) {
154
+ // wait until uWS is ready to accept more data
155
+ this._res.onWritable((offset) => {
156
+ if(this.finished) {
157
+ return true;
158
+ }
159
+ const [ok, done] = this._res.tryEnd(chunk.slice(offset - lastOffset), this.totalSize);
160
+ if(done) {
161
+ this.destroy();
162
+ this.finished = true;
163
+ if(this.socketExists) this.socket.emit('close');
164
+ callback();
165
+ } else if(ok) {
166
+ callback();
167
+ }
168
+
169
+ return ok;
170
+ });
171
+ } else {
172
+ callback();
173
+ }
174
+ }
175
+ }
176
+ });
177
+ }
178
+ writeHead(statusCode, statusMessage, headers) {
179
+ this.statusCode = statusCode;
180
+ if(!headers) {
181
+ if(!statusMessage) return;
182
+ headers = statusMessage;
183
+ }
184
+ for(let header in headers) {
185
+ this.set(header, headers[header]);
186
+ }
187
+ }
188
+ writeHeaders(utf8) {
189
+ for(const header in this.headers) {
190
+ if(header === 'content-length') {
191
+ // if content-length is set, disable chunked transfer encoding, since size is known
192
+ this.chunkedTransfer = false;
193
+ this.totalSize = parseInt(this.headers[header]);
194
+ continue;
195
+ }
196
+ if(Array.isArray(this.headers[header])) {
197
+ for(let value of this.headers[header]) {
198
+ this._res.writeHeader(header, value);
199
+ }
200
+ } else {
201
+ this._res.writeHeader(header, this.headers[header]);
202
+ }
203
+ }
204
+ if(!this.headers['content-type']) {
205
+ this._res.writeHeader('content-type', 'text/html' + (utf8 ? `; charset=utf-8` : ''));
206
+ }
207
+ this.headersSent = true;
208
+ }
209
+ _implicitHeader() {
210
+ // compatibility function
211
+ // usually should send headers but this is useless for us
212
+ this.writeHead(this.statusCode);
213
+ }
214
+ status(code) {
215
+ this.statusCode = parseInt(code);
216
+ return this;
217
+ }
218
+ sendStatus(code) {
219
+ return this.status(code).send(statuses.message[+code] ?? code.toString());
220
+ }
221
+ end(data) {
222
+ if(this.finished) {
223
+ return;
224
+ }
225
+ this.writeHead(this.statusCode);
226
+ this._res.cork(() => {
227
+ if(!this.headersSent) {
228
+ const etagFn = this.app.get('etag fn');
229
+ if(etagFn && data && !this.headers['etag'] && !this.req.noEtag) {
230
+ this.headers['etag'] = etagFn(data);
231
+ }
232
+ const fresh = this.req.fresh;
233
+ this._res.writeStatus(fresh ? '304' : this.statusCode.toString());
234
+ this.writeHeaders(true);
235
+ if(fresh) {
236
+ this._res.end();
237
+ this.finished = true;
238
+ if(this.socketExists) this.socket.emit('close');
239
+ return;
240
+ }
241
+ }
242
+ const contentLength = this.headers['content-length'];
243
+ if(!data && contentLength) {
244
+ this._res.endWithoutBody(contentLength.toString());
245
+ } else {
246
+ if(data instanceof Buffer) {
247
+ data = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
248
+ }
249
+ if(this.req.method === 'HEAD') {
250
+ const length = Buffer.byteLength(data ?? '');
251
+ this._res.endWithoutBody(length.toString());
252
+ } else {
253
+ this._res.end(data);
254
+ }
255
+ }
256
+ this.finished = true;
257
+ if(this.socketExists) this.socket.emit('close');
258
+ });
259
+
260
+ this.emit('finish')
261
+ return this;
262
+ }
263
+
264
+ send(body) {
265
+ if(this.headersSent) {
266
+ throw new Error('Can\'t write body: Response was already sent');
267
+ }
268
+ const isBuffer = Buffer.isBuffer(body);
269
+ if(body === null || body === undefined) {
270
+ body = '';
271
+ } else if(typeof body === 'object' && !isBuffer) {
272
+ return this.json(body);
273
+ } else if(typeof body === 'number') {
274
+ if(arguments[1]) {
275
+ deprecated('res.send(status, body)', 'res.status(status).send(body)');
276
+ return this.status(body).send(arguments[1]);
277
+ } else {
278
+ deprecated('res.send(status)', 'res.sendStatus(status)');
279
+ return this.sendStatus(body);
280
+ }
281
+ } else if(!isBuffer) {
282
+ body = String(body);
283
+ }
284
+ if(typeof body === 'string') {
285
+ const contentType = this.headers['content-type'];
286
+ if(!contentType) {
287
+ this.headers['content-type'] = 'text/html; charset=utf-8';
288
+ } else if(!contentType.includes(';')) {
289
+ this.headers['content-type'] += '; charset=utf-8';
290
+ }
291
+ }
292
+ return this.end(body);
293
+ }
294
+
295
+ sendFile(path, options = new NullObject(), callback) {
296
+ if(typeof path !== 'string') {
297
+ throw new TypeError('path argument is required to res.sendFile');
298
+ }
299
+ if(typeof options === 'function') {
300
+ callback = options;
301
+ options = new NullObject();
302
+ }
303
+ if(!options) options = new NullObject();
304
+ let done = callback;
305
+ if(!done) done = this.req.next;
306
+ // default options
307
+ if(typeof options.maxAge === 'string') {
308
+ options.maxAge = ms(options.maxAge);
309
+ }
310
+ if(typeof options.maxAge === 'undefined') {
311
+ options.maxAge = 0;
312
+ }
313
+ if(typeof options.lastModified === 'undefined') {
314
+ options.lastModified = true;
315
+ }
316
+ if(typeof options.cacheControl === 'undefined') {
317
+ options.cacheControl = true;
318
+ }
319
+ if(typeof options.acceptRanges === 'undefined') {
320
+ options.acceptRanges = true;
321
+ }
322
+ if(typeof options.etag === 'undefined') {
323
+ options.etag = this.app.get('etag') !== false;
324
+ }
325
+ let etagFn = this.app.get('etag fn');
326
+ if(options.etag && !etagFn) {
327
+ etagFn = stat => {
328
+ return etag(stat, { weak: true });
329
+ }
330
+ }
331
+
332
+ // path checks
333
+ if(!options.root && !isAbsolute(path)) {
334
+ this.status(500);
335
+ return done(new Error('path must be absolute or specify root to res.sendFile'));
336
+ }
337
+ if(!options.skipEncodePath) {
338
+ path = encodeURI(path);
339
+ }
340
+ path = decode(path);
341
+ if(path === -1) {
342
+ this.status(400);
343
+ return done(new Error('Bad Request'));
344
+ }
345
+ if(~path.indexOf('\0')) {
346
+ this.status(400);
347
+ return done(new Error('Bad Request'));
348
+ }
349
+ if(UP_PATH_REGEXP.test(path)) {
350
+ this.status(403);
351
+ return done(new Error('Forbidden'));
352
+ }
353
+ const parts = Path.normalize(path).split(Path.sep);
354
+ const fullpath = options.root ? Path.resolve(Path.join(options.root, path)) : path;
355
+ if(options.root && !fullpath.startsWith(Path.resolve(options.root))) {
356
+ this.status(403);
357
+ return done(new Error('Forbidden'));
358
+ }
359
+
360
+ // dotfile checks
361
+ if(containsDotFile(parts)) {
362
+ switch(options.dotfiles) {
363
+ case 'allow':
364
+ break;
365
+ case 'deny':
366
+ this.status(403);
367
+ return done(new Error('Forbidden'));
368
+ case 'ignore_files':
369
+ const len = parts.length;
370
+ if(len > 1 && parts[len - 1].startsWith('.')) {
371
+ this.status(404);
372
+ return done(new Error('Not found'));
373
+ }
374
+ break;
375
+ case 'ignore':
376
+ default:
377
+ this.status(404);
378
+ return done(new Error('Not found'));
379
+ }
380
+ }
381
+
382
+ let stat = options._stat;
383
+ if(!stat) {
384
+ try {
385
+ stat = fs.statSync(fullpath);
386
+ } catch(err) {
387
+ return done(err);
388
+ }
389
+ if(stat.isDirectory()) {
390
+ this.status(404);
391
+ return done(new Error(`Not found`));
392
+ }
393
+ }
394
+
395
+ // headers
396
+ if(!this.headers['content-type']) {
397
+ const m = mime.lookup(fullpath);
398
+ if(m) this.type(m);
399
+ else this.type('application/octet-stream');
400
+ }
401
+ if(options.cacheControl) {
402
+ this.headers['cache-control'] = `public, max-age=${options.maxAge / 1000}` + (options.immutable ? ', immutable' : '');
403
+ }
404
+ if(options.lastModified) {
405
+ this.headers['last-modified'] = stat.mtime.toUTCString();
406
+ }
407
+ if(options.headers) {
408
+ for(const header in options.headers) {
409
+ this.set(header, options.headers[header]);
410
+ }
411
+ }
412
+ if(options.setHeaders) {
413
+ options.setHeaders(this, fullpath, stat);
414
+ }
415
+
416
+ // etag
417
+ if(options.etag && etagFn && !this.headers['etag']) {
418
+ this.headers['etag'] = etagFn(stat);
419
+ }
420
+ if(!options.etag) {
421
+ this.req.noEtag = true;
422
+ }
423
+
424
+ // conditional requests
425
+ if(isPreconditionFailure(this.req, this)) {
426
+ this.status(412);
427
+ return done(new Error('Precondition Failed'));
428
+ }
429
+
430
+ // range requests
431
+ let offset = 0, len = stat.size, ranged = false;
432
+ if(options.acceptRanges) {
433
+ this.headers['accept-ranges'] = 'bytes';
434
+ if(this.req.headers.range) {
435
+ let ranges = this.req.range(stat.size, {
436
+ combine: true
437
+ });
438
+
439
+ // if-range
440
+ if(!isRangeFresh(this.req, this)) {
441
+ ranges = -2;
442
+ }
443
+
444
+ if(ranges === -1) {
445
+ this.status(416);
446
+ this.headers['content-range'] = `bytes */${stat.size}`;
447
+ return done(new Error('Range Not Satisfiable'));
448
+ }
449
+ if(ranges !== -2 && ranges.length === 1) {
450
+ this.status(206);
451
+ const range = ranges[0];
452
+ this.headers['content-range'] = `bytes ${range.start}-${range.end}/${stat.size}`;
453
+ offset = range.start;
454
+ len = range.end - range.start + 1;
455
+ ranged = true;
456
+ }
457
+ }
458
+ }
459
+
460
+ // if-modified-since, if-none-match
461
+ if(this.req.fresh) {
462
+ return this.end();
463
+ }
464
+
465
+ if(this.req.method === 'HEAD') {
466
+ this.set('Content-Length', stat.size);
467
+ return this.end();
468
+ }
469
+
470
+ // serve smaller files using workers
471
+ if(this.app.workers.length && stat.size < 768 * 1024 && !ranged) {
472
+ this.app.readFileWithWorker(fullpath).then((data) => {
473
+ if(this._res.finished) {
474
+ return;
475
+ }
476
+ this.end(data);
477
+ if(callback) callback();
478
+ }).catch((err) => {
479
+ if(callback) callback(err);
480
+ });
481
+ } else {
482
+ // larger files or range requests are piped over response
483
+ let opts = {
484
+ highWaterMark: 256 * 1024
485
+ };
486
+ if(ranged) {
487
+ opts.start = offset;
488
+ opts.end = Math.max(offset, offset + len - 1);
489
+ }
490
+ const file = fs.createReadStream(fullpath, opts);
491
+ pipeStreamOverResponse(this, file, len, callback);
492
+ }
493
+ }
494
+ download(path, filename, options, callback) {
495
+ let done = callback;
496
+ let name = filename;
497
+ let opts = options || new NullObject();
498
+
499
+ // support function as second or third arg
500
+ if (typeof filename === 'function') {
501
+ done = filename;
502
+ name = null;
503
+ opts = {};
504
+ } else if (typeof options === 'function') {
505
+ done = options;
506
+ opts = {};
507
+ }
508
+
509
+ // support optional filename, where options may be in it's place
510
+ if (typeof filename === 'object' &&
511
+ (typeof options === 'function' || options === undefined)) {
512
+ name = null;
513
+ opts = filename;
514
+ }
515
+ if(!name) {
516
+ name = Path.basename(path);
517
+ }
518
+ if(!opts.root && !isAbsolute(path)) {
519
+ opts.root = process.cwd();
520
+ }
521
+
522
+ this.attachment(name);
523
+ this.sendFile(path, opts, done);
524
+ }
525
+ set(field, value) {
526
+ if(this.headersSent) {
527
+ throw new Error('Cannot set headers after they are sent to the client');
528
+ }
529
+ if(typeof field === 'object') {
530
+ for(const header in field) {
531
+ this.set(header, field[header]);
532
+ }
533
+ } else {
534
+ field = field.toLowerCase();
535
+ if(field === 'set-cookie' && Array.isArray(value)) {
536
+ value = value.join('; ');
537
+ } else if(field === 'content-type') {
538
+ if(!value.includes('charset=') && (value.startsWith('text/') || value === 'application/json' || value === 'application/javascript')) {
539
+ value += '; charset=utf-8';
540
+ }
541
+ }
542
+ this.headers[field] = String(value);
543
+ }
544
+ return this;
545
+ }
546
+ header(field, value) {
547
+ return this.set(field, value);
548
+ }
549
+ setHeader(field, value) {
550
+ return this.set(field, value);
551
+ }
552
+ get(field) {
553
+ return this.headers[field.toLowerCase()];
554
+ }
555
+ getHeader = this.get;
556
+ removeHeader(field) {
557
+ delete this.headers[field.toLowerCase()];
558
+ return this;
559
+ }
560
+ append(field, value) {
561
+ field = field.toLowerCase();
562
+ const old = this.headers[field];
563
+ if(old) {
564
+ const newVal = [];
565
+ if(Array.isArray(old)) {
566
+ newVal.push(...old);
567
+ } else if(old) {
568
+ newVal.push(old);
569
+ }
570
+ if(Array.isArray(value)) {
571
+ newVal.push(...value);
572
+ } else {
573
+ newVal.push(value);
574
+ }
575
+ this.headers[field] = newVal;
576
+ } else {
577
+ this.headers[field] = value;
578
+ }
579
+ return this;
580
+ }
581
+ render(view, options, callback) {
582
+ if(typeof options === 'function') {
583
+ callback = options;
584
+ options = {};
585
+ }
586
+ if(!options) {
587
+ options = {};
588
+ } else {
589
+ options = Object.assign({}, options);
590
+ }
591
+ options._locals = this.locals;
592
+ const done = callback || ((err, str) => {
593
+ if(err) return this.req.next(err);
594
+ this.send(str);
595
+ });
596
+
597
+ this.app.render(view, options, done);
598
+ }
599
+ cookie(name, value, options) {
600
+ if(!options) {
601
+ options = {};
602
+ }
603
+ let val = typeof value === 'object' ? "j:"+JSON.stringify(value) : String(value);
604
+ if(options.maxAge != null) {
605
+ const maxAge = options.maxAge - 0;
606
+ if(!isNaN(maxAge)) {
607
+ options.expires = new Date(Date.now() + maxAge);
608
+ options.maxAge = Math.floor(maxAge / 1000);
609
+ }
610
+ }
611
+ if(options.signed) {
612
+ val = 's:' + sign(val, this.req.secret);
613
+ }
614
+
615
+ if(options.path == null) {
616
+ options.path = '/';
617
+ }
618
+
619
+ this.append('Set-Cookie', cookie.serialize(name, val, options));
620
+ return this;
621
+ }
622
+ clearCookie(name, options) {
623
+ const opts = { path: '/', ...options, expires: new Date(1) };
624
+ delete opts.maxAge;
625
+ return this.cookie(name, '', opts);
626
+ }
627
+ attachment(filename) {
628
+ this.headers['Content-Disposition'] = `attachment; filename="${filename}"`;
629
+ this.type(filename.split('.').pop());
630
+ return this;
631
+ }
632
+ format(object) {
633
+ const keys = Object.keys(object).filter(v => v !== 'default');
634
+ const key = keys.length > 0 ? this.req.accepts(keys) : false;
635
+
636
+ this.vary('Accept');
637
+
638
+ if(key) {
639
+ this.set('Content-Type', normalizeType(key).value);
640
+ object[key](this.req, this, this.req.next);
641
+ } else if(object.default) {
642
+ object.default(this.req, this, this.req.next);
643
+ } else {
644
+ this.status(406).send(this.app._generateErrorPage('Not Acceptable'));
645
+ }
646
+
647
+ return this;
648
+ }
649
+ json(body) {
650
+ if(!this.headers['content-type']) {
651
+ this.headers['content-type'] = 'application/json; charset=utf-8';
652
+ }
653
+ const escape = this.app.get('json escape');
654
+ const replacer = this.app.get('json replacer');
655
+ const spaces = this.app.get('json spaces');
656
+ this.send(stringify(body, replacer, spaces, escape));
657
+ }
658
+ jsonp(object) {
659
+ let callback = this.req.query[this.app.get('jsonp callback name')];
660
+ let body = stringify(object, this.app.get('json replacer'), this.app.get('json spaces'), this.app.get('json escape'));
661
+
662
+ if(!this.headers['content-type']) {
663
+ this.headers['content-type'] = 'application/javascript; charset=utf-8';
664
+ this.headers['X-Content-Type-Options'] = 'nosniff';
665
+ }
666
+
667
+ if(Array.isArray(callback)) {
668
+ callback = callback[0];
669
+ }
670
+
671
+ if(typeof callback === 'string' && callback.length !== 0) {
672
+ callback = callback.replace(/[^\[\]\w$.]/g, '');
673
+
674
+ if(body === undefined) {
675
+ body = '';
676
+ } else if(typeof body === 'string') {
677
+ // replace chars not allowed in JavaScript that are in JSON
678
+ body = body
679
+ .replace(/\u2028/g, '\\u2028')
680
+ .replace(/\u2029/g, '\\u2029')
681
+ }
682
+ body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
683
+ }
684
+
685
+ return this.send(body);
686
+ }
687
+ links(links) {
688
+ this.headers['link'] = Object.entries(links).map(([rel, url]) => `<${url}>; rel="${rel}"`).join(', ');
689
+ return this;
690
+ }
691
+ location(path) {
692
+ if(path === 'back') {
693
+ path = this.req.get('Referrer');
694
+ if(!path) path = this.req.get('Referer');
695
+ if(!path) path = '/';
696
+ }
697
+ return this.headers['location'] = encodeUrl(path);
698
+ }
699
+ redirect(status, url) {
700
+ if(typeof status !== 'number' && !url) {
701
+ url = status;
702
+ status = 302;
703
+ }
704
+ this.location(url);
705
+ this.status(status);
706
+ this.headers['content-type'] = 'text/plain; charset=utf-8';
707
+ return this.send(`${statuses.message[status] ?? status}. Redirecting to ${url}`);
708
+ }
709
+
710
+ type(type) {
711
+ let ct = type.indexOf('/') === -1
712
+ ? (mime.contentType(type) || 'application/octet-stream')
713
+ : type;
714
+
715
+ return this.set('content-type', ct);
716
+ }
717
+ contentType = this.type;
718
+
719
+ vary(field) {
720
+ vary(this, field);
721
+ return this;
722
+ }
723
+
724
+ get connection() {
725
+ return this.socket;
726
+ }
727
+
728
+ get writableFinished() {
729
+ return this.finished;
730
+ }
731
+ }
732
+
733
+ function pipeStreamOverResponse(res, readStream, totalSize, callback) {
734
+ readStream.on('data', (chunk) => {
735
+ if(res.finished) {
736
+ return readStream.destroy();
737
+ }
738
+ res._res.cork(() => {
739
+ if(!res.headersSent) {
740
+ res.writeHead(res.statusCode);
741
+ res._res.writeStatus(res.statusCode.toString());
742
+ res.writeHeaders(true);
743
+ }
744
+ const ab = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
745
+
746
+ const lastOffset = res._res.getWriteOffset();
747
+ const [ok, done] = res._res.tryEnd(ab, totalSize);
748
+
749
+ if (done) {
750
+ readStream.destroy();
751
+ res.finished = true;
752
+ if(res.socketExists) res.socket.emit('close');
753
+ if(callback) callback();
754
+ } else if (!ok) {
755
+ readStream.pause();
756
+
757
+ res._res.ab = ab;
758
+ res._res.abOffset = lastOffset;
759
+
760
+ res._res.onWritable((offset) => {
761
+ if(res.finished) {
762
+ return true;
763
+ }
764
+ const [ok, done] = res._res.tryEnd(res._res.ab.slice(offset - res._res.abOffset), totalSize);
765
+ if (done) {
766
+ readStream.destroy();
767
+ res.finished = true;
768
+ if(res.socketExists) res.socket.emit('close');
769
+ if(callback) callback();
770
+ } else if (ok) {
771
+ readStream.resume();
772
+ }
773
+
774
+ return ok;
775
+ });
776
+ }
777
+ });
778
+ }).on('error', e => {
779
+ if(callback) callback(e);
780
+ if(!res.finished) {
781
+ res._res.close();
782
+ res.finished = true;
783
+ if(res.socketExists) res.socket.emit('error', e);
784
+ }
785
+ });
786
+ }