ultimate-express 1.3.14 → 1.3.15

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