(href, info = {})
| 129 | } |
| 130 | |
| 131 | function fetch(href, info = {}) { |
| 132 | return new Promise((resolveResponse, rejectResponse) => { |
| 133 | let url = new URL(href); |
| 134 | if ((url.protocol != "http:") && (url.protocol != "https:")) |
| 135 | rejectResponse(new URIError("only http or https")); |
| 136 | const promiseBody = new Promise((resolveBody /*, rejectBody */) => { |
| 137 | let method = info.method; |
| 138 | let headers = info.headers; |
| 139 | let body = info.body; |
| 140 | let length = 0; |
| 141 | if ((method == "POST") || (method == "PUT")) { |
| 142 | body = info.body; |
| 143 | if (body == undefined) |
| 144 | rejectResponse(new URIError(method + " no body")); |
| 145 | else if (!(body instanceof ArrayBuffer)) { |
| 146 | body = body.toString(); |
| 147 | body = ArrayBuffer.fromString(body); |
| 148 | } |
| 149 | if (!headers) |
| 150 | headers = new Headers(); |
| 151 | else { |
| 152 | if (!(headers instanceof Headers)) { |
| 153 | const h = new Headers(); |
| 154 | for (const name in headers) |
| 155 | h.set(name.toLowerCase(), headers[name]); |
| 156 | headers = h; |
| 157 | } |
| 158 | } |
| 159 | length = headers.get("content-length"); |
| 160 | if (length == undefined) { |
| 161 | length = body.byteLength; |
| 162 | const transferEncoding = headers.get("transfer-encoding"); |
| 163 | if (transferEncoding?.toLowerCase() != "chunked") |
| 164 | headers.set("content-length", length); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | let redirected = false; |
| 169 | let offset = 0; |
| 170 | let buffer = null; |
| 171 | const options = { |
| 172 | method, |
| 173 | headers, |
| 174 | onHeaders(status, headers, statusText) { |
| 175 | if ((301 === status) || (308 === status) || (302 === status) || (303 === status) || (307 === status)) { |
| 176 | url = new URL(headers.get("location")); |
| 177 | redirected = this.redirected = true; |
| 178 | offset = 0; |
| 179 | return; |
| 180 | } |
| 181 | resolveResponse(new Response(url, status, headers, promiseBody, redirected, statusText)); |
| 182 | }, |
| 183 | onWritable(count) { |
| 184 | if (body) { |
| 185 | let remain = length - offset; |
| 186 | if (remain > 0) { |
| 187 | if (count > remain) |
| 188 | count = remain; |
no test coverage detected