-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddlewares.js
More file actions
2999 lines (2983 loc) · 114 KB
/
middlewares.js
File metadata and controls
2999 lines (2983 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// node_modules/@sveltejs/adapter-node/files/shims.js
import { createRequire } from "module";
// node_modules/@sveltejs/kit/dist/install-fetch.js
import http from "http";
import https from "https";
import zlib from "zlib";
import Stream, { PassThrough, pipeline } from "stream";
import { types } from "util";
import { randomBytes } from "crypto";
import { format } from "url";
function dataUriToBuffer(uri) {
if (!/^data:/i.test(uri)) {
throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
}
uri = uri.replace(/\r?\n/g, "");
const firstComma = uri.indexOf(",");
if (firstComma === -1 || firstComma <= 4) {
throw new TypeError("malformed data: URI");
}
const meta = uri.substring(5, firstComma).split(";");
let charset = "";
let base64 = false;
const type = meta[0] || "text/plain";
let typeFull = type;
for (let i = 1; i < meta.length; i++) {
if (meta[i] === "base64") {
base64 = true;
} else {
typeFull += `;${meta[i]}`;
if (meta[i].indexOf("charset=") === 0) {
charset = meta[i].substring(8);
}
}
}
if (!meta[0] && !charset.length) {
typeFull += ";charset=US-ASCII";
charset = "US-ASCII";
}
const encoding = base64 ? "base64" : "ascii";
const data = unescape(uri.substring(firstComma + 1));
const buffer = Buffer.from(data, encoding);
buffer.type = type;
buffer.typeFull = typeFull;
buffer.charset = charset;
return buffer;
}
var src = dataUriToBuffer;
var dataUriToBuffer$1 = src;
var { Readable } = Stream;
var wm = new WeakMap();
async function* read(parts) {
for (const part of parts) {
if ("stream" in part) {
yield* part.stream();
} else {
yield part;
}
}
}
var Blob = class {
constructor(blobParts = [], options2 = {}) {
let size = 0;
const parts = blobParts.map((element) => {
let buffer;
if (element instanceof Buffer) {
buffer = element;
} else if (ArrayBuffer.isView(element)) {
buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
} else if (element instanceof ArrayBuffer) {
buffer = Buffer.from(element);
} else if (element instanceof Blob) {
buffer = element;
} else {
buffer = Buffer.from(typeof element === "string" ? element : String(element));
}
size += buffer.length || buffer.size || 0;
return buffer;
});
const type = options2.type === void 0 ? "" : String(options2.type).toLowerCase();
wm.set(this, {
type: /[^\u0020-\u007E]/.test(type) ? "" : type,
size,
parts
});
}
get size() {
return wm.get(this).size;
}
get type() {
return wm.get(this).type;
}
async text() {
return Buffer.from(await this.arrayBuffer()).toString();
}
async arrayBuffer() {
const data = new Uint8Array(this.size);
let offset = 0;
for await (const chunk of this.stream()) {
data.set(chunk, offset);
offset += chunk.length;
}
return data.buffer;
}
stream() {
return Readable.from(read(wm.get(this).parts));
}
slice(start = 0, end = this.size, type = "") {
const { size } = this;
let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size);
let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size);
const span = Math.max(relativeEnd - relativeStart, 0);
const parts = wm.get(this).parts.values();
const blobParts = [];
let added = 0;
for (const part of parts) {
const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size;
if (relativeStart && size2 <= relativeStart) {
relativeStart -= size2;
relativeEnd -= size2;
} else {
const chunk = part.slice(relativeStart, Math.min(size2, relativeEnd));
blobParts.push(chunk);
added += ArrayBuffer.isView(chunk) ? chunk.byteLength : chunk.size;
relativeStart = 0;
if (added >= span) {
break;
}
}
}
const blob = new Blob([], { type: String(type).toLowerCase() });
Object.assign(wm.get(blob), { size: span, parts: blobParts });
return blob;
}
get [Symbol.toStringTag]() {
return "Blob";
}
static [Symbol.hasInstance](object) {
return object && typeof object === "object" && typeof object.stream === "function" && object.stream.length === 0 && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[Symbol.toStringTag]);
}
};
Object.defineProperties(Blob.prototype, {
size: { enumerable: true },
type: { enumerable: true },
slice: { enumerable: true }
});
var fetchBlob = Blob;
var Blob$1 = fetchBlob;
var FetchBaseError = class extends Error {
constructor(message, type) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.type = type;
}
get name() {
return this.constructor.name;
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
};
var FetchError = class extends FetchBaseError {
constructor(message, type, systemError) {
super(message, type);
if (systemError) {
this.code = this.errno = systemError.code;
this.erroredSysCall = systemError.syscall;
}
}
};
var NAME = Symbol.toStringTag;
var isURLSearchParameters = (object) => {
return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
};
var isBlob = (object) => {
return typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
};
function isFormData(object) {
return typeof object === "object" && typeof object.append === "function" && typeof object.set === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.delete === "function" && typeof object.keys === "function" && typeof object.values === "function" && typeof object.entries === "function" && typeof object.constructor === "function" && object[NAME] === "FormData";
}
var isAbortSignal = (object) => {
return typeof object === "object" && object[NAME] === "AbortSignal";
};
var carriage = "\r\n";
var dashes = "-".repeat(2);
var carriageLength = Buffer.byteLength(carriage);
var getFooter = (boundary) => `${dashes}${boundary}${dashes}${carriage.repeat(2)}`;
function getHeader(boundary, name, field) {
let header = "";
header += `${dashes}${boundary}${carriage}`;
header += `Content-Disposition: form-data; name="${name}"`;
if (isBlob(field)) {
header += `; filename="${field.name}"${carriage}`;
header += `Content-Type: ${field.type || "application/octet-stream"}`;
}
return `${header}${carriage.repeat(2)}`;
}
var getBoundary = () => randomBytes(8).toString("hex");
async function* formDataIterator(form, boundary) {
for (const [name, value] of form) {
yield getHeader(boundary, name, value);
if (isBlob(value)) {
yield* value.stream();
} else {
yield value;
}
yield carriage;
}
yield getFooter(boundary);
}
function getFormDataLength(form, boundary) {
let length = 0;
for (const [name, value] of form) {
length += Buffer.byteLength(getHeader(boundary, name, value));
if (isBlob(value)) {
length += value.size;
} else {
length += Buffer.byteLength(String(value));
}
length += carriageLength;
}
length += Buffer.byteLength(getFooter(boundary));
return length;
}
var INTERNALS$2 = Symbol("Body internals");
var Body = class {
constructor(body, {
size = 0
} = {}) {
let boundary = null;
if (body === null) {
body = null;
} else if (isURLSearchParameters(body)) {
body = Buffer.from(body.toString());
} else if (isBlob(body))
;
else if (Buffer.isBuffer(body))
;
else if (types.isAnyArrayBuffer(body)) {
body = Buffer.from(body);
} else if (ArrayBuffer.isView(body)) {
body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
} else if (body instanceof Stream)
;
else if (isFormData(body)) {
boundary = `NodeFetchFormDataBoundary${getBoundary()}`;
body = Stream.Readable.from(formDataIterator(body, boundary));
} else {
body = Buffer.from(String(body));
}
this[INTERNALS$2] = {
body,
boundary,
disturbed: false,
error: null
};
this.size = size;
if (body instanceof Stream) {
body.on("error", (err) => {
const error2 = err instanceof FetchBaseError ? err : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${err.message}`, "system", err);
this[INTERNALS$2].error = error2;
});
}
}
get body() {
return this[INTERNALS$2].body;
}
get bodyUsed() {
return this[INTERNALS$2].disturbed;
}
async arrayBuffer() {
const { buffer, byteOffset, byteLength } = await consumeBody(this);
return buffer.slice(byteOffset, byteOffset + byteLength);
}
async blob() {
const ct = this.headers && this.headers.get("content-type") || this[INTERNALS$2].body && this[INTERNALS$2].body.type || "";
const buf = await this.buffer();
return new Blob$1([buf], {
type: ct
});
}
async json() {
const buffer = await consumeBody(this);
return JSON.parse(buffer.toString());
}
async text() {
const buffer = await consumeBody(this);
return buffer.toString();
}
buffer() {
return consumeBody(this);
}
};
Object.defineProperties(Body.prototype, {
body: { enumerable: true },
bodyUsed: { enumerable: true },
arrayBuffer: { enumerable: true },
blob: { enumerable: true },
json: { enumerable: true },
text: { enumerable: true }
});
async function consumeBody(data) {
if (data[INTERNALS$2].disturbed) {
throw new TypeError(`body used already for: ${data.url}`);
}
data[INTERNALS$2].disturbed = true;
if (data[INTERNALS$2].error) {
throw data[INTERNALS$2].error;
}
let { body } = data;
if (body === null) {
return Buffer.alloc(0);
}
if (isBlob(body)) {
body = body.stream();
}
if (Buffer.isBuffer(body)) {
return body;
}
if (!(body instanceof Stream)) {
return Buffer.alloc(0);
}
const accum = [];
let accumBytes = 0;
try {
for await (const chunk of body) {
if (data.size > 0 && accumBytes + chunk.length > data.size) {
const err = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
body.destroy(err);
throw err;
}
accumBytes += chunk.length;
accum.push(chunk);
}
} catch (error2) {
if (error2 instanceof FetchBaseError) {
throw error2;
} else {
throw new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2);
}
}
if (body.readableEnded === true || body._readableState.ended === true) {
try {
if (accum.every((c) => typeof c === "string")) {
return Buffer.from(accum.join(""));
}
return Buffer.concat(accum, accumBytes);
} catch (error2) {
throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2);
}
} else {
throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
}
}
var clone = (instance, highWaterMark) => {
let p1;
let p2;
let { body } = instance;
if (instance.bodyUsed) {
throw new Error("cannot clone body after it is used");
}
if (body instanceof Stream && typeof body.getBoundary !== "function") {
p1 = new PassThrough({ highWaterMark });
p2 = new PassThrough({ highWaterMark });
body.pipe(p1);
body.pipe(p2);
instance[INTERNALS$2].body = p1;
body = p2;
}
return body;
};
var extractContentType = (body, request) => {
if (body === null) {
return null;
}
if (typeof body === "string") {
return "text/plain;charset=UTF-8";
}
if (isURLSearchParameters(body)) {
return "application/x-www-form-urlencoded;charset=UTF-8";
}
if (isBlob(body)) {
return body.type || null;
}
if (Buffer.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
return null;
}
if (body && typeof body.getBoundary === "function") {
return `multipart/form-data;boundary=${body.getBoundary()}`;
}
if (isFormData(body)) {
return `multipart/form-data; boundary=${request[INTERNALS$2].boundary}`;
}
if (body instanceof Stream) {
return null;
}
return "text/plain;charset=UTF-8";
};
var getTotalBytes = (request) => {
const { body } = request;
if (body === null) {
return 0;
}
if (isBlob(body)) {
return body.size;
}
if (Buffer.isBuffer(body)) {
return body.length;
}
if (body && typeof body.getLengthSync === "function") {
return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
}
if (isFormData(body)) {
return getFormDataLength(request[INTERNALS$2].boundary);
}
return null;
};
var writeToStream = (dest, { body }) => {
if (body === null) {
dest.end();
} else if (isBlob(body)) {
body.stream().pipe(dest);
} else if (Buffer.isBuffer(body)) {
dest.write(body);
dest.end();
} else {
body.pipe(dest);
}
};
var validateHeaderName = typeof http.validateHeaderName === "function" ? http.validateHeaderName : (name) => {
if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
const err = new TypeError(`Header name must be a valid HTTP token [${name}]`);
Object.defineProperty(err, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
throw err;
}
};
var validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name, value) => {
if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
const err = new TypeError(`Invalid character in header content ["${name}"]`);
Object.defineProperty(err, "code", { value: "ERR_INVALID_CHAR" });
throw err;
}
};
var Headers = class extends URLSearchParams {
constructor(init2) {
let result = [];
if (init2 instanceof Headers) {
const raw = init2.raw();
for (const [name, values] of Object.entries(raw)) {
result.push(...values.map((value) => [name, value]));
}
} else if (init2 == null)
;
else if (typeof init2 === "object" && !types.isBoxedPrimitive(init2)) {
const method = init2[Symbol.iterator];
if (method == null) {
result.push(...Object.entries(init2));
} else {
if (typeof method !== "function") {
throw new TypeError("Header pairs must be iterable");
}
result = [...init2].map((pair) => {
if (typeof pair !== "object" || types.isBoxedPrimitive(pair)) {
throw new TypeError("Each header pair must be an iterable object");
}
return [...pair];
}).map((pair) => {
if (pair.length !== 2) {
throw new TypeError("Each header pair must be a name/value tuple");
}
return [...pair];
});
}
} else {
throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
}
result = result.length > 0 ? result.map(([name, value]) => {
validateHeaderName(name);
validateHeaderValue(name, String(value));
return [String(name).toLowerCase(), String(value)];
}) : void 0;
super(result);
return new Proxy(this, {
get(target, p, receiver) {
switch (p) {
case "append":
case "set":
return (name, value) => {
validateHeaderName(name);
validateHeaderValue(name, String(value));
return URLSearchParams.prototype[p].call(receiver, String(name).toLowerCase(), String(value));
};
case "delete":
case "has":
case "getAll":
return (name) => {
validateHeaderName(name);
return URLSearchParams.prototype[p].call(receiver, String(name).toLowerCase());
};
case "keys":
return () => {
target.sort();
return new Set(URLSearchParams.prototype.keys.call(target)).keys();
};
default:
return Reflect.get(target, p, receiver);
}
}
});
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
toString() {
return Object.prototype.toString.call(this);
}
get(name) {
const values = this.getAll(name);
if (values.length === 0) {
return null;
}
let value = values.join(", ");
if (/^content-encoding$/i.test(name)) {
value = value.toLowerCase();
}
return value;
}
forEach(callback) {
for (const name of this.keys()) {
callback(this.get(name), name);
}
}
*values() {
for (const name of this.keys()) {
yield this.get(name);
}
}
*entries() {
for (const name of this.keys()) {
yield [name, this.get(name)];
}
}
[Symbol.iterator]() {
return this.entries();
}
raw() {
return [...this.keys()].reduce((result, key) => {
result[key] = this.getAll(key);
return result;
}, {});
}
[Symbol.for("nodejs.util.inspect.custom")]() {
return [...this.keys()].reduce((result, key) => {
const values = this.getAll(key);
if (key === "host") {
result[key] = values[0];
} else {
result[key] = values.length > 1 ? values : values[0];
}
return result;
}, {});
}
};
Object.defineProperties(Headers.prototype, ["get", "entries", "forEach", "values"].reduce((result, property) => {
result[property] = { enumerable: true };
return result;
}, {}));
function fromRawHeaders(headers = []) {
return new Headers(headers.reduce((result, value, index2, array) => {
if (index2 % 2 === 0) {
result.push(array.slice(index2, index2 + 2));
}
return result;
}, []).filter(([name, value]) => {
try {
validateHeaderName(name);
validateHeaderValue(name, String(value));
return true;
} catch {
return false;
}
}));
}
var redirectStatus = new Set([301, 302, 303, 307, 308]);
var isRedirect = (code) => {
return redirectStatus.has(code);
};
var INTERNALS$1 = Symbol("Response internals");
var Response = class extends Body {
constructor(body = null, options2 = {}) {
super(body, options2);
const status = options2.status || 200;
const headers = new Headers(options2.headers);
if (body !== null && !headers.has("Content-Type")) {
const contentType = extractContentType(body);
if (contentType) {
headers.append("Content-Type", contentType);
}
}
this[INTERNALS$1] = {
url: options2.url,
status,
statusText: options2.statusText || "",
headers,
counter: options2.counter,
highWaterMark: options2.highWaterMark
};
}
get url() {
return this[INTERNALS$1].url || "";
}
get status() {
return this[INTERNALS$1].status;
}
get ok() {
return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
}
get redirected() {
return this[INTERNALS$1].counter > 0;
}
get statusText() {
return this[INTERNALS$1].statusText;
}
get headers() {
return this[INTERNALS$1].headers;
}
get highWaterMark() {
return this[INTERNALS$1].highWaterMark;
}
clone() {
return new Response(clone(this, this.highWaterMark), {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected,
size: this.size
});
}
static redirect(url, status = 302) {
if (!isRedirect(status)) {
throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
}
return new Response(null, {
headers: {
location: new URL(url).toString()
},
status
});
}
get [Symbol.toStringTag]() {
return "Response";
}
};
Object.defineProperties(Response.prototype, {
url: { enumerable: true },
status: { enumerable: true },
ok: { enumerable: true },
redirected: { enumerable: true },
statusText: { enumerable: true },
headers: { enumerable: true },
clone: { enumerable: true }
});
var getSearch = (parsedURL) => {
if (parsedURL.search) {
return parsedURL.search;
}
const lastOffset = parsedURL.href.length - 1;
const hash2 = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
return parsedURL.href[lastOffset - hash2.length] === "?" ? "?" : "";
};
var INTERNALS = Symbol("Request internals");
var isRequest = (object) => {
return typeof object === "object" && typeof object[INTERNALS] === "object";
};
var Request = class extends Body {
constructor(input, init2 = {}) {
let parsedURL;
if (isRequest(input)) {
parsedURL = new URL(input.url);
} else {
parsedURL = new URL(input);
input = {};
}
let method = init2.method || input.method || "GET";
method = method.toUpperCase();
if ((init2.body != null || isRequest(input)) && input.body !== null && (method === "GET" || method === "HEAD")) {
throw new TypeError("Request with GET/HEAD method cannot have body");
}
const inputBody = init2.body ? init2.body : isRequest(input) && input.body !== null ? clone(input) : null;
super(inputBody, {
size: init2.size || input.size || 0
});
const headers = new Headers(init2.headers || input.headers || {});
if (inputBody !== null && !headers.has("Content-Type")) {
const contentType = extractContentType(inputBody, this);
if (contentType) {
headers.append("Content-Type", contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ("signal" in init2) {
signal = init2.signal;
}
if (signal !== null && !isAbortSignal(signal)) {
throw new TypeError("Expected signal to be an instanceof AbortSignal");
}
this[INTERNALS] = {
method,
redirect: init2.redirect || input.redirect || "follow",
headers,
parsedURL,
signal
};
this.follow = init2.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init2.follow;
this.compress = init2.compress === void 0 ? input.compress === void 0 ? true : input.compress : init2.compress;
this.counter = init2.counter || input.counter || 0;
this.agent = init2.agent || input.agent;
this.highWaterMark = init2.highWaterMark || input.highWaterMark || 16384;
this.insecureHTTPParser = init2.insecureHTTPParser || input.insecureHTTPParser || false;
}
get method() {
return this[INTERNALS].method;
}
get url() {
return format(this[INTERNALS].parsedURL);
}
get headers() {
return this[INTERNALS].headers;
}
get redirect() {
return this[INTERNALS].redirect;
}
get signal() {
return this[INTERNALS].signal;
}
clone() {
return new Request(this);
}
get [Symbol.toStringTag]() {
return "Request";
}
};
Object.defineProperties(Request.prototype, {
method: { enumerable: true },
url: { enumerable: true },
headers: { enumerable: true },
redirect: { enumerable: true },
clone: { enumerable: true },
signal: { enumerable: true }
});
var getNodeRequestOptions = (request) => {
const { parsedURL } = request[INTERNALS];
const headers = new Headers(request[INTERNALS].headers);
if (!headers.has("Accept")) {
headers.set("Accept", "*/*");
}
let contentLengthValue = null;
if (request.body === null && /^(post|put)$/i.test(request.method)) {
contentLengthValue = "0";
}
if (request.body !== null) {
const totalBytes = getTotalBytes(request);
if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
contentLengthValue = String(totalBytes);
}
}
if (contentLengthValue) {
headers.set("Content-Length", contentLengthValue);
}
if (!headers.has("User-Agent")) {
headers.set("User-Agent", "node-fetch");
}
if (request.compress && !headers.has("Accept-Encoding")) {
headers.set("Accept-Encoding", "gzip,deflate,br");
}
let { agent } = request;
if (typeof agent === "function") {
agent = agent(parsedURL);
}
if (!headers.has("Connection") && !agent) {
headers.set("Connection", "close");
}
const search = getSearch(parsedURL);
const requestOptions = {
path: parsedURL.pathname + search,
pathname: parsedURL.pathname,
hostname: parsedURL.hostname,
protocol: parsedURL.protocol,
port: parsedURL.port,
hash: parsedURL.hash,
search: parsedURL.search,
query: parsedURL.query,
href: parsedURL.href,
method: request.method,
headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
insecureHTTPParser: request.insecureHTTPParser,
agent
};
return requestOptions;
};
var AbortError = class extends FetchBaseError {
constructor(message, type = "aborted") {
super(message, type);
}
};
var supportedSchemas = new Set(["data:", "http:", "https:"]);
async function fetch(url, options_) {
return new Promise((resolve3, reject) => {
const request = new Request(url, options_);
const options2 = getNodeRequestOptions(request);
if (!supportedSchemas.has(options2.protocol)) {
throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${options2.protocol.replace(/:$/, "")}" is not supported.`);
}
if (options2.protocol === "data:") {
const data = dataUriToBuffer$1(request.url);
const response2 = new Response(data, { headers: { "Content-Type": data.typeFull } });
resolve3(response2);
return;
}
const send2 = (options2.protocol === "https:" ? https : http).request;
const { signal } = request;
let response = null;
const abort = () => {
const error2 = new AbortError("The operation was aborted.");
reject(error2);
if (request.body && request.body instanceof Stream.Readable) {
request.body.destroy(error2);
}
if (!response || !response.body) {
return;
}
response.body.emit("error", error2);
};
if (signal && signal.aborted) {
abort();
return;
}
const abortAndFinalize = () => {
abort();
finalize();
};
const request_ = send2(options2);
if (signal) {
signal.addEventListener("abort", abortAndFinalize);
}
const finalize = () => {
request_.abort();
if (signal) {
signal.removeEventListener("abort", abortAndFinalize);
}
};
request_.on("error", (err) => {
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, "system", err));
finalize();
});
request_.on("response", (response_) => {
request_.setTimeout(0);
const headers = fromRawHeaders(response_.rawHeaders);
if (isRedirect(response_.statusCode)) {
const location = headers.get("Location");
const locationURL = location === null ? null : new URL(location, request.url);
switch (request.redirect) {
case "error":
reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect"));
finalize();
return;
case "manual":
if (locationURL !== null) {
try {
headers.set("Location", locationURL);
} catch (error2) {
reject(error2);
}
}
break;
case "follow": {
if (locationURL === null) {
break;
}
if (request.counter >= request.follow) {
reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect"));
finalize();
return;
}
const requestOptions = {
headers: new Headers(request.headers),
follow: request.follow,
counter: request.counter + 1,
agent: request.agent,
compress: request.compress,
method: request.method,
body: request.body,
signal: request.signal,
size: request.size
};
if (response_.statusCode !== 303 && request.body && options_.body instanceof Stream.Readable) {
reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
finalize();
return;
}
if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request.method === "POST") {
requestOptions.method = "GET";
requestOptions.body = void 0;
requestOptions.headers.delete("content-length");
}
resolve3(fetch(new Request(locationURL, requestOptions)));
finalize();
return;
}
}
}
response_.once("end", () => {
if (signal) {
signal.removeEventListener("abort", abortAndFinalize);
}
});
let body = pipeline(response_, new PassThrough(), (error2) => {
reject(error2);
});
if (process.version < "v12.10") {
response_.on("aborted", abortAndFinalize);
}
const responseOptions = {
url: request.url,
status: response_.statusCode,
statusText: response_.statusMessage,
headers,
size: request.size,
counter: request.counter,
highWaterMark: request.highWaterMark
};
const codings = headers.get("Content-Encoding");
if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
response = new Response(body, responseOptions);
resolve3(response);
return;
}
const zlibOptions = {
flush: zlib.Z_SYNC_FLUSH,
finishFlush: zlib.Z_SYNC_FLUSH
};
if (codings === "gzip" || codings === "x-gzip") {
body = pipeline(body, zlib.createGunzip(zlibOptions), (error2) => {
reject(error2);
});
response = new Response(body, responseOptions);
resolve3(response);
return;
}
if (codings === "deflate" || codings === "x-deflate") {
const raw = pipeline(response_, new PassThrough(), (error2) => {
reject(error2);
});
raw.once("data", (chunk) => {
if ((chunk[0] & 15) === 8) {
body = pipeline(body, zlib.createInflate(), (error2) => {
reject(error2);
});
} else {
body = pipeline(body, zlib.createInflateRaw(), (error2) => {
reject(error2);
});
}
response = new Response(body, responseOptions);
resolve3(response);
});
return;
}
if (codings === "br") {
body = pipeline(body, zlib.createBrotliDecompress(), (error2) => {
reject(error2);
});
response = new Response(body, responseOptions);
resolve3(response);
return;
}
response = new Response(body, responseOptions);
resolve3(response);