-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbody.ts
241 lines (215 loc) · 6.55 KB
/
body.ts
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
import {
binaryArrayToBytes,
isArrayBufferView,
readFullStream
} from "./util.ts";
import { ReadableStream } from "https://denopkg.com/keroxp/deno-streams@v0.1.1/readable_stream.ts";
import { MultipartWriter } from "https://denopkg.com/keroxp/deno-multipart/multipart.ts";
import { defer } from "https://denopkg.com/keroxp/deno-streams@v0.1.1/defer.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export type BodyInit =
| Blob
| domTypes.BufferSource
| FormData
| URLSearchParams
| ReadableStream<Uint8Array>
| string;
export interface BodyMixin {
readonly body: ReadableStream | null;
readonly bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<domTypes.Blob>;
formData(): Promise<FormData>;
json(): Promise<any>;
text(): Promise<string>;
}
export class Body implements BodyMixin {
private _bodyInit: BodyInit;
public get bodyInit(): BodyInit {
return this._bodyInit;
}
private _headers: Headers;
public get headers(): Headers {
return this._headers;
}
constructor(
public readonly stream: ReadableStream<Uint8Array>,
public readonly contentType: string
) {}
get body(): ReadableStream {
return this.stream;
}
get bodyUsed(): boolean {
return this.body !== null && this.body.disturbed;
}
get bodyLocked(): boolean {
return this.body !== null && this.body.locked;
}
private async readFullBody(): Promise<Uint8Array> {
if (this.bodyUsed || this.bodyLocked) {
throw new TypeError("body is locked or disturbed");
}
const stream = this.body || new ReadableStream<Uint8Array>({});
return readFullStream(stream);
}
private bodyArrayBuffer: ArrayBuffer;
async arrayBuffer(): Promise<ArrayBuffer> {
if (this.bodyArrayBuffer) return this.bodyArrayBuffer;
const bytes = await this.readFullBody();
return (this.bodyArrayBuffer = bytes.buffer as ArrayBuffer);
}
private bodyBlob: Blob;
async blob(): Promise<domTypes.Blob> {
if (this.bodyBlob) return this.bodyBlob;
return (this.bodyBlob = new Blob([await this.arrayBuffer()], {
type: this.contentType
}));
}
private bodyFormData: FormData;
async formData(): Promise<domTypes.FormData> {
if (this.bodyFormData) return this.bodyFormData;
if (!this.contentType) throw new RangeError("body is not form data");
if (this.contentType.match(/^application\/x-www-form-urlencoded/)) {
// form
const text = await this.text();
const form = new FormData();
text
.trim()
.split("&")
.map(kv => kv.split("="))
.map(kv => form.set(kv[0], kv[1]));
return (this.bodyFormData = form);
} else if (this.contentType.match(/^multipart\/form-data/)) {
throw new Error("multipart formdata is not implemented");
}
throw new Error("body is not formData");
}
private bodyString: string;
async json(): Promise<any> {
return JSON.parse(await this.text());
}
async text(): Promise<string> {
if (this.bodyString) return this.bodyString;
return (this.bodyString = decoder.decode(await this.arrayBuffer()));
}
}
export function extractBody(
body: BodyInit
): {
stream: ReadableStream<Uint8Array>;
contentType: string;
size: number | null;
} {
let contentType = null;
let size = null;
let stream: ReadableStream<Uint8Array> = null;
if (body instanceof ReadableStream) {
if (body.locked) {
throw new Error(`body stream is locked`);
} else if (body.disturbed) {
throw new Error(`body stream is disturbed`);
}
stream = body;
} else if (typeof body === "string") {
contentType = "text/plain;charset=UTF-8";
const bytes = encoder.encode(body);
stream = new ReadableStream<Uint8Array>({
start: controller => {
controller.enqueue(bytes);
controller.close();
}
});
size = bytes.byteLength;
} else if (body instanceof ArrayBuffer) {
const view = new Uint8Array(body);
stream = new ReadableStream<Uint8Array>({
start: controller => {
controller.enqueue(view);
controller.close();
}
});
size = view.byteLength;
} else if (body instanceof Blob) {
if (body.type && body.type !== "") {
contentType = body.type;
}
stream = new ReadableStream({
start: async controller => {
return readBlob(body)
.then(controller.enqueue)
.then(controller.close)
.catch(controller.error);
}
});
size = body.size;
} else if (body instanceof FormData) {
const startDefer = defer<void>();
stream = new ReadableStream({
start: async _ => startDefer
});
const controller = stream.readableStreamController;
const writer = {
write: async p => {
controller.enqueue(p);
return p.byteLength;
}
};
const multipart = new MultipartWriter(writer);
(async function a() {
for (const [key, val] of body.entries()) {
if (typeof val === "string") {
await multipart.writeField(key, val);
} else if (val) {
const fw = multipart.createFormFile(key, val.name);
await readBlob(val).then(fw.write);
}
}
await multipart.close();
await multipart.flush();
})()
.then(startDefer.resolve)
.catch(startDefer.reject);
contentType = multipart.formDataContentType();
} else if (body instanceof URLSearchParams) {
let kv = [];
for (const [key, val] of body.entries()) {
kv.push(`${key}=${val}`);
}
const bytes = encoder.encode(kv.join("&"));
stream = new ReadableStream<Uint8Array>({
start: controller => {
controller.enqueue(bytes);
controller.close();
}
});
contentType = "application/x-www-form-urlencoded";
size = bytes.byteLength;
} else if (isArrayBufferView(body)) {
const bytes = binaryArrayToBytes(body);
stream = new ReadableStream<Uint8Array>({
start: controller => {
controller.enqueue(bytes);
controller.close();
}
});
size = bytes.byteLength;
} else {
throw new Error("invalid input: " + body);
}
return { stream, contentType, size };
}
async function readBlob(blob: domTypes.Blob): Promise<Uint8Array> {
const fileReader = null; //new FileReader();
await new Promise(resolve => {
fileReader.addEventListener("loadend", resolve);
fileReader.readAsArrayBuffer(blob);
});
const { result } = fileReader;
if (typeof result === "string") {
return new TextEncoder().encode(result);
} else if (result instanceof ArrayBuffer) {
return new Uint8Array(result);
}
return null;
}