UNPKG

24.1 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var globals = require('../../utilities/globals');
6var tslib = require('tslib');
7var utilities = require('../../utilities');
8var utils = require('../utils');
9var errors = require('../../errors');
10var core = require('../core');
11
12function asyncIterator(source) {
13 var _a;
14 var iterator = source[Symbol.asyncIterator]();
15 return _a = {
16 next: function () {
17 return iterator.next();
18 }
19 },
20 _a[Symbol.asyncIterator] = function () {
21 return this;
22 },
23 _a;
24}
25
26function nodeStreamIterator(stream) {
27 var cleanup = null;
28 var error = null;
29 var done = false;
30 var data = [];
31 var waiting = [];
32 function onData(chunk) {
33 if (error)
34 return;
35 if (waiting.length) {
36 var shiftedArr = waiting.shift();
37 if (Array.isArray(shiftedArr) && shiftedArr[0]) {
38 return shiftedArr[0]({ value: chunk, done: false });
39 }
40 }
41 data.push(chunk);
42 }
43 function onError(err) {
44 error = err;
45 var all = waiting.slice();
46 all.forEach(function (pair) {
47 pair[1](err);
48 });
49 !cleanup || cleanup();
50 }
51 function onEnd() {
52 done = true;
53 var all = waiting.slice();
54 all.forEach(function (pair) {
55 pair[0]({ value: undefined, done: true });
56 });
57 !cleanup || cleanup();
58 }
59 cleanup = function () {
60 cleanup = null;
61 stream.removeListener("data", onData);
62 stream.removeListener("error", onError);
63 stream.removeListener("end", onEnd);
64 stream.removeListener("finish", onEnd);
65 stream.removeListener("close", onEnd);
66 };
67 stream.on("data", onData);
68 stream.on("error", onError);
69 stream.on("end", onEnd);
70 stream.on("finish", onEnd);
71 stream.on("close", onEnd);
72 function getNext() {
73 return new Promise(function (resolve, reject) {
74 if (error)
75 return reject(error);
76 if (data.length)
77 return resolve({ value: data.shift(), done: false });
78 if (done)
79 return resolve({ value: undefined, done: true });
80 waiting.push([resolve, reject]);
81 });
82 }
83 var iterator = {
84 next: function () {
85 return getNext();
86 },
87 };
88 if (utilities.canUseAsyncIteratorSymbol) {
89 iterator[Symbol.asyncIterator] = function () {
90 return this;
91 };
92 }
93 return iterator;
94}
95
96function promiseIterator(promise) {
97 var resolved = false;
98 var iterator = {
99 next: function () {
100 if (resolved)
101 return Promise.resolve({
102 value: undefined,
103 done: true,
104 });
105 resolved = true;
106 return new Promise(function (resolve, reject) {
107 promise
108 .then(function (value) {
109 resolve({ value: value, done: false });
110 })
111 .catch(reject);
112 });
113 },
114 };
115 if (utilities.canUseAsyncIteratorSymbol) {
116 iterator[Symbol.asyncIterator] = function () {
117 return this;
118 };
119 }
120 return iterator;
121}
122
123function readerIterator(reader) {
124 var iterator = {
125 next: function () {
126 return reader.read();
127 },
128 };
129 if (utilities.canUseAsyncIteratorSymbol) {
130 iterator[Symbol.asyncIterator] = function () {
131 return this;
132 };
133 }
134 return iterator;
135}
136
137function isNodeResponse(value) {
138 return !!value.body;
139}
140function isReadableStream(value) {
141 return !!value.getReader;
142}
143function isAsyncIterableIterator(value) {
144 return !!(utilities.canUseAsyncIteratorSymbol &&
145 value[Symbol.asyncIterator]);
146}
147function isStreamableBlob(value) {
148 return !!value.stream;
149}
150function isBlob(value) {
151 return !!value.arrayBuffer;
152}
153function isNodeReadableStream(value) {
154 return !!value.pipe;
155}
156function responseIterator(response) {
157 var body = response;
158 if (isNodeResponse(response))
159 body = response.body;
160 if (isAsyncIterableIterator(body))
161 return asyncIterator(body);
162 if (isReadableStream(body))
163 return readerIterator(body.getReader());
164 if (isStreamableBlob(body)) {
165 return readerIterator(body.stream().getReader());
166 }
167 if (isBlob(body))
168 return promiseIterator(body.arrayBuffer());
169 if (isNodeReadableStream(body))
170 return nodeStreamIterator(body);
171 throw new Error("Unknown body type for responseIterator. Please pass a streamable response.");
172}
173
174function isNonNullObject(obj) {
175 return obj !== null && typeof obj === "object";
176}
177
178function isApolloPayloadResult(value) {
179 return isNonNullObject(value) && "payload" in value;
180}
181
182var hasOwnProperty = Object.prototype.hasOwnProperty;
183function readMultipartBody(response, nextValue) {
184 return tslib.__awaiter(this, void 0, void 0, function () {
185 var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _a, value, done, chunk, searchFrom, bi, message, i, headers, contentType_1, body, result, next;
186 var _b, _c;
187 var _d;
188 return tslib.__generator(this, function (_e) {
189 switch (_e.label) {
190 case 0:
191 if (TextDecoder === undefined) {
192 throw new Error("TextDecoder must be defined in the environment: please import a polyfill.");
193 }
194 decoder = new TextDecoder("utf-8");
195 contentType = (_d = response.headers) === null || _d === void 0 ? void 0 : _d.get("content-type");
196 delimiter = "boundary=";
197 boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter)) ?
198 contentType === null || contentType === void 0 ? void 0 : contentType.substring((contentType === null || contentType === void 0 ? void 0 : contentType.indexOf(delimiter)) + delimiter.length).replace(/['"]/g, "").replace(/\;(.*)/gm, "").trim()
199 : "-";
200 boundary = "\r\n--".concat(boundaryVal);
201 buffer = "";
202 iterator = responseIterator(response);
203 running = true;
204 _e.label = 1;
205 case 1:
206 if (!running) return [3 , 3];
207 return [4 , iterator.next()];
208 case 2:
209 _a = _e.sent(), value = _a.value, done = _a.done;
210 chunk = typeof value === "string" ? value : decoder.decode(value);
211 searchFrom = buffer.length - boundary.length + 1;
212 running = !done;
213 buffer += chunk;
214 bi = buffer.indexOf(boundary, searchFrom);
215 while (bi > -1) {
216 message = void 0;
217 _b = [
218 buffer.slice(0, bi),
219 buffer.slice(bi + boundary.length),
220 ], message = _b[0], buffer = _b[1];
221 i = message.indexOf("\r\n\r\n");
222 headers = parseHeaders(message.slice(0, i));
223 contentType_1 = headers["content-type"];
224 if (contentType_1 &&
225 contentType_1.toLowerCase().indexOf("application/json") === -1) {
226 throw new Error("Unsupported patch content type: application/json is required.");
227 }
228 body = message.slice(i);
229 if (body) {
230 result = parseJsonBody(response, body);
231 if (Object.keys(result).length > 1 ||
232 "data" in result ||
233 "incremental" in result ||
234 "errors" in result ||
235 "payload" in result) {
236 if (isApolloPayloadResult(result)) {
237 next = {};
238 if ("payload" in result) {
239 if (Object.keys(result).length === 1 && result.payload === null) {
240 return [2 ];
241 }
242 next = tslib.__assign({}, result.payload);
243 }
244 if ("errors" in result) {
245 next = tslib.__assign(tslib.__assign({}, next), { extensions: tslib.__assign(tslib.__assign({}, ("extensions" in next ? next.extensions : null)), (_c = {}, _c[errors.PROTOCOL_ERRORS_SYMBOL] = result.errors, _c)) });
246 }
247 nextValue(next);
248 }
249 else {
250 nextValue(result);
251 }
252 }
253 else if (
254 Object.keys(result).length === 1 &&
255 "hasNext" in result &&
256 !result.hasNext) {
257 return [2 ];
258 }
259 }
260 bi = buffer.indexOf(boundary);
261 }
262 return [3 , 1];
263 case 3: return [2 ];
264 }
265 });
266 });
267}
268function parseHeaders(headerText) {
269 var headersInit = {};
270 headerText.split("\n").forEach(function (line) {
271 var i = line.indexOf(":");
272 if (i > -1) {
273 var name_1 = line.slice(0, i).trim().toLowerCase();
274 var value = line.slice(i + 1).trim();
275 headersInit[name_1] = value;
276 }
277 });
278 return headersInit;
279}
280function parseJsonBody(response, bodyText) {
281 if (response.status >= 300) {
282 var getResult = function () {
283 try {
284 return JSON.parse(bodyText);
285 }
286 catch (err) {
287 return bodyText;
288 }
289 };
290 utils.throwServerError(response, getResult(), "Response not successful: Received status code ".concat(response.status));
291 }
292 try {
293 return JSON.parse(bodyText);
294 }
295 catch (err) {
296 var parseError = err;
297 parseError.name = "ServerParseError";
298 parseError.response = response;
299 parseError.statusCode = response.status;
300 parseError.bodyText = bodyText;
301 throw parseError;
302 }
303}
304function handleError(err, observer) {
305 if (err.result && err.result.errors && err.result.data) {
306 observer.next(err.result);
307 }
308 observer.error(err);
309}
310function parseAndCheckHttpResponse(operations) {
311 return function (response) {
312 return response
313 .text()
314 .then(function (bodyText) { return parseJsonBody(response, bodyText); })
315 .then(function (result) {
316 if (!Array.isArray(result) &&
317 !hasOwnProperty.call(result, "data") &&
318 !hasOwnProperty.call(result, "errors")) {
319 utils.throwServerError(response, result, "Server response was missing for query '".concat(Array.isArray(operations) ?
320 operations.map(function (op) { return op.operationName; })
321 : operations.operationName, "'."));
322 }
323 return result;
324 });
325 };
326}
327
328var serializeFetchParameter = function (p, label) {
329 var serialized;
330 try {
331 serialized = JSON.stringify(p);
332 }
333 catch (e) {
334 var parseError = globals.newInvariantError(40, label, e.message);
335 parseError.parseError = e;
336 throw parseError;
337 }
338 return serialized;
339};
340
341var defaultHttpOptions = {
342 includeQuery: true,
343 includeExtensions: false,
344 preserveHeaderCase: false,
345};
346var defaultHeaders = {
347 accept: "*/*",
348 "content-type": "application/json",
349};
350var defaultOptions = {
351 method: "POST",
352};
353var fallbackHttpConfig = {
354 http: defaultHttpOptions,
355 headers: defaultHeaders,
356 options: defaultOptions,
357};
358var defaultPrinter = function (ast, printer) { return printer(ast); };
359function selectHttpOptionsAndBody(operation, fallbackConfig) {
360 var configs = [];
361 for (var _i = 2; _i < arguments.length; _i++) {
362 configs[_i - 2] = arguments[_i];
363 }
364 configs.unshift(fallbackConfig);
365 return selectHttpOptionsAndBodyInternal.apply(void 0, tslib.__spreadArray([operation,
366 defaultPrinter], configs, false));
367}
368function selectHttpOptionsAndBodyInternal(operation, printer) {
369 var configs = [];
370 for (var _i = 2; _i < arguments.length; _i++) {
371 configs[_i - 2] = arguments[_i];
372 }
373 var options = {};
374 var http = {};
375 configs.forEach(function (config) {
376 options = tslib.__assign(tslib.__assign(tslib.__assign({}, options), config.options), { headers: tslib.__assign(tslib.__assign({}, options.headers), config.headers) });
377 if (config.credentials) {
378 options.credentials = config.credentials;
379 }
380 http = tslib.__assign(tslib.__assign({}, http), config.http);
381 });
382 if (options.headers) {
383 options.headers = removeDuplicateHeaders(options.headers, http.preserveHeaderCase);
384 }
385 var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;
386 var body = { operationName: operationName, variables: variables };
387 if (http.includeExtensions)
388 body.extensions = extensions;
389 if (http.includeQuery)
390 body.query = printer(query, utilities.print);
391 return {
392 options: options,
393 body: body,
394 };
395}
396function removeDuplicateHeaders(headers, preserveHeaderCase) {
397 if (!preserveHeaderCase) {
398 var normalizedHeaders_1 = Object.create(null);
399 Object.keys(Object(headers)).forEach(function (name) {
400 normalizedHeaders_1[name.toLowerCase()] = headers[name];
401 });
402 return normalizedHeaders_1;
403 }
404 var headerData = Object.create(null);
405 Object.keys(Object(headers)).forEach(function (name) {
406 headerData[name.toLowerCase()] = {
407 originalName: name,
408 value: headers[name],
409 };
410 });
411 var normalizedHeaders = Object.create(null);
412 Object.keys(headerData).forEach(function (name) {
413 normalizedHeaders[headerData[name].originalName] = headerData[name].value;
414 });
415 return normalizedHeaders;
416}
417
418var checkFetcher = function (fetcher) {
419 if (!fetcher && typeof fetch === "undefined") {
420 throw globals.newInvariantError(38);
421 }
422};
423
424var createSignalIfSupported = function () {
425 if (typeof AbortController === "undefined")
426 return { controller: false, signal: false };
427 var controller = new AbortController();
428 var signal = controller.signal;
429 return { controller: controller, signal: signal };
430};
431
432var selectURI = function (operation, fallbackURI) {
433 var context = operation.getContext();
434 var contextURI = context.uri;
435 if (contextURI) {
436 return contextURI;
437 }
438 else if (typeof fallbackURI === "function") {
439 return fallbackURI(operation);
440 }
441 else {
442 return fallbackURI || "/graphql";
443 }
444};
445
446function rewriteURIForGET(chosenURI, body) {
447 var queryParams = [];
448 var addQueryParam = function (key, value) {
449 queryParams.push("".concat(key, "=").concat(encodeURIComponent(value)));
450 };
451 if ("query" in body) {
452 addQueryParam("query", body.query);
453 }
454 if (body.operationName) {
455 addQueryParam("operationName", body.operationName);
456 }
457 if (body.variables) {
458 var serializedVariables = void 0;
459 try {
460 serializedVariables = serializeFetchParameter(body.variables, "Variables map");
461 }
462 catch (parseError) {
463 return { parseError: parseError };
464 }
465 addQueryParam("variables", serializedVariables);
466 }
467 if (body.extensions) {
468 var serializedExtensions = void 0;
469 try {
470 serializedExtensions = serializeFetchParameter(body.extensions, "Extensions map");
471 }
472 catch (parseError) {
473 return { parseError: parseError };
474 }
475 addQueryParam("extensions", serializedExtensions);
476 }
477 var fragment = "", preFragment = chosenURI;
478 var fragmentStart = chosenURI.indexOf("#");
479 if (fragmentStart !== -1) {
480 fragment = chosenURI.substr(fragmentStart);
481 preFragment = chosenURI.substr(0, fragmentStart);
482 }
483 var queryParamsPrefix = preFragment.indexOf("?") === -1 ? "?" : "&";
484 var newURI = preFragment + queryParamsPrefix + queryParams.join("&") + fragment;
485 return { newURI: newURI };
486}
487
488var backupFetch = utilities.maybe(function () { return fetch; });
489var createHttpLink = function (linkOptions) {
490 if (linkOptions === void 0) { linkOptions = {}; }
491 var _a = linkOptions.uri, uri = _a === void 0 ? "/graphql" : _a,
492 preferredFetch = linkOptions.fetch, _b = linkOptions.print, print = _b === void 0 ? defaultPrinter : _b, includeExtensions = linkOptions.includeExtensions, preserveHeaderCase = linkOptions.preserveHeaderCase, useGETForQueries = linkOptions.useGETForQueries, _c = linkOptions.includeUnusedVariables, includeUnusedVariables = _c === void 0 ? false : _c, requestOptions = tslib.__rest(linkOptions, ["uri", "fetch", "print", "includeExtensions", "preserveHeaderCase", "useGETForQueries", "includeUnusedVariables"]);
493 if (globalThis.__DEV__ !== false) {
494 checkFetcher(preferredFetch || backupFetch);
495 }
496 var linkConfig = {
497 http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
498 options: requestOptions.fetchOptions,
499 credentials: requestOptions.credentials,
500 headers: requestOptions.headers,
501 };
502 return new core.ApolloLink(function (operation) {
503 var chosenURI = selectURI(operation, uri);
504 var context = operation.getContext();
505 var clientAwarenessHeaders = {};
506 if (context.clientAwareness) {
507 var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
508 if (name_1) {
509 clientAwarenessHeaders["apollographql-client-name"] = name_1;
510 }
511 if (version) {
512 clientAwarenessHeaders["apollographql-client-version"] = version;
513 }
514 }
515 var contextHeaders = tslib.__assign(tslib.__assign({}, clientAwarenessHeaders), context.headers);
516 var contextConfig = {
517 http: context.http,
518 options: context.fetchOptions,
519 credentials: context.credentials,
520 headers: contextHeaders,
521 };
522 if (utilities.hasDirectives(["client"], operation.query)) {
523 var transformedQuery = utilities.removeClientSetsFromDocument(operation.query);
524 if (!transformedQuery) {
525 return utils.fromError(new Error("HttpLink: Trying to send a client-only query to the server. To send to the server, ensure a non-client field is added to the query or set the `transformOptions.removeClientFields` option to `true`."));
526 }
527 operation.query = transformedQuery;
528 }
529 var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;
530 if (body.variables && !includeUnusedVariables) {
531 body.variables = utils.filterOperationVariables(body.variables, operation.query);
532 }
533 var controller;
534 if (!options.signal && typeof AbortController !== "undefined") {
535 controller = new AbortController();
536 options.signal = controller.signal;
537 }
538 var definitionIsMutation = function (d) {
539 return d.kind === "OperationDefinition" && d.operation === "mutation";
540 };
541 var definitionIsSubscription = function (d) {
542 return d.kind === "OperationDefinition" && d.operation === "subscription";
543 };
544 var isSubscription = definitionIsSubscription(utilities.getMainDefinition(operation.query));
545 var hasDefer = utilities.hasDirectives(["defer"], operation.query);
546 if (useGETForQueries &&
547 !operation.query.definitions.some(definitionIsMutation)) {
548 options.method = "GET";
549 }
550 if (hasDefer || isSubscription) {
551 options.headers = options.headers || {};
552 var acceptHeader = "multipart/mixed;";
553 if (isSubscription && hasDefer) {
554 globalThis.__DEV__ !== false && globals.invariant.warn(39);
555 }
556 if (isSubscription) {
557 acceptHeader +=
558 "boundary=graphql;subscriptionSpec=1.0,application/json";
559 }
560 else if (hasDefer) {
561 acceptHeader += "deferSpec=20220824,application/json";
562 }
563 options.headers.accept = acceptHeader;
564 }
565 if (options.method === "GET") {
566 var _c = rewriteURIForGET(chosenURI, body), newURI = _c.newURI, parseError = _c.parseError;
567 if (parseError) {
568 return utils.fromError(parseError);
569 }
570 chosenURI = newURI;
571 }
572 else {
573 try {
574 options.body = serializeFetchParameter(body, "Payload");
575 }
576 catch (parseError) {
577 return utils.fromError(parseError);
578 }
579 }
580 return new utilities.Observable(function (observer) {
581 var currentFetch = preferredFetch || utilities.maybe(function () { return fetch; }) || backupFetch;
582 var observerNext = observer.next.bind(observer);
583 currentFetch(chosenURI, options)
584 .then(function (response) {
585 var _a;
586 operation.setContext({ response: response });
587 var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
588 if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
589 return readMultipartBody(response, observerNext);
590 }
591 else {
592 return parseAndCheckHttpResponse(operation)(response).then(observerNext);
593 }
594 })
595 .then(function () {
596 controller = undefined;
597 observer.complete();
598 })
599 .catch(function (err) {
600 controller = undefined;
601 handleError(err, observer);
602 });
603 return function () {
604 if (controller)
605 controller.abort();
606 };
607 });
608 });
609};
610
611var HttpLink = (function (_super) {
612 tslib.__extends(HttpLink, _super);
613 function HttpLink(options) {
614 if (options === void 0) { options = {}; }
615 var _this = _super.call(this, createHttpLink(options).request) || this;
616 _this.options = options;
617 return _this;
618 }
619 return HttpLink;
620}(core.ApolloLink));
621
622exports.HttpLink = HttpLink;
623exports.checkFetcher = checkFetcher;
624exports.createHttpLink = createHttpLink;
625exports.createSignalIfSupported = createSignalIfSupported;
626exports.defaultPrinter = defaultPrinter;
627exports.fallbackHttpConfig = fallbackHttpConfig;
628exports.parseAndCheckHttpResponse = parseAndCheckHttpResponse;
629exports.rewriteURIForGET = rewriteURIForGET;
630exports.selectHttpOptionsAndBody = selectHttpOptionsAndBody;
631exports.selectHttpOptionsAndBodyInternal = selectHttpOptionsAndBodyInternal;
632exports.selectURI = selectURI;
633exports.serializeFetchParameter = serializeFetchParameter;
634//# sourceMappingURL=http.cjs.map