ultimate-express 1.2.13 → 1.2.14

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