Initial Sample.

This commit is contained in:
2024-06-03 20:23:50 +05:30
parent ef2b65f673
commit 5269ec3c66
2575 changed files with 282312 additions and 0 deletions

View File

@@ -0,0 +1,160 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var core = require('../core');
var utilities = require('../../utilities');
var utils = require('../utils');
var http = require('../http');
var batch = require('../batch');
var graphql = require('graphql');
function filterOperationVariables(variables, query) {
var result = tslib.__assign({}, variables);
var unusedNames = new Set(Object.keys(variables));
graphql.visit(query, {
Variable: function (node, _key, parent) {
if (parent &&
parent.kind !== "VariableDefinition") {
unusedNames.delete(node.name.value);
}
},
});
unusedNames.forEach(function (name) {
delete result[name];
});
return result;
}
var BatchHttpLink = (function (_super) {
tslib.__extends(BatchHttpLink, _super);
function BatchHttpLink(fetchParams) {
var _this = _super.call(this) || this;
var _a = fetchParams || {}, _b = _a.uri, uri = _b === void 0 ? "/graphql" : _b,
fetcher = _a.fetch, _c = _a.print, print = _c === void 0 ? http.defaultPrinter : _c, includeExtensions = _a.includeExtensions, preserveHeaderCase = _a.preserveHeaderCase, batchInterval = _a.batchInterval, batchDebounce = _a.batchDebounce, batchMax = _a.batchMax, batchKey = _a.batchKey, _d = _a.includeUnusedVariables, includeUnusedVariables = _d === void 0 ? false : _d, requestOptions = tslib.__rest(_a, ["uri", "fetch", "print", "includeExtensions", "preserveHeaderCase", "batchInterval", "batchDebounce", "batchMax", "batchKey", "includeUnusedVariables"]);
http.checkFetcher(fetcher);
if (!fetcher) {
fetcher = fetch;
}
var linkConfig = {
http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
_this.batchDebounce = batchDebounce;
_this.batchInterval = batchInterval || 10;
_this.batchMax = batchMax || 10;
var batchHandler = function (operations) {
var chosenURI = http.selectURI(operations[0], uri);
var context = operations[0].getContext();
var clientAwarenessHeaders = {};
if (context.clientAwareness) {
var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
if (name_1) {
clientAwarenessHeaders["apollographql-client-name"] = name_1;
}
if (version) {
clientAwarenessHeaders["apollographql-client-version"] = version;
}
}
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: tslib.__assign(tslib.__assign({}, clientAwarenessHeaders), context.headers),
};
var queries = operations.map(function (_a) {
var query = _a.query;
if (utilities.hasDirectives(["client"], query)) {
return utilities.removeClientSetsFromDocument(query);
}
return query;
});
if (queries.some(function (query) { return !query; })) {
return utils.fromError(new Error("BatchHttpLink: 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 enable the `transformOptions.removeClientFields` option."));
}
var optsAndBody = operations.map(function (operation, index) {
var result = http.selectHttpOptionsAndBodyInternal(tslib.__assign(tslib.__assign({}, operation), { query: queries[index] }), print, http.fallbackHttpConfig, linkConfig, contextConfig);
if (result.body.variables && !includeUnusedVariables) {
result.body.variables = filterOperationVariables(result.body.variables, operation.query);
}
return result;
});
var loadedBody = optsAndBody.map(function (_a) {
var body = _a.body;
return body;
});
var options = optsAndBody[0].options;
if (options.method === "GET") {
return utils.fromError(new Error("apollo-link-batch-http does not support GET requests"));
}
try {
options.body = http.serializeFetchParameter(loadedBody, "Payload");
}
catch (parseError) {
return utils.fromError(parseError);
}
var controller;
if (!options.signal && typeof AbortController !== "undefined") {
controller = new AbortController();
options.signal = controller.signal;
}
return new utilities.Observable(function (observer) {
fetcher(chosenURI, options)
.then(function (response) {
operations.forEach(function (operation) {
return operation.setContext({ response: response });
});
return response;
})
.then(http.parseAndCheckHttpResponse(operations))
.then(function (result) {
controller = undefined;
observer.next(result);
observer.complete();
return result;
})
.catch(function (err) {
controller = undefined;
if (err.result && err.result.errors && err.result.data) {
observer.next(err.result);
}
observer.error(err);
});
return function () {
if (controller)
controller.abort();
};
});
};
batchKey =
batchKey ||
(function (operation) {
var context = operation.getContext();
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: context.headers,
};
return http.selectURI(operation, uri) + JSON.stringify(contextConfig);
});
_this.batcher = new batch.BatchLink({
batchDebounce: _this.batchDebounce,
batchInterval: _this.batchInterval,
batchMax: _this.batchMax,
batchKey: batchKey,
batchHandler: batchHandler,
});
return _this;
}
BatchHttpLink.prototype.request = function (operation) {
return this.batcher.request(operation);
};
return BatchHttpLink;
}(core.ApolloLink));
exports.BatchHttpLink = BatchHttpLink;
//# sourceMappingURL=batch-http.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,160 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var core = require('../core');
var utilities = require('../../utilities');
var utils = require('../utils');
var http = require('../http');
var batch = require('../batch');
var graphql = require('graphql');
function filterOperationVariables(variables, query) {
var result = tslib.__assign({}, variables);
var unusedNames = new Set(Object.keys(variables));
graphql.visit(query, {
Variable: function (node, _key, parent) {
if (parent &&
parent.kind !== "VariableDefinition") {
unusedNames.delete(node.name.value);
}
},
});
unusedNames.forEach(function (name) {
delete result[name];
});
return result;
}
var BatchHttpLink = (function (_super) {
tslib.__extends(BatchHttpLink, _super);
function BatchHttpLink(fetchParams) {
var _this = _super.call(this) || this;
var _a = fetchParams || {}, _b = _a.uri, uri = _b === void 0 ? "/graphql" : _b,
fetcher = _a.fetch, _c = _a.print, print = _c === void 0 ? http.defaultPrinter : _c, includeExtensions = _a.includeExtensions, preserveHeaderCase = _a.preserveHeaderCase, batchInterval = _a.batchInterval, batchDebounce = _a.batchDebounce, batchMax = _a.batchMax, batchKey = _a.batchKey, _d = _a.includeUnusedVariables, includeUnusedVariables = _d === void 0 ? false : _d, requestOptions = tslib.__rest(_a, ["uri", "fetch", "print", "includeExtensions", "preserveHeaderCase", "batchInterval", "batchDebounce", "batchMax", "batchKey", "includeUnusedVariables"]);
http.checkFetcher(fetcher);
if (!fetcher) {
fetcher = fetch;
}
var linkConfig = {
http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
_this.batchDebounce = batchDebounce;
_this.batchInterval = batchInterval || 10;
_this.batchMax = batchMax || 10;
var batchHandler = function (operations) {
var chosenURI = http.selectURI(operations[0], uri);
var context = operations[0].getContext();
var clientAwarenessHeaders = {};
if (context.clientAwareness) {
var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
if (name_1) {
clientAwarenessHeaders["apollographql-client-name"] = name_1;
}
if (version) {
clientAwarenessHeaders["apollographql-client-version"] = version;
}
}
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: tslib.__assign(tslib.__assign({}, clientAwarenessHeaders), context.headers),
};
var queries = operations.map(function (_a) {
var query = _a.query;
if (utilities.hasDirectives(["client"], query)) {
return utilities.removeClientSetsFromDocument(query);
}
return query;
});
if (queries.some(function (query) { return !query; })) {
return utils.fromError(new Error("BatchHttpLink: 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 enable the `transformOptions.removeClientFields` option."));
}
var optsAndBody = operations.map(function (operation, index) {
var result = http.selectHttpOptionsAndBodyInternal(tslib.__assign(tslib.__assign({}, operation), { query: queries[index] }), print, http.fallbackHttpConfig, linkConfig, contextConfig);
if (result.body.variables && !includeUnusedVariables) {
result.body.variables = filterOperationVariables(result.body.variables, operation.query);
}
return result;
});
var loadedBody = optsAndBody.map(function (_a) {
var body = _a.body;
return body;
});
var options = optsAndBody[0].options;
if (options.method === "GET") {
return utils.fromError(new Error("apollo-link-batch-http does not support GET requests"));
}
try {
options.body = http.serializeFetchParameter(loadedBody, "Payload");
}
catch (parseError) {
return utils.fromError(parseError);
}
var controller;
if (!options.signal && typeof AbortController !== "undefined") {
controller = new AbortController();
options.signal = controller.signal;
}
return new utilities.Observable(function (observer) {
fetcher(chosenURI, options)
.then(function (response) {
operations.forEach(function (operation) {
return operation.setContext({ response: response });
});
return response;
})
.then(http.parseAndCheckHttpResponse(operations))
.then(function (result) {
controller = undefined;
observer.next(result);
observer.complete();
return result;
})
.catch(function (err) {
controller = undefined;
if (err.result && err.result.errors && err.result.data) {
observer.next(err.result);
}
observer.error(err);
});
return function () {
if (controller)
controller.abort();
};
});
};
batchKey =
batchKey ||
(function (operation) {
var context = operation.getContext();
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: context.headers,
};
return http.selectURI(operation, uri) + JSON.stringify(contextConfig);
});
_this.batcher = new batch.BatchLink({
batchDebounce: _this.batchDebounce,
batchInterval: _this.batchInterval,
batchMax: _this.batchMax,
batchKey: batchKey,
batchHandler: batchHandler,
});
return _this;
}
BatchHttpLink.prototype.request = function (operation) {
return this.batcher.request(operation);
};
return BatchHttpLink;
}(core.ApolloLink));
exports.BatchHttpLink = BatchHttpLink;
//# sourceMappingURL=batch-http.cjs.map

View File

@@ -0,0 +1,21 @@
import type { Operation, FetchResult } from "../core/index.js";
import { ApolloLink } from "../core/index.js";
import { Observable } from "../../utilities/index.js";
import type { HttpOptions } from "../http/index.js";
import { BatchLink } from "../batch/index.js";
export declare namespace BatchHttpLink {
type Options = Pick<BatchLink.Options, "batchMax" | "batchDebounce" | "batchInterval" | "batchKey"> & Omit<HttpOptions, "useGETForQueries">;
}
/**
* Transforms Operation for into HTTP results.
* context can include the headers property, which will be passed to the fetch function
*/
export declare class BatchHttpLink extends ApolloLink {
private batchDebounce?;
private batchInterval;
private batchMax;
private batcher;
constructor(fetchParams?: BatchHttpLink.Options);
request(operation: Operation): Observable<FetchResult> | null;
}
//# sourceMappingURL=batchHttpLink.d.ts.map

View File

@@ -0,0 +1,187 @@
import { __assign, __extends, __rest } from "tslib";
import { ApolloLink } from "../core/index.js";
import { Observable, hasDirectives, removeClientSetsFromDocument, } from "../../utilities/index.js";
import { fromError } from "../utils/index.js";
import { serializeFetchParameter, selectURI, parseAndCheckHttpResponse, checkFetcher, selectHttpOptionsAndBodyInternal, defaultPrinter, fallbackHttpConfig, } from "../http/index.js";
import { BatchLink } from "../batch/index.js";
import { filterOperationVariables } from "../utils/filterOperationVariables.js";
/**
* Transforms Operation for into HTTP results.
* context can include the headers property, which will be passed to the fetch function
*/
var BatchHttpLink = /** @class */ (function (_super) {
__extends(BatchHttpLink, _super);
function BatchHttpLink(fetchParams) {
var _this = _super.call(this) || this;
var _a = fetchParams || {}, _b = _a.uri, uri = _b === void 0 ? "/graphql" : _b,
// use default global fetch if nothing is passed in
fetcher = _a.fetch, _c = _a.print, print = _c === void 0 ? defaultPrinter : _c, includeExtensions = _a.includeExtensions, preserveHeaderCase = _a.preserveHeaderCase, batchInterval = _a.batchInterval, batchDebounce = _a.batchDebounce, batchMax = _a.batchMax, batchKey = _a.batchKey, _d = _a.includeUnusedVariables, includeUnusedVariables = _d === void 0 ? false : _d, requestOptions = __rest(_a, ["uri", "fetch", "print", "includeExtensions", "preserveHeaderCase", "batchInterval", "batchDebounce", "batchMax", "batchKey", "includeUnusedVariables"]);
// dev warnings to ensure fetch is present
checkFetcher(fetcher);
//fetcher is set here rather than the destructuring to ensure fetch is
//declared before referencing it. Reference in the destructuring would cause
//a ReferenceError
if (!fetcher) {
fetcher = fetch;
}
var linkConfig = {
http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
_this.batchDebounce = batchDebounce;
_this.batchInterval = batchInterval || 10;
_this.batchMax = batchMax || 10;
var batchHandler = function (operations) {
var chosenURI = selectURI(operations[0], uri);
var context = operations[0].getContext();
var clientAwarenessHeaders = {};
if (context.clientAwareness) {
var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
if (name_1) {
clientAwarenessHeaders["apollographql-client-name"] = name_1;
}
if (version) {
clientAwarenessHeaders["apollographql-client-version"] = version;
}
}
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: __assign(__assign({}, clientAwarenessHeaders), context.headers),
};
var queries = operations.map(function (_a) {
var query = _a.query;
if (hasDirectives(["client"], query)) {
return removeClientSetsFromDocument(query);
}
return query;
});
// If we have a query that returned `null` after removing client-only
// fields, it indicates a query that is using all client-only fields.
if (queries.some(function (query) { return !query; })) {
return fromError(new Error("BatchHttpLink: 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 enable the `transformOptions.removeClientFields` option."));
}
//uses fallback, link, and then context to build options
var optsAndBody = operations.map(function (operation, index) {
var result = selectHttpOptionsAndBodyInternal(__assign(__assign({}, operation), { query: queries[index] }), print, fallbackHttpConfig, linkConfig, contextConfig);
if (result.body.variables && !includeUnusedVariables) {
result.body.variables = filterOperationVariables(result.body.variables, operation.query);
}
return result;
});
var loadedBody = optsAndBody.map(function (_a) {
var body = _a.body;
return body;
});
var options = optsAndBody[0].options;
// There's no spec for using GET with batches.
if (options.method === "GET") {
return fromError(new Error("apollo-link-batch-http does not support GET requests"));
}
try {
options.body = serializeFetchParameter(loadedBody, "Payload");
}
catch (parseError) {
return fromError(parseError);
}
var controller;
if (!options.signal && typeof AbortController !== "undefined") {
controller = new AbortController();
options.signal = controller.signal;
}
return new Observable(function (observer) {
fetcher(chosenURI, options)
.then(function (response) {
// Make the raw response available in the context.
operations.forEach(function (operation) {
return operation.setContext({ response: response });
});
return response;
})
.then(parseAndCheckHttpResponse(operations))
.then(function (result) {
controller = undefined;
// we have data and can send it to back up the link chain
observer.next(result);
observer.complete();
return result;
})
.catch(function (err) {
controller = undefined;
// if it is a network error, BUT there is graphql result info
// fire the next observer before calling error
// this gives apollo-client (and react-apollo) the `graphqlErrors` and `networkErrors`
// to pass to UI
// this should only happen if we *also* have data as part of the response key per
// the spec
if (err.result && err.result.errors && err.result.data) {
// if we dont' call next, the UI can only show networkError because AC didn't
// get andy graphqlErrors
// this is graphql execution result info (i.e errors and possibly data)
// this is because there is no formal spec how errors should translate to
// http status codes. So an auth error (401) could have both data
// from a public field, errors from a private field, and a status of 401
// {
// user { // this will have errors
// firstName
// }
// products { // this is public so will have data
// cost
// }
// }
//
// the result of above *could* look like this:
// {
// data: { products: [{ cost: "$10" }] },
// errors: [{
// message: 'your session has timed out',
// path: []
// }]
// }
// status code of above would be a 401
// in the UI you want to show data where you can, errors as data where you can
// and use correct http status codes
observer.next(err.result);
}
observer.error(err);
});
return function () {
// XXX support canceling this request
// https://developers.google.com/web/updates/2017/09/abortable-fetch
if (controller)
controller.abort();
};
});
};
batchKey =
batchKey ||
(function (operation) {
var context = operation.getContext();
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: context.headers,
};
//may throw error if config not serializable
return selectURI(operation, uri) + JSON.stringify(contextConfig);
});
_this.batcher = new BatchLink({
batchDebounce: _this.batchDebounce,
batchInterval: _this.batchInterval,
batchMax: _this.batchMax,
batchKey: batchKey,
batchHandler: batchHandler,
});
return _this;
}
BatchHttpLink.prototype.request = function (operation) {
return this.batcher.request(operation);
};
return BatchHttpLink;
}(ApolloLink));
export { BatchHttpLink };
//# sourceMappingURL=batchHttpLink.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export * from "./batchHttpLink.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,2 @@
export * from "./batchHttpLink.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/link/batch-http/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC","sourcesContent":["export * from \"./batchHttpLink.js\";\n"]}

View File

@@ -0,0 +1,8 @@
{
"name": "@apollo/client/link/batch-http",
"type": "module",
"main": "batch-http.cjs",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false
}

View File

@@ -0,0 +1,159 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var core = require('../core');
var utilities = require('../../utilities');
var OperationBatcher = (function () {
function OperationBatcher(_a) {
var batchDebounce = _a.batchDebounce, batchInterval = _a.batchInterval, batchMax = _a.batchMax, batchHandler = _a.batchHandler, batchKey = _a.batchKey;
this.batchesByKey = new Map();
this.scheduledBatchTimerByKey = new Map();
this.batchDebounce = batchDebounce;
this.batchInterval = batchInterval;
this.batchMax = batchMax || 0;
this.batchHandler = batchHandler;
this.batchKey = batchKey || (function () { return ""; });
}
OperationBatcher.prototype.enqueueRequest = function (request) {
var _this = this;
var requestCopy = tslib.__assign(tslib.__assign({}, request), { next: [], error: [], complete: [], subscribers: new Set() });
var key = this.batchKey(request.operation);
if (!requestCopy.observable) {
requestCopy.observable = new utilities.Observable(function (observer) {
var batch = _this.batchesByKey.get(key);
if (!batch)
_this.batchesByKey.set(key, (batch = new Set()));
var isFirstEnqueuedRequest = batch.size === 0;
var isFirstSubscriber = requestCopy.subscribers.size === 0;
requestCopy.subscribers.add(observer);
if (isFirstSubscriber) {
batch.add(requestCopy);
}
if (observer.next) {
requestCopy.next.push(observer.next.bind(observer));
}
if (observer.error) {
requestCopy.error.push(observer.error.bind(observer));
}
if (observer.complete) {
requestCopy.complete.push(observer.complete.bind(observer));
}
if (isFirstEnqueuedRequest || _this.batchDebounce) {
_this.scheduleQueueConsumption(key);
}
if (batch.size === _this.batchMax) {
_this.consumeQueue(key);
}
return function () {
var _a;
if (requestCopy.subscribers.delete(observer) &&
requestCopy.subscribers.size < 1) {
if (batch.delete(requestCopy) && batch.size < 1) {
_this.consumeQueue(key);
(_a = batch.subscription) === null || _a === void 0 ? void 0 : _a.unsubscribe();
}
}
};
});
}
return requestCopy.observable;
};
OperationBatcher.prototype.consumeQueue = function (key) {
if (key === void 0) { key = ""; }
var batch = this.batchesByKey.get(key);
this.batchesByKey.delete(key);
if (!batch || !batch.size) {
return;
}
var operations = [];
var forwards = [];
var observables = [];
var nexts = [];
var errors = [];
var completes = [];
batch.forEach(function (request) {
operations.push(request.operation);
forwards.push(request.forward);
observables.push(request.observable);
nexts.push(request.next);
errors.push(request.error);
completes.push(request.complete);
});
var batchedObservable = this.batchHandler(operations, forwards) || utilities.Observable.of();
var onError = function (error) {
errors.forEach(function (rejecters) {
if (rejecters) {
rejecters.forEach(function (e) { return e(error); });
}
});
};
batch.subscription = batchedObservable.subscribe({
next: function (results) {
if (!Array.isArray(results)) {
results = [results];
}
if (nexts.length !== results.length) {
var error = new Error("server returned results with length ".concat(results.length, ", expected length of ").concat(nexts.length));
error.result = results;
return onError(error);
}
results.forEach(function (result, index) {
if (nexts[index]) {
nexts[index].forEach(function (next) { return next(result); });
}
});
},
error: onError,
complete: function () {
completes.forEach(function (complete) {
if (complete) {
complete.forEach(function (c) { return c(); });
}
});
},
});
return observables;
};
OperationBatcher.prototype.scheduleQueueConsumption = function (key) {
var _this = this;
clearTimeout(this.scheduledBatchTimerByKey.get(key));
this.scheduledBatchTimerByKey.set(key, setTimeout(function () {
_this.consumeQueue(key);
_this.scheduledBatchTimerByKey.delete(key);
}, this.batchInterval));
};
return OperationBatcher;
}());
var BatchLink = (function (_super) {
tslib.__extends(BatchLink, _super);
function BatchLink(fetchParams) {
var _this = _super.call(this) || this;
var _a = fetchParams || {}, batchDebounce = _a.batchDebounce, _b = _a.batchInterval, batchInterval = _b === void 0 ? 10 : _b, _c = _a.batchMax, batchMax = _c === void 0 ? 0 : _c, _d = _a.batchHandler, batchHandler = _d === void 0 ? function () { return null; } : _d, _e = _a.batchKey, batchKey = _e === void 0 ? function () { return ""; } : _e;
_this.batcher = new OperationBatcher({
batchDebounce: batchDebounce,
batchInterval: batchInterval,
batchMax: batchMax,
batchHandler: batchHandler,
batchKey: batchKey,
});
if (fetchParams.batchHandler.length <= 1) {
_this.request = function (operation) { return _this.batcher.enqueueRequest({ operation: operation }); };
}
return _this;
}
BatchLink.prototype.request = function (operation, forward) {
return this.batcher.enqueueRequest({
operation: operation,
forward: forward,
});
};
return BatchLink;
}(core.ApolloLink));
exports.BatchLink = BatchLink;
exports.OperationBatcher = OperationBatcher;
//# sourceMappingURL=batch.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,159 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var core = require('../core');
var utilities = require('../../utilities');
var OperationBatcher = (function () {
function OperationBatcher(_a) {
var batchDebounce = _a.batchDebounce, batchInterval = _a.batchInterval, batchMax = _a.batchMax, batchHandler = _a.batchHandler, batchKey = _a.batchKey;
this.batchesByKey = new Map();
this.scheduledBatchTimerByKey = new Map();
this.batchDebounce = batchDebounce;
this.batchInterval = batchInterval;
this.batchMax = batchMax || 0;
this.batchHandler = batchHandler;
this.batchKey = batchKey || (function () { return ""; });
}
OperationBatcher.prototype.enqueueRequest = function (request) {
var _this = this;
var requestCopy = tslib.__assign(tslib.__assign({}, request), { next: [], error: [], complete: [], subscribers: new Set() });
var key = this.batchKey(request.operation);
if (!requestCopy.observable) {
requestCopy.observable = new utilities.Observable(function (observer) {
var batch = _this.batchesByKey.get(key);
if (!batch)
_this.batchesByKey.set(key, (batch = new Set()));
var isFirstEnqueuedRequest = batch.size === 0;
var isFirstSubscriber = requestCopy.subscribers.size === 0;
requestCopy.subscribers.add(observer);
if (isFirstSubscriber) {
batch.add(requestCopy);
}
if (observer.next) {
requestCopy.next.push(observer.next.bind(observer));
}
if (observer.error) {
requestCopy.error.push(observer.error.bind(observer));
}
if (observer.complete) {
requestCopy.complete.push(observer.complete.bind(observer));
}
if (isFirstEnqueuedRequest || _this.batchDebounce) {
_this.scheduleQueueConsumption(key);
}
if (batch.size === _this.batchMax) {
_this.consumeQueue(key);
}
return function () {
var _a;
if (requestCopy.subscribers.delete(observer) &&
requestCopy.subscribers.size < 1) {
if (batch.delete(requestCopy) && batch.size < 1) {
_this.consumeQueue(key);
(_a = batch.subscription) === null || _a === void 0 ? void 0 : _a.unsubscribe();
}
}
};
});
}
return requestCopy.observable;
};
OperationBatcher.prototype.consumeQueue = function (key) {
if (key === void 0) { key = ""; }
var batch = this.batchesByKey.get(key);
this.batchesByKey.delete(key);
if (!batch || !batch.size) {
return;
}
var operations = [];
var forwards = [];
var observables = [];
var nexts = [];
var errors = [];
var completes = [];
batch.forEach(function (request) {
operations.push(request.operation);
forwards.push(request.forward);
observables.push(request.observable);
nexts.push(request.next);
errors.push(request.error);
completes.push(request.complete);
});
var batchedObservable = this.batchHandler(operations, forwards) || utilities.Observable.of();
var onError = function (error) {
errors.forEach(function (rejecters) {
if (rejecters) {
rejecters.forEach(function (e) { return e(error); });
}
});
};
batch.subscription = batchedObservable.subscribe({
next: function (results) {
if (!Array.isArray(results)) {
results = [results];
}
if (nexts.length !== results.length) {
var error = new Error("server returned results with length ".concat(results.length, ", expected length of ").concat(nexts.length));
error.result = results;
return onError(error);
}
results.forEach(function (result, index) {
if (nexts[index]) {
nexts[index].forEach(function (next) { return next(result); });
}
});
},
error: onError,
complete: function () {
completes.forEach(function (complete) {
if (complete) {
complete.forEach(function (c) { return c(); });
}
});
},
});
return observables;
};
OperationBatcher.prototype.scheduleQueueConsumption = function (key) {
var _this = this;
clearTimeout(this.scheduledBatchTimerByKey.get(key));
this.scheduledBatchTimerByKey.set(key, setTimeout(function () {
_this.consumeQueue(key);
_this.scheduledBatchTimerByKey.delete(key);
}, this.batchInterval));
};
return OperationBatcher;
}());
var BatchLink = (function (_super) {
tslib.__extends(BatchLink, _super);
function BatchLink(fetchParams) {
var _this = _super.call(this) || this;
var _a = fetchParams || {}, batchDebounce = _a.batchDebounce, _b = _a.batchInterval, batchInterval = _b === void 0 ? 10 : _b, _c = _a.batchMax, batchMax = _c === void 0 ? 0 : _c, _d = _a.batchHandler, batchHandler = _d === void 0 ? function () { return null; } : _d, _e = _a.batchKey, batchKey = _e === void 0 ? function () { return ""; } : _e;
_this.batcher = new OperationBatcher({
batchDebounce: batchDebounce,
batchInterval: batchInterval,
batchMax: batchMax,
batchHandler: batchHandler,
batchKey: batchKey,
});
if (fetchParams.batchHandler.length <= 1) {
_this.request = function (operation) { return _this.batcher.enqueueRequest({ operation: operation }); };
}
return _this;
}
BatchLink.prototype.request = function (operation, forward) {
return this.batcher.enqueueRequest({
operation: operation,
forward: forward,
});
};
return BatchLink;
}(core.ApolloLink));
exports.BatchLink = BatchLink;
exports.OperationBatcher = OperationBatcher;
//# sourceMappingURL=batch.cjs.map

View File

@@ -0,0 +1,42 @@
import type { Operation, FetchResult, NextLink } from "../core/index.js";
import { ApolloLink } from "../core/index.js";
import type { Observable } from "../../utilities/index.js";
import type { BatchHandler } from "./batching.js";
export type { BatchableRequest, BatchHandler } from "./batching.js";
export { OperationBatcher } from "./batching.js";
export declare namespace BatchLink {
interface Options {
/**
* The interval at which to batch, in milliseconds.
*
* Defaults to 10.
*/
batchInterval?: number;
/**
* "batchInterval" is a throttling behavior by default, if you instead wish
* to debounce outbound requests, set "batchDebounce" to true. More useful
* for mutations than queries.
*/
batchDebounce?: boolean;
/**
* The maximum number of operations to include in one fetch.
*
* Defaults to 0 (infinite operations within the interval).
*/
batchMax?: number;
/**
* The handler that should execute a batch of operations.
*/
batchHandler?: BatchHandler;
/**
* creates the key for a batch
*/
batchKey?: (operation: Operation) => string;
}
}
export declare class BatchLink extends ApolloLink {
private batcher;
constructor(fetchParams?: BatchLink.Options);
request(operation: Operation, forward?: NextLink): Observable<FetchResult> | null;
}
//# sourceMappingURL=batchLink.d.ts.map

View File

@@ -0,0 +1,32 @@
import { __extends } from "tslib";
import { ApolloLink } from "../core/index.js";
import { OperationBatcher } from "./batching.js";
export { OperationBatcher } from "./batching.js";
var BatchLink = /** @class */ (function (_super) {
__extends(BatchLink, _super);
function BatchLink(fetchParams) {
var _this = _super.call(this) || this;
var _a = fetchParams || {}, batchDebounce = _a.batchDebounce, _b = _a.batchInterval, batchInterval = _b === void 0 ? 10 : _b, _c = _a.batchMax, batchMax = _c === void 0 ? 0 : _c, _d = _a.batchHandler, batchHandler = _d === void 0 ? function () { return null; } : _d, _e = _a.batchKey, batchKey = _e === void 0 ? function () { return ""; } : _e;
_this.batcher = new OperationBatcher({
batchDebounce: batchDebounce,
batchInterval: batchInterval,
batchMax: batchMax,
batchHandler: batchHandler,
batchKey: batchKey,
});
//make this link terminating
if (fetchParams.batchHandler.length <= 1) {
_this.request = function (operation) { return _this.batcher.enqueueRequest({ operation: operation }); };
}
return _this;
}
BatchLink.prototype.request = function (operation, forward) {
return this.batcher.enqueueRequest({
operation: operation,
forward: forward,
});
};
return BatchLink;
}(ApolloLink));
export { BatchLink };
//# sourceMappingURL=batchLink.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"batchLink.js","sourceRoot":"","sources":["../../../src/link/batch/batchLink.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAG9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAqCjD;IAA+B,6BAAU;IAGvC,mBAAY,WAA+B;QACzC,YAAA,MAAK,WAAE,SAAC;QAEF,IAAA,KAMF,WAAW,IAAI,EAAE,EALnB,aAAa,mBAAA,EACb,qBAAkB,EAAlB,aAAa,mBAAG,EAAE,KAAA,EAClB,gBAAY,EAAZ,QAAQ,mBAAG,CAAC,KAAA,EACZ,oBAAyB,EAAzB,YAAY,mBAAG,cAAM,OAAA,IAAI,EAAJ,CAAI,KAAA,EACzB,gBAAmB,EAAnB,QAAQ,mBAAG,cAAM,OAAA,EAAE,EAAF,CAAE,KACA,CAAC;QAEtB,KAAI,CAAC,OAAO,GAAG,IAAI,gBAAgB,CAAC;YAClC,aAAa,eAAA;YACb,aAAa,eAAA;YACb,QAAQ,UAAA;YACR,YAAY,cAAA;YACZ,QAAQ,UAAA;SACT,CAAC,CAAC;QAEH,4BAA4B;QAC5B,IAAI,WAAY,CAAC,YAAa,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;YAC3C,KAAI,CAAC,OAAO,GAAG,UAAC,SAAS,IAAK,OAAA,KAAI,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,SAAS,WAAA,EAAE,CAAC,EAA1C,CAA0C,CAAC;QAC3E,CAAC;;IACH,CAAC;IAEM,2BAAO,GAAd,UACE,SAAoB,EACpB,OAAkB;QAElB,OAAO,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC;YACjC,SAAS,WAAA;YACT,OAAO,SAAA;SACR,CAAC,CAAC;IACL,CAAC;IACH,gBAAC;AAAD,CAAC,AArCD,CAA+B,UAAU,GAqCxC","sourcesContent":["import type { Operation, FetchResult, NextLink } from \"../core/index.js\";\nimport { ApolloLink } from \"../core/index.js\";\nimport type { Observable } from \"../../utilities/index.js\";\nimport type { BatchHandler } from \"./batching.js\";\nimport { OperationBatcher } from \"./batching.js\";\nexport type { BatchableRequest, BatchHandler } from \"./batching.js\";\nexport { OperationBatcher } from \"./batching.js\";\n\nexport namespace BatchLink {\n export interface Options {\n /**\n * The interval at which to batch, in milliseconds.\n *\n * Defaults to 10.\n */\n batchInterval?: number;\n\n /**\n * \"batchInterval\" is a throttling behavior by default, if you instead wish\n * to debounce outbound requests, set \"batchDebounce\" to true. More useful\n * for mutations than queries.\n */\n batchDebounce?: boolean;\n\n /**\n * The maximum number of operations to include in one fetch.\n *\n * Defaults to 0 (infinite operations within the interval).\n */\n batchMax?: number;\n\n /**\n * The handler that should execute a batch of operations.\n */\n batchHandler?: BatchHandler;\n\n /**\n * creates the key for a batch\n */\n batchKey?: (operation: Operation) => string;\n }\n}\n\nexport class BatchLink extends ApolloLink {\n private batcher: OperationBatcher;\n\n constructor(fetchParams?: BatchLink.Options) {\n super();\n\n const {\n batchDebounce,\n batchInterval = 10,\n batchMax = 0,\n batchHandler = () => null,\n batchKey = () => \"\",\n } = fetchParams || {};\n\n this.batcher = new OperationBatcher({\n batchDebounce,\n batchInterval,\n batchMax,\n batchHandler,\n batchKey,\n });\n\n //make this link terminating\n if (fetchParams!.batchHandler!.length <= 1) {\n this.request = (operation) => this.batcher.enqueueRequest({ operation });\n }\n }\n\n public request(\n operation: Operation,\n forward?: NextLink\n ): Observable<FetchResult> | null {\n return this.batcher.enqueueRequest({\n operation,\n forward,\n });\n }\n}\n"]}

View File

@@ -0,0 +1,27 @@
import type { FetchResult, NextLink, Operation } from "../core/index.js";
import { Observable } from "../../utilities/index.js";
export type BatchHandler = (operations: Operation[], forward?: (NextLink | undefined)[]) => Observable<FetchResult[]> | null;
export interface BatchableRequest {
operation: Operation;
forward?: NextLink;
}
export declare class OperationBatcher {
private batchesByKey;
private scheduledBatchTimerByKey;
private batchDebounce?;
private batchInterval?;
private batchMax;
private batchHandler;
private batchKey;
constructor({ batchDebounce, batchInterval, batchMax, batchHandler, batchKey, }: {
batchDebounce?: boolean;
batchInterval?: number;
batchMax?: number;
batchHandler: BatchHandler;
batchKey?: (operation: Operation) => string;
});
enqueueRequest(request: BatchableRequest): Observable<FetchResult>;
consumeQueue(key?: string): (Observable<FetchResult> | undefined)[] | undefined;
private scheduleQueueConsumption;
}
//# sourceMappingURL=batching.d.ts.map

View File

@@ -0,0 +1,148 @@
import { __assign } from "tslib";
import { Observable } from "../../utilities/index.js";
// QueryBatcher doesn't fire requests immediately. Requests that were enqueued within
// a certain amount of time (configurable through `batchInterval`) will be batched together
// into one query.
var OperationBatcher = /** @class */ (function () {
function OperationBatcher(_a) {
var batchDebounce = _a.batchDebounce, batchInterval = _a.batchInterval, batchMax = _a.batchMax, batchHandler = _a.batchHandler, batchKey = _a.batchKey;
// Queue on which the QueryBatcher will operate on a per-tick basis.
this.batchesByKey = new Map();
this.scheduledBatchTimerByKey = new Map();
this.batchDebounce = batchDebounce;
this.batchInterval = batchInterval;
this.batchMax = batchMax || 0;
this.batchHandler = batchHandler;
this.batchKey = batchKey || (function () { return ""; });
}
OperationBatcher.prototype.enqueueRequest = function (request) {
var _this = this;
var requestCopy = __assign(__assign({}, request), { next: [], error: [], complete: [], subscribers: new Set() });
var key = this.batchKey(request.operation);
if (!requestCopy.observable) {
requestCopy.observable = new Observable(function (observer) {
var batch = _this.batchesByKey.get(key);
if (!batch)
_this.batchesByKey.set(key, (batch = new Set()));
// These booleans seem to me (@benjamn) like they might always be the
// same (and thus we could do with only one of them), but I'm not 100%
// sure about that.
var isFirstEnqueuedRequest = batch.size === 0;
var isFirstSubscriber = requestCopy.subscribers.size === 0;
requestCopy.subscribers.add(observer);
if (isFirstSubscriber) {
batch.add(requestCopy);
}
// called for each subscriber, so need to save all listeners (next, error, complete)
if (observer.next) {
requestCopy.next.push(observer.next.bind(observer));
}
if (observer.error) {
requestCopy.error.push(observer.error.bind(observer));
}
if (observer.complete) {
requestCopy.complete.push(observer.complete.bind(observer));
}
// The first enqueued request triggers the queue consumption after `batchInterval` milliseconds.
if (isFirstEnqueuedRequest || _this.batchDebounce) {
_this.scheduleQueueConsumption(key);
}
// When amount of requests reaches `batchMax`, trigger the queue consumption without waiting on the `batchInterval`.
if (batch.size === _this.batchMax) {
_this.consumeQueue(key);
}
return function () {
var _a;
// If this is last subscriber for this request, remove request from queue
if (requestCopy.subscribers.delete(observer) &&
requestCopy.subscribers.size < 1) {
// If this is last request from queue, remove queue entirely
if (batch.delete(requestCopy) && batch.size < 1) {
_this.consumeQueue(key);
// If queue was in flight, cancel it
(_a = batch.subscription) === null || _a === void 0 ? void 0 : _a.unsubscribe();
}
}
};
});
}
return requestCopy.observable;
};
// Consumes the queue.
// Returns a list of promises (one for each query).
OperationBatcher.prototype.consumeQueue = function (key) {
if (key === void 0) { key = ""; }
var batch = this.batchesByKey.get(key);
// Delete this batch and process it below.
this.batchesByKey.delete(key);
if (!batch || !batch.size) {
// No requests to be processed.
return;
}
var operations = [];
var forwards = [];
var observables = [];
var nexts = [];
var errors = [];
var completes = [];
// Even though batch is a Set, it preserves the order of first insertion
// when iterating (per ECMAScript specification), so these requests will be
// handled in the order they were enqueued (minus any deleted ones).
batch.forEach(function (request) {
operations.push(request.operation);
forwards.push(request.forward);
observables.push(request.observable);
nexts.push(request.next);
errors.push(request.error);
completes.push(request.complete);
});
var batchedObservable = this.batchHandler(operations, forwards) || Observable.of();
var onError = function (error) {
//each callback list in batch
errors.forEach(function (rejecters) {
if (rejecters) {
//each subscriber to request
rejecters.forEach(function (e) { return e(error); });
}
});
};
batch.subscription = batchedObservable.subscribe({
next: function (results) {
if (!Array.isArray(results)) {
results = [results];
}
if (nexts.length !== results.length) {
var error = new Error("server returned results with length ".concat(results.length, ", expected length of ").concat(nexts.length));
error.result = results;
return onError(error);
}
results.forEach(function (result, index) {
if (nexts[index]) {
nexts[index].forEach(function (next) { return next(result); });
}
});
},
error: onError,
complete: function () {
completes.forEach(function (complete) {
if (complete) {
//each subscriber to request
complete.forEach(function (c) { return c(); });
}
});
},
});
return observables;
};
OperationBatcher.prototype.scheduleQueueConsumption = function (key) {
var _this = this;
clearTimeout(this.scheduledBatchTimerByKey.get(key));
this.scheduledBatchTimerByKey.set(key, setTimeout(function () {
_this.consumeQueue(key);
_this.scheduledBatchTimerByKey.delete(key);
}, this.batchInterval));
};
return OperationBatcher;
}());
export { OperationBatcher };
//# sourceMappingURL=batching.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export * from "./batchLink.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,2 @@
export * from "./batchLink.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/link/batch/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC","sourcesContent":["export * from \"./batchLink.js\";\n"]}

View File

@@ -0,0 +1,8 @@
{
"name": "@apollo/client/link/batch",
"type": "module",
"main": "batch.cjs",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false
}

View File

@@ -0,0 +1,38 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var core = require('../core');
var utilities = require('../../utilities');
function setContext(setter) {
return new core.ApolloLink(function (operation, forward) {
var request = tslib.__rest(operation, []);
return new utilities.Observable(function (observer) {
var handle;
var closed = false;
Promise.resolve(request)
.then(function (req) { return setter(req, operation.getContext()); })
.then(operation.setContext)
.then(function () {
if (closed)
return;
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
return function () {
closed = true;
if (handle)
handle.unsubscribe();
};
});
});
}
exports.setContext = setContext;
//# sourceMappingURL=context.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"context.cjs","sources":["index.js"],"sourcesContent":["import { __rest } from \"tslib\";\nimport { ApolloLink } from \"../core/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nexport function setContext(setter) {\n return new ApolloLink(function (operation, forward) {\n var request = __rest(operation, []);\n return new Observable(function (observer) {\n var handle;\n var closed = false;\n Promise.resolve(request)\n .then(function (req) { return setter(req, operation.getContext()); })\n .then(operation.setContext)\n .then(function () {\n // if the observer is already closed, no need to subscribe.\n if (closed)\n return;\n handle = forward(operation).subscribe({\n next: observer.next.bind(observer),\n error: observer.error.bind(observer),\n complete: observer.complete.bind(observer),\n });\n })\n .catch(observer.error.bind(observer));\n return function () {\n closed = true;\n if (handle)\n handle.unsubscribe();\n };\n });\n });\n}\n//# sourceMappingURL=index.js.map"],"names":["ApolloLink","__rest","Observable"],"mappings":";;;;;;;;AAGO,SAAS,UAAU,CAAC,MAAM,EAAE;AACnC,IAAI,OAAO,IAAIA,eAAU,CAAC,UAAU,SAAS,EAAE,OAAO,EAAE;AACxD,QAAQ,IAAI,OAAO,GAAGC,YAAM,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;AAC5C,QAAQ,OAAO,IAAIC,oBAAU,CAAC,UAAU,QAAQ,EAAE;AAClD,YAAY,IAAI,MAAM,CAAC;AACvB,YAAY,IAAI,MAAM,GAAG,KAAK,CAAC;AAC/B,YAAY,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC;AACpC,iBAAiB,IAAI,CAAC,UAAU,GAAG,EAAE,EAAE,OAAO,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,CAAC;AACrF,iBAAiB,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC;AAC3C,iBAAiB,IAAI,CAAC,YAAY;AAElC,gBAAgB,IAAI,MAAM;AAC1B,oBAAoB,OAAO;AAC3B,gBAAgB,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC;AACtD,oBAAoB,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC;AACtD,oBAAoB,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;AACxD,oBAAoB,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC;AAC9D,iBAAiB,CAAC,CAAC;AACnB,aAAa,CAAC;AACd,iBAAiB,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;AACtD,YAAY,OAAO,YAAY;AAC/B,gBAAgB,MAAM,GAAG,IAAI,CAAC;AAC9B,gBAAgB,IAAI,MAAM;AAC1B,oBAAoB,MAAM,CAAC,WAAW,EAAE,CAAC;AACzC,aAAa,CAAC;AACd,SAAS,CAAC,CAAC;AACX,KAAK,CAAC,CAAC;AACP;;;;"}

View File

@@ -0,0 +1,38 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var core = require('../core');
var utilities = require('../../utilities');
function setContext(setter) {
return new core.ApolloLink(function (operation, forward) {
var request = tslib.__rest(operation, []);
return new utilities.Observable(function (observer) {
var handle;
var closed = false;
Promise.resolve(request)
.then(function (req) { return setter(req, operation.getContext()); })
.then(operation.setContext)
.then(function () {
if (closed)
return;
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
return function () {
closed = true;
if (handle)
handle.unsubscribe();
};
});
});
}
exports.setContext = setContext;
//# sourceMappingURL=context.cjs.map

View File

@@ -0,0 +1,6 @@
import type { GraphQLRequest } from "../core/index.js";
import { ApolloLink } from "../core/index.js";
import type { DefaultContext } from "../../core/index.js";
export type ContextSetter = (operation: GraphQLRequest, prevContext: DefaultContext) => Promise<DefaultContext> | DefaultContext;
export declare function setContext(setter: ContextSetter): ApolloLink;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,32 @@
import { __rest } from "tslib";
import { ApolloLink } from "../core/index.js";
import { Observable } from "../../utilities/index.js";
export function setContext(setter) {
return new ApolloLink(function (operation, forward) {
var request = __rest(operation, []);
return new Observable(function (observer) {
var handle;
var closed = false;
Promise.resolve(request)
.then(function (req) { return setter(req, operation.getContext()); })
.then(operation.setContext)
.then(function () {
// if the observer is already closed, no need to subscribe.
if (closed)
return;
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
return function () {
closed = true;
if (handle)
handle.unsubscribe();
};
});
});
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/link/context/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAQtD,MAAM,UAAU,UAAU,CAAC,MAAqB;IAC9C,OAAO,IAAI,UAAU,CAAC,UAAC,SAAoB,EAAE,OAAiB;QAC5D,IAAW,OAAO,UAAK,SAAS,EAA1B,EAAc,CAAY,CAAC;QAEjC,OAAO,IAAI,UAAU,CAAC,UAAC,QAAQ;YAC7B,IAAI,MAA8B,CAAC;YACnC,IAAI,MAAM,GAAG,KAAK,CAAC;YACnB,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC;iBACrB,IAAI,CAAC,UAAC,GAAG,IAAK,OAAA,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,UAAU,EAAE,CAAC,EAAnC,CAAmC,CAAC;iBAClD,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC;iBAC1B,IAAI,CAAC;gBACJ,2DAA2D;gBAC3D,IAAI,MAAM;oBAAE,OAAO;gBACnB,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC;oBACpC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC;oBAClC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC;oBACpC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC;iBAC3C,CAAC,CAAC;YACL,CAAC,CAAC;iBACD,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;YAExC,OAAO;gBACL,MAAM,GAAG,IAAI,CAAC;gBACd,IAAI,MAAM;oBAAE,MAAM,CAAC,WAAW,EAAE,CAAC;YACnC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Operation, GraphQLRequest, NextLink } from \"../core/index.js\";\nimport { ApolloLink } from \"../core/index.js\";\nimport type { ObservableSubscription } from \"../../utilities/index.js\";\nimport { Observable } from \"../../utilities/index.js\";\nimport type { DefaultContext } from \"../../core/index.js\";\n\nexport type ContextSetter = (\n operation: GraphQLRequest,\n prevContext: DefaultContext\n) => Promise<DefaultContext> | DefaultContext;\n\nexport function setContext(setter: ContextSetter): ApolloLink {\n return new ApolloLink((operation: Operation, forward: NextLink) => {\n const { ...request } = operation;\n\n return new Observable((observer) => {\n let handle: ObservableSubscription;\n let closed = false;\n Promise.resolve(request)\n .then((req) => setter(req, operation.getContext()))\n .then(operation.setContext)\n .then(() => {\n // if the observer is already closed, no need to subscribe.\n if (closed) return;\n handle = forward(operation).subscribe({\n next: observer.next.bind(observer),\n error: observer.error.bind(observer),\n complete: observer.complete.bind(observer),\n });\n })\n .catch(observer.error.bind(observer));\n\n return () => {\n closed = true;\n if (handle) handle.unsubscribe();\n };\n });\n });\n}\n"]}

View File

@@ -0,0 +1,8 @@
{
"name": "@apollo/client/link/context",
"type": "module",
"main": "context.cjs",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false
}

View File

@@ -0,0 +1,32 @@
import type { Observer } from "../../utilities/index.js";
import { Observable } from "../../utilities/index.js";
import type { NextLink, Operation, RequestHandler, FetchResult, GraphQLRequest } from "./types.js";
export declare class ApolloLink {
static empty(): ApolloLink;
static from(links: (ApolloLink | RequestHandler)[]): ApolloLink;
static split(test: (op: Operation) => boolean, left: ApolloLink | RequestHandler, right?: ApolloLink | RequestHandler): ApolloLink;
static execute(link: ApolloLink, operation: GraphQLRequest): Observable<FetchResult>;
static concat(first: ApolloLink | RequestHandler, second: ApolloLink | RequestHandler): ApolloLink;
constructor(request?: RequestHandler);
split(test: (op: Operation) => boolean, left: ApolloLink | RequestHandler, right?: ApolloLink | RequestHandler): ApolloLink;
concat(next: ApolloLink | RequestHandler): ApolloLink;
request(operation: Operation, forward?: NextLink): Observable<FetchResult> | null;
protected onError(error: any, observer?: Observer<FetchResult>): false | void;
setOnError(fn: ApolloLink["onError"]): this;
/**
* @internal
* Used to iterate through all links that are concatenations or `split` links.
*/
readonly left?: ApolloLink;
/**
* @internal
* Used to iterate through all links that are concatenations or `split` links.
*/
readonly right?: ApolloLink;
/**
* @internal
* Can be provided by a link that has an internal cache to report it's memory details.
*/
getMemoryInternals?: () => unknown;
}
//# sourceMappingURL=ApolloLink.d.ts.map

View File

@@ -0,0 +1,101 @@
import { newInvariantError, invariant } from "../../utilities/globals/index.js";
import { Observable } from "../../utilities/index.js";
import { validateOperation, createOperation, transformOperation, } from "../utils/index.js";
function passthrough(op, forward) {
return (forward ? forward(op) : Observable.of());
}
function toLink(handler) {
return typeof handler === "function" ? new ApolloLink(handler) : handler;
}
function isTerminating(link) {
return link.request.length <= 1;
}
var ApolloLink = /** @class */ (function () {
function ApolloLink(request) {
if (request)
this.request = request;
}
ApolloLink.empty = function () {
return new ApolloLink(function () { return Observable.of(); });
};
ApolloLink.from = function (links) {
if (links.length === 0)
return ApolloLink.empty();
return links.map(toLink).reduce(function (x, y) { return x.concat(y); });
};
ApolloLink.split = function (test, left, right) {
var leftLink = toLink(left);
var rightLink = toLink(right || new ApolloLink(passthrough));
var ret;
if (isTerminating(leftLink) && isTerminating(rightLink)) {
ret = new ApolloLink(function (operation) {
return test(operation) ?
leftLink.request(operation) || Observable.of()
: rightLink.request(operation) || Observable.of();
});
}
else {
ret = new ApolloLink(function (operation, forward) {
return test(operation) ?
leftLink.request(operation, forward) || Observable.of()
: rightLink.request(operation, forward) || Observable.of();
});
}
return Object.assign(ret, { left: leftLink, right: rightLink });
};
ApolloLink.execute = function (link, operation) {
return (link.request(createOperation(operation.context, transformOperation(validateOperation(operation)))) || Observable.of());
};
ApolloLink.concat = function (first, second) {
var firstLink = toLink(first);
if (isTerminating(firstLink)) {
globalThis.__DEV__ !== false && invariant.warn(35, firstLink);
return firstLink;
}
var nextLink = toLink(second);
var ret;
if (isTerminating(nextLink)) {
ret = new ApolloLink(function (operation) {
return firstLink.request(operation, function (op) { return nextLink.request(op) || Observable.of(); }) || Observable.of();
});
}
else {
ret = new ApolloLink(function (operation, forward) {
return (firstLink.request(operation, function (op) {
return nextLink.request(op, forward) || Observable.of();
}) || Observable.of());
});
}
return Object.assign(ret, { left: firstLink, right: nextLink });
};
ApolloLink.prototype.split = function (test, left, right) {
return this.concat(ApolloLink.split(test, left, right || new ApolloLink(passthrough)));
};
ApolloLink.prototype.concat = function (next) {
return ApolloLink.concat(this, next);
};
ApolloLink.prototype.request = function (operation, forward) {
throw newInvariantError(36);
};
ApolloLink.prototype.onError = function (error, observer) {
if (observer && observer.error) {
observer.error(error);
// Returning false indicates that observer.error does not need to be
// called again, since it was already called (on the previous line).
// Calling observer.error again would not cause any real problems,
// since only the first call matters, but custom onError functions
// might have other reasons for wanting to prevent the default
// behavior by returning false.
return false;
}
// Throw errors will be passed to observer.error.
throw error;
};
ApolloLink.prototype.setOnError = function (fn) {
this.onError = fn;
return this;
};
return ApolloLink;
}());
export { ApolloLink };
//# sourceMappingURL=ApolloLink.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export declare const concat: typeof ApolloLink.concat;
//# sourceMappingURL=concat.d.ts.map

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export var concat = ApolloLink.concat;
//# sourceMappingURL=concat.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"concat.js","sourceRoot":"","sources":["../../../src/link/core/concat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,MAAM,CAAC,IAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC","sourcesContent":["import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const concat = ApolloLink.concat;\n"]}

View File

@@ -0,0 +1,115 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var globals = require('../../utilities/globals');
var utilities = require('../../utilities');
var utils = require('../utils');
function passthrough(op, forward) {
return (forward ? forward(op) : utilities.Observable.of());
}
function toLink(handler) {
return typeof handler === "function" ? new ApolloLink(handler) : handler;
}
function isTerminating(link) {
return link.request.length <= 1;
}
var ApolloLink = (function () {
function ApolloLink(request) {
if (request)
this.request = request;
}
ApolloLink.empty = function () {
return new ApolloLink(function () { return utilities.Observable.of(); });
};
ApolloLink.from = function (links) {
if (links.length === 0)
return ApolloLink.empty();
return links.map(toLink).reduce(function (x, y) { return x.concat(y); });
};
ApolloLink.split = function (test, left, right) {
var leftLink = toLink(left);
var rightLink = toLink(right || new ApolloLink(passthrough));
var ret;
if (isTerminating(leftLink) && isTerminating(rightLink)) {
ret = new ApolloLink(function (operation) {
return test(operation) ?
leftLink.request(operation) || utilities.Observable.of()
: rightLink.request(operation) || utilities.Observable.of();
});
}
else {
ret = new ApolloLink(function (operation, forward) {
return test(operation) ?
leftLink.request(operation, forward) || utilities.Observable.of()
: rightLink.request(operation, forward) || utilities.Observable.of();
});
}
return Object.assign(ret, { left: leftLink, right: rightLink });
};
ApolloLink.execute = function (link, operation) {
return (link.request(utils.createOperation(operation.context, utils.transformOperation(utils.validateOperation(operation)))) || utilities.Observable.of());
};
ApolloLink.concat = function (first, second) {
var firstLink = toLink(first);
if (isTerminating(firstLink)) {
globalThis.__DEV__ !== false && globals.invariant.warn(35, firstLink);
return firstLink;
}
var nextLink = toLink(second);
var ret;
if (isTerminating(nextLink)) {
ret = new ApolloLink(function (operation) {
return firstLink.request(operation, function (op) { return nextLink.request(op) || utilities.Observable.of(); }) || utilities.Observable.of();
});
}
else {
ret = new ApolloLink(function (operation, forward) {
return (firstLink.request(operation, function (op) {
return nextLink.request(op, forward) || utilities.Observable.of();
}) || utilities.Observable.of());
});
}
return Object.assign(ret, { left: firstLink, right: nextLink });
};
ApolloLink.prototype.split = function (test, left, right) {
return this.concat(ApolloLink.split(test, left, right || new ApolloLink(passthrough)));
};
ApolloLink.prototype.concat = function (next) {
return ApolloLink.concat(this, next);
};
ApolloLink.prototype.request = function (operation, forward) {
throw globals.newInvariantError(36);
};
ApolloLink.prototype.onError = function (error, observer) {
if (observer && observer.error) {
observer.error(error);
return false;
}
throw error;
};
ApolloLink.prototype.setOnError = function (fn) {
this.onError = fn;
return this;
};
return ApolloLink;
}());
var empty = ApolloLink.empty;
var from = ApolloLink.from;
var split = ApolloLink.split;
var concat = ApolloLink.concat;
var execute = ApolloLink.execute;
exports.ApolloLink = ApolloLink;
exports.concat = concat;
exports.empty = empty;
exports.execute = execute;
exports.from = from;
exports.split = split;
//# sourceMappingURL=core.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,115 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var globals = require('../../utilities/globals');
var utilities = require('../../utilities');
var utils = require('../utils');
function passthrough(op, forward) {
return (forward ? forward(op) : utilities.Observable.of());
}
function toLink(handler) {
return typeof handler === "function" ? new ApolloLink(handler) : handler;
}
function isTerminating(link) {
return link.request.length <= 1;
}
var ApolloLink = (function () {
function ApolloLink(request) {
if (request)
this.request = request;
}
ApolloLink.empty = function () {
return new ApolloLink(function () { return utilities.Observable.of(); });
};
ApolloLink.from = function (links) {
if (links.length === 0)
return ApolloLink.empty();
return links.map(toLink).reduce(function (x, y) { return x.concat(y); });
};
ApolloLink.split = function (test, left, right) {
var leftLink = toLink(left);
var rightLink = toLink(right || new ApolloLink(passthrough));
var ret;
if (isTerminating(leftLink) && isTerminating(rightLink)) {
ret = new ApolloLink(function (operation) {
return test(operation) ?
leftLink.request(operation) || utilities.Observable.of()
: rightLink.request(operation) || utilities.Observable.of();
});
}
else {
ret = new ApolloLink(function (operation, forward) {
return test(operation) ?
leftLink.request(operation, forward) || utilities.Observable.of()
: rightLink.request(operation, forward) || utilities.Observable.of();
});
}
return Object.assign(ret, { left: leftLink, right: rightLink });
};
ApolloLink.execute = function (link, operation) {
return (link.request(utils.createOperation(operation.context, utils.transformOperation(utils.validateOperation(operation)))) || utilities.Observable.of());
};
ApolloLink.concat = function (first, second) {
var firstLink = toLink(first);
if (isTerminating(firstLink)) {
globalThis.__DEV__ !== false && globals.invariant.warn(35, firstLink);
return firstLink;
}
var nextLink = toLink(second);
var ret;
if (isTerminating(nextLink)) {
ret = new ApolloLink(function (operation) {
return firstLink.request(operation, function (op) { return nextLink.request(op) || utilities.Observable.of(); }) || utilities.Observable.of();
});
}
else {
ret = new ApolloLink(function (operation, forward) {
return (firstLink.request(operation, function (op) {
return nextLink.request(op, forward) || utilities.Observable.of();
}) || utilities.Observable.of());
});
}
return Object.assign(ret, { left: firstLink, right: nextLink });
};
ApolloLink.prototype.split = function (test, left, right) {
return this.concat(ApolloLink.split(test, left, right || new ApolloLink(passthrough)));
};
ApolloLink.prototype.concat = function (next) {
return ApolloLink.concat(this, next);
};
ApolloLink.prototype.request = function (operation, forward) {
throw globals.newInvariantError(36);
};
ApolloLink.prototype.onError = function (error, observer) {
if (observer && observer.error) {
observer.error(error);
return false;
}
throw error;
};
ApolloLink.prototype.setOnError = function (fn) {
this.onError = fn;
return this;
};
return ApolloLink;
}());
var empty = ApolloLink.empty;
var from = ApolloLink.from;
var split = ApolloLink.split;
var concat = ApolloLink.concat;
var execute = ApolloLink.execute;
exports.ApolloLink = ApolloLink;
exports.concat = concat;
exports.empty = empty;
exports.execute = execute;
exports.from = from;
exports.split = split;
//# sourceMappingURL=core.cjs.map

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export declare const empty: typeof ApolloLink.empty;
//# sourceMappingURL=empty.d.ts.map

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export var empty = ApolloLink.empty;
//# sourceMappingURL=empty.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"empty.js","sourceRoot":"","sources":["../../../src/link/core/empty.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,MAAM,CAAC,IAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC","sourcesContent":["import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const empty = ApolloLink.empty;\n"]}

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export declare const execute: typeof ApolloLink.execute;
//# sourceMappingURL=execute.d.ts.map

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export var execute = ApolloLink.execute;
//# sourceMappingURL=execute.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/link/core/execute.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,MAAM,CAAC,IAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC","sourcesContent":["import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const execute = ApolloLink.execute;\n"]}

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export declare const from: typeof ApolloLink.from;
//# sourceMappingURL=from.d.ts.map

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export var from = ApolloLink.from;
//# sourceMappingURL=from.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"from.js","sourceRoot":"","sources":["../../../src/link/core/from.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,MAAM,CAAC,IAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC","sourcesContent":["import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const from = ApolloLink.from;\n"]}

View File

@@ -0,0 +1,9 @@
import "../../utilities/globals/index.js";
export { empty } from "./empty.js";
export { from } from "./from.js";
export { split } from "./split.js";
export { concat } from "./concat.js";
export { execute } from "./execute.js";
export { ApolloLink } from "./ApolloLink.js";
export * from "./types.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,9 @@
import "../../utilities/globals/index.js";
export { empty } from "./empty.js";
export { from } from "./from.js";
export { split } from "./split.js";
export { concat } from "./concat.js";
export { execute } from "./execute.js";
export { ApolloLink } from "./ApolloLink.js";
export * from "./types.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/link/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,kCAAkC,CAAC;AAE1C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,cAAc,YAAY,CAAC","sourcesContent":["import \"../../utilities/globals/index.js\";\n\nexport { empty } from \"./empty.js\";\nexport { from } from \"./from.js\";\nexport { split } from \"./split.js\";\nexport { concat } from \"./concat.js\";\nexport { execute } from \"./execute.js\";\nexport { ApolloLink } from \"./ApolloLink.js\";\n\nexport * from \"./types.js\";\n"]}

View File

@@ -0,0 +1,8 @@
{
"name": "@apollo/client/link/core",
"type": "module",
"main": "core.cjs",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false
}

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export declare const split: typeof ApolloLink.split;
//# sourceMappingURL=split.d.ts.map

View File

@@ -0,0 +1,3 @@
import { ApolloLink } from "./ApolloLink.js";
export var split = ApolloLink.split;
//# sourceMappingURL=split.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"split.js","sourceRoot":"","sources":["../../../src/link/core/split.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,MAAM,CAAC,IAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC","sourcesContent":["import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const split = ApolloLink.split;\n"]}

View File

@@ -0,0 +1,56 @@
import type { ExecutionResult, GraphQLError } from "graphql";
import type { DocumentNode } from "graphql";
import type { DefaultContext } from "../../core/index.js";
export type { DocumentNode };
import type { Observable } from "../../utilities/index.js";
export type Path = ReadonlyArray<string | number>;
interface ExecutionPatchResultBase {
hasNext?: boolean;
}
export interface ExecutionPatchInitialResult<TData = Record<string, any>, TExtensions = Record<string, any>> extends ExecutionPatchResultBase {
data: TData | null | undefined;
incremental?: never;
errors?: ReadonlyArray<GraphQLError>;
extensions?: TExtensions;
}
export interface IncrementalPayload<TData, TExtensions> {
data: TData | null;
label?: string;
path: Path;
errors?: ReadonlyArray<GraphQLError>;
extensions?: TExtensions;
}
export interface ExecutionPatchIncrementalResult<TData = Record<string, any>, TExtensions = Record<string, any>> extends ExecutionPatchResultBase {
incremental?: IncrementalPayload<TData, TExtensions>[];
data?: never;
errors?: never;
extensions?: never;
}
export interface ApolloPayloadResult<TData = Record<string, any>, TExtensions = Record<string, any>> {
payload: SingleExecutionResult | ExecutionPatchResult | null;
errors?: ReadonlyArray<Error | string>;
}
export type ExecutionPatchResult<TData = Record<string, any>, TExtensions = Record<string, any>> = ExecutionPatchInitialResult<TData, TExtensions> | ExecutionPatchIncrementalResult<TData, TExtensions>;
export interface GraphQLRequest<TVariables = Record<string, any>> {
query: DocumentNode;
variables?: TVariables;
operationName?: string;
context?: DefaultContext;
extensions?: Record<string, any>;
}
export interface Operation {
query: DocumentNode;
variables: Record<string, any>;
operationName: string;
extensions: Record<string, any>;
setContext: (context: DefaultContext) => DefaultContext;
getContext: () => DefaultContext;
}
export interface SingleExecutionResult<TData = Record<string, any>, TContext = DefaultContext, TExtensions = Record<string, any>> extends ExecutionResult<TData, TExtensions> {
data?: TData | null;
context?: TContext;
}
export type FetchResult<TData = Record<string, any>, TContext = Record<string, any>, TExtensions = Record<string, any>> = SingleExecutionResult<TData, TContext, TExtensions> | ExecutionPatchResult<TData, TExtensions>;
export type NextLink = (operation: Operation) => Observable<FetchResult>;
export type RequestHandler = (operation: Operation, forward: NextLink) => Observable<FetchResult> | null;
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/link/core/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ExecutionResult, GraphQLError } from \"graphql\";\nimport type { DocumentNode } from \"graphql\";\nimport type { DefaultContext } from \"../../core/index.js\";\nexport type { DocumentNode };\n\nimport type { Observable } from \"../../utilities/index.js\";\n\nexport type Path = ReadonlyArray<string | number>;\n\ninterface ExecutionPatchResultBase {\n hasNext?: boolean;\n}\n\nexport interface ExecutionPatchInitialResult<\n TData = Record<string, any>,\n TExtensions = Record<string, any>,\n> extends ExecutionPatchResultBase {\n // if data is present, incremental is not\n data: TData | null | undefined;\n incremental?: never;\n errors?: ReadonlyArray<GraphQLError>;\n extensions?: TExtensions;\n}\n\nexport interface IncrementalPayload<TData, TExtensions> {\n // data and path must both be present\n // https://github.com/graphql/graphql-spec/pull/742/files#diff-98d0cd153b72b63c417ad4238e8cc0d3385691ccbde7f7674bc0d2a718b896ecR288-R293\n data: TData | null;\n label?: string;\n path: Path;\n errors?: ReadonlyArray<GraphQLError>;\n extensions?: TExtensions;\n}\n\nexport interface ExecutionPatchIncrementalResult<\n TData = Record<string, any>,\n TExtensions = Record<string, any>,\n> extends ExecutionPatchResultBase {\n // the reverse is also true: if incremental is present,\n // data (and errors and extensions) are not\n incremental?: IncrementalPayload<TData, TExtensions>[];\n data?: never;\n // Errors only exist for chunks, not at the top level\n // https://github.com/robrichard/defer-stream-wg/discussions/50#discussioncomment-3466739\n errors?: never;\n extensions?: never;\n}\n\nexport interface ApolloPayloadResult<\n TData = Record<string, any>,\n TExtensions = Record<string, any>,\n> {\n payload: SingleExecutionResult | ExecutionPatchResult | null;\n // Transport layer errors (as distinct from GraphQL or NetworkErrors),\n // these are fatal errors that will include done: true.\n errors?: ReadonlyArray<Error | string>;\n}\n\nexport type ExecutionPatchResult<\n TData = Record<string, any>,\n TExtensions = Record<string, any>,\n> =\n | ExecutionPatchInitialResult<TData, TExtensions>\n | ExecutionPatchIncrementalResult<TData, TExtensions>;\n\nexport interface GraphQLRequest<TVariables = Record<string, any>> {\n query: DocumentNode;\n variables?: TVariables;\n operationName?: string;\n context?: DefaultContext;\n extensions?: Record<string, any>;\n}\n\nexport interface Operation {\n query: DocumentNode;\n variables: Record<string, any>;\n operationName: string;\n extensions: Record<string, any>;\n setContext: (context: DefaultContext) => DefaultContext;\n getContext: () => DefaultContext;\n}\n\nexport interface SingleExecutionResult<\n TData = Record<string, any>,\n TContext = DefaultContext,\n TExtensions = Record<string, any>,\n> extends ExecutionResult<TData, TExtensions> {\n // data might be undefined if errorPolicy was set to 'ignore'\n data?: TData | null;\n context?: TContext;\n}\n\nexport type FetchResult<\n TData = Record<string, any>,\n TContext = Record<string, any>,\n TExtensions = Record<string, any>,\n> =\n | SingleExecutionResult<TData, TContext, TExtensions>\n | ExecutionPatchResult<TData, TExtensions>;\n\nexport type NextLink = (operation: Operation) => Observable<FetchResult>;\n\nexport type RequestHandler = (\n operation: Operation,\n forward: NextLink\n) => Observable<FetchResult> | null;\n"]}

View File

@@ -0,0 +1,90 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var utilities = require('../../utilities');
var core = require('../core');
function onError(errorHandler) {
return new core.ApolloLink(function (operation, forward) {
return new utilities.Observable(function (observer) {
var sub;
var retriedSub;
var retriedResult;
try {
sub = forward(operation).subscribe({
next: function (result) {
if (result.errors) {
retriedResult = errorHandler({
graphQLErrors: result.errors,
response: result,
operation: operation,
forward: forward,
});
if (retriedResult) {
retriedSub = retriedResult.subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
return;
}
}
observer.next(result);
},
error: function (networkError) {
retriedResult = errorHandler({
operation: operation,
networkError: networkError,
graphQLErrors: networkError &&
networkError.result &&
networkError.result.errors,
forward: forward,
});
if (retriedResult) {
retriedSub = retriedResult.subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
return;
}
observer.error(networkError);
},
complete: function () {
if (!retriedResult) {
observer.complete.bind(observer)();
}
},
});
}
catch (e) {
errorHandler({ networkError: e, operation: operation, forward: forward });
observer.error(e);
}
return function () {
if (sub)
sub.unsubscribe();
if (retriedSub)
sub.unsubscribe();
};
});
});
}
var ErrorLink = (function (_super) {
tslib.__extends(ErrorLink, _super);
function ErrorLink(errorHandler) {
var _this = _super.call(this) || this;
_this.link = onError(errorHandler);
return _this;
}
ErrorLink.prototype.request = function (operation, forward) {
return this.link.request(operation, forward);
};
return ErrorLink;
}(core.ApolloLink));
exports.ErrorLink = ErrorLink;
exports.onError = onError;
//# sourceMappingURL=error.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,90 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib = require('tslib');
var utilities = require('../../utilities');
var core = require('../core');
function onError(errorHandler) {
return new core.ApolloLink(function (operation, forward) {
return new utilities.Observable(function (observer) {
var sub;
var retriedSub;
var retriedResult;
try {
sub = forward(operation).subscribe({
next: function (result) {
if (result.errors) {
retriedResult = errorHandler({
graphQLErrors: result.errors,
response: result,
operation: operation,
forward: forward,
});
if (retriedResult) {
retriedSub = retriedResult.subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
return;
}
}
observer.next(result);
},
error: function (networkError) {
retriedResult = errorHandler({
operation: operation,
networkError: networkError,
graphQLErrors: networkError &&
networkError.result &&
networkError.result.errors,
forward: forward,
});
if (retriedResult) {
retriedSub = retriedResult.subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
return;
}
observer.error(networkError);
},
complete: function () {
if (!retriedResult) {
observer.complete.bind(observer)();
}
},
});
}
catch (e) {
errorHandler({ networkError: e, operation: operation, forward: forward });
observer.error(e);
}
return function () {
if (sub)
sub.unsubscribe();
if (retriedSub)
sub.unsubscribe();
};
});
});
}
var ErrorLink = (function (_super) {
tslib.__extends(ErrorLink, _super);
function ErrorLink(errorHandler) {
var _this = _super.call(this) || this;
_this.link = onError(errorHandler);
return _this;
}
ErrorLink.prototype.request = function (operation, forward) {
return this.link.request(operation, forward);
};
return ErrorLink;
}(core.ApolloLink));
exports.ErrorLink = ErrorLink;
exports.onError = onError;
//# sourceMappingURL=error.cjs.map

View File

@@ -0,0 +1,28 @@
import type { ExecutionResult } from "graphql";
import type { NetworkError, GraphQLErrors } from "../../errors/index.js";
import { Observable } from "../../utilities/index.js";
import type { Operation, FetchResult, NextLink } from "../core/index.js";
import { ApolloLink } from "../core/index.js";
export interface ErrorResponse {
graphQLErrors?: GraphQLErrors;
networkError?: NetworkError;
response?: ExecutionResult;
operation: Operation;
forward: NextLink;
}
export declare namespace ErrorLink {
/**
* Callback to be triggered when an error occurs within the link stack.
*/
interface ErrorHandler {
(error: ErrorResponse): Observable<FetchResult> | void;
}
}
export import ErrorHandler = ErrorLink.ErrorHandler;
export declare function onError(errorHandler: ErrorHandler): ApolloLink;
export declare class ErrorLink extends ApolloLink {
private link;
constructor(errorHandler: ErrorLink.ErrorHandler);
request(operation: Operation, forward: NextLink): Observable<FetchResult> | null;
}
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,86 @@
import { __extends } from "tslib";
import { Observable } from "../../utilities/index.js";
import { ApolloLink } from "../core/index.js";
export function onError(errorHandler) {
return new ApolloLink(function (operation, forward) {
return new Observable(function (observer) {
var sub;
var retriedSub;
var retriedResult;
try {
sub = forward(operation).subscribe({
next: function (result) {
if (result.errors) {
retriedResult = errorHandler({
graphQLErrors: result.errors,
response: result,
operation: operation,
forward: forward,
});
if (retriedResult) {
retriedSub = retriedResult.subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
return;
}
}
observer.next(result);
},
error: function (networkError) {
retriedResult = errorHandler({
operation: operation,
networkError: networkError,
//Network errors can return GraphQL errors on for example a 403
graphQLErrors: networkError &&
networkError.result &&
networkError.result.errors,
forward: forward,
});
if (retriedResult) {
retriedSub = retriedResult.subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
return;
}
observer.error(networkError);
},
complete: function () {
// disable the previous sub from calling complete on observable
// if retry is in flight.
if (!retriedResult) {
observer.complete.bind(observer)();
}
},
});
}
catch (e) {
errorHandler({ networkError: e, operation: operation, forward: forward });
observer.error(e);
}
return function () {
if (sub)
sub.unsubscribe();
if (retriedSub)
sub.unsubscribe();
};
});
});
}
var ErrorLink = /** @class */ (function (_super) {
__extends(ErrorLink, _super);
function ErrorLink(errorHandler) {
var _this = _super.call(this) || this;
_this.link = onError(errorHandler);
return _this;
}
ErrorLink.prototype.request = function (operation, forward) {
return this.link.request(operation, forward);
};
return ErrorLink;
}(ApolloLink));
export { ErrorLink };
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
{
"name": "@apollo/client/link/error",
"type": "module",
"main": "error.cjs",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false
}

View File

@@ -0,0 +1,7 @@
import { ApolloLink } from "../core/index.js";
import type { HttpOptions } from "./selectHttpOptionsAndBody.js";
export declare class HttpLink extends ApolloLink {
options: HttpOptions;
constructor(options?: HttpOptions);
}
//# sourceMappingURL=HttpLink.d.ts.map

View File

@@ -0,0 +1,15 @@
import { __extends } from "tslib";
import { ApolloLink } from "../core/index.js";
import { createHttpLink } from "./createHttpLink.js";
var HttpLink = /** @class */ (function (_super) {
__extends(HttpLink, _super);
function HttpLink(options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, createHttpLink(options).request) || this;
_this.options = options;
return _this;
}
return HttpLink;
}(ApolloLink));
export { HttpLink };
//# sourceMappingURL=HttpLink.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"HttpLink.js","sourceRoot":"","sources":["../../../src/link/http/HttpLink.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD;IAA8B,4BAAU;IACtC,kBAAmB,OAAyB;QAAzB,wBAAA,EAAA,YAAyB;QAC1C,YAAA,MAAK,YAAC,cAAc,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,SAAC;QADtB,aAAO,GAAP,OAAO,CAAkB;;IAE5C,CAAC;IACH,eAAC;AAAD,CAAC,AAJD,CAA8B,UAAU,GAIvC","sourcesContent":["import { ApolloLink } from \"../core/index.js\";\nimport type { HttpOptions } from \"./selectHttpOptionsAndBody.js\";\nimport { createHttpLink } from \"./createHttpLink.js\";\n\nexport class HttpLink extends ApolloLink {\n constructor(public options: HttpOptions = {}) {\n super(createHttpLink(options).request);\n }\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare const checkFetcher: (fetcher: typeof fetch | undefined) => void;
//# sourceMappingURL=checkFetcher.d.ts.map

View File

@@ -0,0 +1,7 @@
import { newInvariantError } from "../../utilities/globals/index.js";
export var checkFetcher = function (fetcher) {
if (!fetcher && typeof fetch === "undefined") {
throw newInvariantError(37);
}
};
//# sourceMappingURL=checkFetcher.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"checkFetcher.js","sourceRoot":"","sources":["../../../src/link/http/checkFetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AAErE,MAAM,CAAC,IAAM,YAAY,GAAG,UAAC,OAAiC;IAC5D,IAAI,CAAC,OAAO,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE,CAAC;QAC7C,MAAM,iBAAiB,CAAC,obAWvB,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC","sourcesContent":["import { newInvariantError } from \"../../utilities/globals/index.js\";\n\nexport const checkFetcher = (fetcher: typeof fetch | undefined) => {\n if (!fetcher && typeof fetch === \"undefined\") {\n throw newInvariantError(`\n\"fetch\" has not been found globally and no fetcher has been \\\nconfigured. To fix this, install a fetch package (like \\\nhttps://www.npmjs.com/package/cross-fetch), instantiate the \\\nfetcher, and pass it into your HttpLink constructor. For example:\n\nimport fetch from 'cross-fetch';\nimport { ApolloClient, HttpLink } from '@apollo/client';\nconst client = new ApolloClient({\n link: new HttpLink({ uri: '/graphql', fetch })\n});\n `);\n }\n};\n"]}

View File

@@ -0,0 +1,4 @@
import { ApolloLink } from "../core/index.js";
import type { HttpOptions } from "./selectHttpOptionsAndBody.js";
export declare const createHttpLink: (linkOptions?: HttpOptions) => ApolloLink;
//# sourceMappingURL=createHttpLink.d.ts.map

View File

@@ -0,0 +1,156 @@
import { __assign, __rest } from "tslib";
import { invariant } from "../../utilities/globals/index.js";
import { ApolloLink } from "../core/index.js";
import { Observable, hasDirectives } from "../../utilities/index.js";
import { serializeFetchParameter } from "./serializeFetchParameter.js";
import { selectURI } from "./selectURI.js";
import { handleError, readMultipartBody, parseAndCheckHttpResponse, } from "./parseAndCheckHttpResponse.js";
import { checkFetcher } from "./checkFetcher.js";
import { selectHttpOptionsAndBodyInternal, defaultPrinter, fallbackHttpConfig, } from "./selectHttpOptionsAndBody.js";
import { rewriteURIForGET } from "./rewriteURIForGET.js";
import { fromError, filterOperationVariables } from "../utils/index.js";
import { maybe, getMainDefinition, removeClientSetsFromDocument, } from "../../utilities/index.js";
var backupFetch = maybe(function () { return fetch; });
export var createHttpLink = function (linkOptions) {
if (linkOptions === void 0) { linkOptions = {}; }
var _a = linkOptions.uri, uri = _a === void 0 ? "/graphql" : _a,
// use default global fetch if nothing passed in
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 = __rest(linkOptions, ["uri", "fetch", "print", "includeExtensions", "preserveHeaderCase", "useGETForQueries", "includeUnusedVariables"]);
if (globalThis.__DEV__ !== false) {
// Make sure at least one of preferredFetch, window.fetch, or backupFetch is
// defined, so requests won't fail at runtime.
checkFetcher(preferredFetch || backupFetch);
}
var linkConfig = {
http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
return new ApolloLink(function (operation) {
var chosenURI = selectURI(operation, uri);
var context = operation.getContext();
// `apollographql-client-*` headers are automatically set if a
// `clientAwareness` object is found in the context. These headers are
// set first, followed by the rest of the headers pulled from
// `context.headers`. If desired, `apollographql-client-*` headers set by
// the `clientAwareness` object can be overridden by
// `apollographql-client-*` headers set in `context.headers`.
var clientAwarenessHeaders = {};
if (context.clientAwareness) {
var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
if (name_1) {
clientAwarenessHeaders["apollographql-client-name"] = name_1;
}
if (version) {
clientAwarenessHeaders["apollographql-client-version"] = version;
}
}
var contextHeaders = __assign(__assign({}, clientAwarenessHeaders), context.headers);
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: contextHeaders,
};
if (hasDirectives(["client"], operation.query)) {
var transformedQuery = removeClientSetsFromDocument(operation.query);
if (!transformedQuery) {
return 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`."));
}
operation.query = transformedQuery;
}
//uses fallback, link, and then context to build options
var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;
if (body.variables && !includeUnusedVariables) {
body.variables = filterOperationVariables(body.variables, operation.query);
}
var controller;
if (!options.signal && typeof AbortController !== "undefined") {
controller = new AbortController();
options.signal = controller.signal;
}
// If requested, set method to GET if there are no mutations.
var definitionIsMutation = function (d) {
return d.kind === "OperationDefinition" && d.operation === "mutation";
};
var definitionIsSubscription = function (d) {
return d.kind === "OperationDefinition" && d.operation === "subscription";
};
var isSubscription = definitionIsSubscription(getMainDefinition(operation.query));
// does not match custom directives beginning with @defer
var hasDefer = hasDirectives(["defer"], operation.query);
if (useGETForQueries &&
!operation.query.definitions.some(definitionIsMutation)) {
options.method = "GET";
}
if (hasDefer || isSubscription) {
options.headers = options.headers || {};
var acceptHeader = "multipart/mixed;";
// Omit defer-specific headers if the user attempts to defer a selection
// set on a subscription and log a warning.
if (isSubscription && hasDefer) {
globalThis.__DEV__ !== false && invariant.warn(38);
}
if (isSubscription) {
acceptHeader +=
"boundary=graphql;subscriptionSpec=1.0,application/json";
}
else if (hasDefer) {
acceptHeader += "deferSpec=20220824,application/json";
}
options.headers.accept = acceptHeader;
}
if (options.method === "GET") {
var _c = rewriteURIForGET(chosenURI, body), newURI = _c.newURI, parseError = _c.parseError;
if (parseError) {
return fromError(parseError);
}
chosenURI = newURI;
}
else {
try {
options.body = serializeFetchParameter(body, "Payload");
}
catch (parseError) {
return fromError(parseError);
}
}
return new Observable(function (observer) {
// Prefer linkOptions.fetch (preferredFetch) if provided, and otherwise
// fall back to the *current* global window.fetch function (see issue
// #7832), or (if all else fails) the backupFetch function we saved when
// this module was first evaluated. This last option protects against the
// removal of window.fetch, which is unlikely but not impossible.
var currentFetch = preferredFetch || maybe(function () { return fetch; }) || backupFetch;
var observerNext = observer.next.bind(observer);
currentFetch(chosenURI, options)
.then(function (response) {
var _a;
operation.setContext({ response: response });
var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
return readMultipartBody(response, observerNext);
}
else {
return parseAndCheckHttpResponse(operation)(response).then(observerNext);
}
})
.then(function () {
controller = undefined;
observer.complete();
})
.catch(function (err) {
controller = undefined;
handleError(err, observer);
});
return function () {
// XXX support canceling this request
// https://developers.google.com/web/updates/2017/09/abortable-fetch
if (controller)
controller.abort();
};
});
});
};
//# sourceMappingURL=createHttpLink.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
/**
* @deprecated
* This is not used internally any more and will be removed in
* the next major version of Apollo Client.
*/
export declare const createSignalIfSupported: () => {
controller: boolean;
signal: boolean;
} | {
controller: AbortController;
signal: AbortSignal;
};
//# sourceMappingURL=createSignalIfSupported.d.ts.map

View File

@@ -0,0 +1,13 @@
/**
* @deprecated
* This is not used internally any more and will be removed in
* the next major version of Apollo Client.
*/
export var createSignalIfSupported = function () {
if (typeof AbortController === "undefined")
return { controller: false, signal: false };
var controller = new AbortController();
var signal = controller.signal;
return { controller: controller, signal: signal };
};
//# sourceMappingURL=createSignalIfSupported.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"createSignalIfSupported.js","sourceRoot":"","sources":["../../../src/link/http/createSignalIfSupported.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,IAAM,uBAAuB,GAAG;IACrC,IAAI,OAAO,eAAe,KAAK,WAAW;QACxC,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IAE9C,IAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,IAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;IACjC,OAAO,EAAE,UAAU,YAAA,EAAE,MAAM,QAAA,EAAE,CAAC;AAChC,CAAC,CAAC","sourcesContent":["/**\n * @deprecated\n * This is not used internally any more and will be removed in\n * the next major version of Apollo Client.\n */\nexport const createSignalIfSupported = () => {\n if (typeof AbortController === \"undefined\")\n return { controller: false, signal: false };\n\n const controller = new AbortController();\n const signal = controller.signal;\n return { controller, signal };\n};\n"]}

View File

@@ -0,0 +1,631 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var globals = require('../../utilities/globals');
var tslib = require('tslib');
var utilities = require('../../utilities');
var utils = require('../utils');
var errors = require('../../errors');
var core = require('../core');
function asyncIterator(source) {
var _a;
var iterator = source[Symbol.asyncIterator]();
return _a = {
next: function () {
return iterator.next();
}
},
_a[Symbol.asyncIterator] = function () {
return this;
},
_a;
}
function nodeStreamIterator(stream) {
var cleanup = null;
var error = null;
var done = false;
var data = [];
var waiting = [];
function onData(chunk) {
if (error)
return;
if (waiting.length) {
var shiftedArr = waiting.shift();
if (Array.isArray(shiftedArr) && shiftedArr[0]) {
return shiftedArr[0]({ value: chunk, done: false });
}
}
data.push(chunk);
}
function onError(err) {
error = err;
var all = waiting.slice();
all.forEach(function (pair) {
pair[1](err);
});
!cleanup || cleanup();
}
function onEnd() {
done = true;
var all = waiting.slice();
all.forEach(function (pair) {
pair[0]({ value: undefined, done: true });
});
!cleanup || cleanup();
}
cleanup = function () {
cleanup = null;
stream.removeListener("data", onData);
stream.removeListener("error", onError);
stream.removeListener("end", onEnd);
stream.removeListener("finish", onEnd);
stream.removeListener("close", onEnd);
};
stream.on("data", onData);
stream.on("error", onError);
stream.on("end", onEnd);
stream.on("finish", onEnd);
stream.on("close", onEnd);
function getNext() {
return new Promise(function (resolve, reject) {
if (error)
return reject(error);
if (data.length)
return resolve({ value: data.shift(), done: false });
if (done)
return resolve({ value: undefined, done: true });
waiting.push([resolve, reject]);
});
}
var iterator = {
next: function () {
return getNext();
},
};
if (utilities.canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
function promiseIterator(promise) {
var resolved = false;
var iterator = {
next: function () {
if (resolved)
return Promise.resolve({
value: undefined,
done: true,
});
resolved = true;
return new Promise(function (resolve, reject) {
promise
.then(function (value) {
resolve({ value: value, done: false });
})
.catch(reject);
});
},
};
if (utilities.canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
function readerIterator(reader) {
var iterator = {
next: function () {
return reader.read();
},
};
if (utilities.canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
function isNodeResponse(value) {
return !!value.body;
}
function isReadableStream(value) {
return !!value.getReader;
}
function isAsyncIterableIterator(value) {
return !!(utilities.canUseAsyncIteratorSymbol &&
value[Symbol.asyncIterator]);
}
function isStreamableBlob(value) {
return !!value.stream;
}
function isBlob(value) {
return !!value.arrayBuffer;
}
function isNodeReadableStream(value) {
return !!value.pipe;
}
function responseIterator(response) {
var body = response;
if (isNodeResponse(response))
body = response.body;
if (isAsyncIterableIterator(body))
return asyncIterator(body);
if (isReadableStream(body))
return readerIterator(body.getReader());
if (isStreamableBlob(body)) {
return readerIterator(body.stream().getReader());
}
if (isBlob(body))
return promiseIterator(body.arrayBuffer());
if (isNodeReadableStream(body))
return nodeStreamIterator(body);
throw new Error("Unknown body type for responseIterator. Please pass a streamable response.");
}
function isNonNullObject(obj) {
return obj !== null && typeof obj === "object";
}
function isApolloPayloadResult(value) {
return isNonNullObject(value) && "payload" in value;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function readMultipartBody(response, nextValue) {
var _a;
return tslib.__awaiter(this, void 0, void 0, function () {
var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _b, value, done, chunk, searchFrom, bi, message, i, headers, contentType_1, body, result, next;
var _c, _d;
return tslib.__generator(this, function (_e) {
switch (_e.label) {
case 0:
if (TextDecoder === undefined) {
throw new Error("TextDecoder must be defined in the environment: please import a polyfill.");
}
decoder = new TextDecoder("utf-8");
contentType = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
delimiter = "boundary=";
boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter)) ?
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()
: "-";
boundary = "\r\n--".concat(boundaryVal);
buffer = "";
iterator = responseIterator(response);
running = true;
_e.label = 1;
case 1:
if (!running) return [3 , 3];
return [4 , iterator.next()];
case 2:
_b = _e.sent(), value = _b.value, done = _b.done;
chunk = typeof value === "string" ? value : decoder.decode(value);
searchFrom = buffer.length - boundary.length + 1;
running = !done;
buffer += chunk;
bi = buffer.indexOf(boundary, searchFrom);
while (bi > -1) {
message = void 0;
_c = [
buffer.slice(0, bi),
buffer.slice(bi + boundary.length),
], message = _c[0], buffer = _c[1];
i = message.indexOf("\r\n\r\n");
headers = parseHeaders(message.slice(0, i));
contentType_1 = headers["content-type"];
if (contentType_1 &&
contentType_1.toLowerCase().indexOf("application/json") === -1) {
throw new Error("Unsupported patch content type: application/json is required.");
}
body = message.slice(i);
if (body) {
result = parseJsonBody(response, body);
if (Object.keys(result).length > 1 ||
"data" in result ||
"incremental" in result ||
"errors" in result ||
"payload" in result) {
if (isApolloPayloadResult(result)) {
next = {};
if ("payload" in result) {
next = tslib.__assign({}, result.payload);
}
if ("errors" in result) {
next = tslib.__assign(tslib.__assign({}, next), { extensions: tslib.__assign(tslib.__assign({}, ("extensions" in next ? next.extensions : null)), (_d = {}, _d[errors.PROTOCOL_ERRORS_SYMBOL] = result.errors, _d)) });
}
nextValue(next);
}
else {
nextValue(result);
}
}
else if (
Object.keys(result).length === 1 &&
"hasNext" in result &&
!result.hasNext) {
return [2 ];
}
}
bi = buffer.indexOf(boundary);
}
return [3 , 1];
case 3: return [2 ];
}
});
});
}
function parseHeaders(headerText) {
var headersInit = {};
headerText.split("\n").forEach(function (line) {
var i = line.indexOf(":");
if (i > -1) {
var name_1 = line.slice(0, i).trim().toLowerCase();
var value = line.slice(i + 1).trim();
headersInit[name_1] = value;
}
});
return headersInit;
}
function parseJsonBody(response, bodyText) {
if (response.status >= 300) {
var getResult = function () {
try {
return JSON.parse(bodyText);
}
catch (err) {
return bodyText;
}
};
utils.throwServerError(response, getResult(), "Response not successful: Received status code ".concat(response.status));
}
try {
return JSON.parse(bodyText);
}
catch (err) {
var parseError = err;
parseError.name = "ServerParseError";
parseError.response = response;
parseError.statusCode = response.status;
parseError.bodyText = bodyText;
throw parseError;
}
}
function handleError(err, observer) {
if (err.result && err.result.errors && err.result.data) {
observer.next(err.result);
}
observer.error(err);
}
function parseAndCheckHttpResponse(operations) {
return function (response) {
return response
.text()
.then(function (bodyText) { return parseJsonBody(response, bodyText); })
.then(function (result) {
if (!Array.isArray(result) &&
!hasOwnProperty.call(result, "data") &&
!hasOwnProperty.call(result, "errors")) {
utils.throwServerError(response, result, "Server response was missing for query '".concat(Array.isArray(operations) ?
operations.map(function (op) { return op.operationName; })
: operations.operationName, "'."));
}
return result;
});
};
}
var serializeFetchParameter = function (p, label) {
var serialized;
try {
serialized = JSON.stringify(p);
}
catch (e) {
var parseError = globals.newInvariantError(39, label, e.message);
parseError.parseError = e;
throw parseError;
}
return serialized;
};
var defaultHttpOptions = {
includeQuery: true,
includeExtensions: false,
preserveHeaderCase: false,
};
var defaultHeaders = {
accept: "*/*",
"content-type": "application/json",
};
var defaultOptions = {
method: "POST",
};
var fallbackHttpConfig = {
http: defaultHttpOptions,
headers: defaultHeaders,
options: defaultOptions,
};
var defaultPrinter = function (ast, printer) { return printer(ast); };
function selectHttpOptionsAndBody(operation, fallbackConfig) {
var configs = [];
for (var _i = 2; _i < arguments.length; _i++) {
configs[_i - 2] = arguments[_i];
}
configs.unshift(fallbackConfig);
return selectHttpOptionsAndBodyInternal.apply(void 0, tslib.__spreadArray([operation,
defaultPrinter], configs, false));
}
function selectHttpOptionsAndBodyInternal(operation, printer) {
var configs = [];
for (var _i = 2; _i < arguments.length; _i++) {
configs[_i - 2] = arguments[_i];
}
var options = {};
var http = {};
configs.forEach(function (config) {
options = tslib.__assign(tslib.__assign(tslib.__assign({}, options), config.options), { headers: tslib.__assign(tslib.__assign({}, options.headers), config.headers) });
if (config.credentials) {
options.credentials = config.credentials;
}
http = tslib.__assign(tslib.__assign({}, http), config.http);
});
if (options.headers) {
options.headers = removeDuplicateHeaders(options.headers, http.preserveHeaderCase);
}
var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;
var body = { operationName: operationName, variables: variables };
if (http.includeExtensions)
body.extensions = extensions;
if (http.includeQuery)
body.query = printer(query, utilities.print);
return {
options: options,
body: body,
};
}
function removeDuplicateHeaders(headers, preserveHeaderCase) {
if (!preserveHeaderCase) {
var normalizedHeaders_1 = Object.create(null);
Object.keys(Object(headers)).forEach(function (name) {
normalizedHeaders_1[name.toLowerCase()] = headers[name];
});
return normalizedHeaders_1;
}
var headerData = Object.create(null);
Object.keys(Object(headers)).forEach(function (name) {
headerData[name.toLowerCase()] = {
originalName: name,
value: headers[name],
};
});
var normalizedHeaders = Object.create(null);
Object.keys(headerData).forEach(function (name) {
normalizedHeaders[headerData[name].originalName] = headerData[name].value;
});
return normalizedHeaders;
}
var checkFetcher = function (fetcher) {
if (!fetcher && typeof fetch === "undefined") {
throw globals.newInvariantError(37);
}
};
var createSignalIfSupported = function () {
if (typeof AbortController === "undefined")
return { controller: false, signal: false };
var controller = new AbortController();
var signal = controller.signal;
return { controller: controller, signal: signal };
};
var selectURI = function (operation, fallbackURI) {
var context = operation.getContext();
var contextURI = context.uri;
if (contextURI) {
return contextURI;
}
else if (typeof fallbackURI === "function") {
return fallbackURI(operation);
}
else {
return fallbackURI || "/graphql";
}
};
function rewriteURIForGET(chosenURI, body) {
var queryParams = [];
var addQueryParam = function (key, value) {
queryParams.push("".concat(key, "=").concat(encodeURIComponent(value)));
};
if ("query" in body) {
addQueryParam("query", body.query);
}
if (body.operationName) {
addQueryParam("operationName", body.operationName);
}
if (body.variables) {
var serializedVariables = void 0;
try {
serializedVariables = serializeFetchParameter(body.variables, "Variables map");
}
catch (parseError) {
return { parseError: parseError };
}
addQueryParam("variables", serializedVariables);
}
if (body.extensions) {
var serializedExtensions = void 0;
try {
serializedExtensions = serializeFetchParameter(body.extensions, "Extensions map");
}
catch (parseError) {
return { parseError: parseError };
}
addQueryParam("extensions", serializedExtensions);
}
var fragment = "", preFragment = chosenURI;
var fragmentStart = chosenURI.indexOf("#");
if (fragmentStart !== -1) {
fragment = chosenURI.substr(fragmentStart);
preFragment = chosenURI.substr(0, fragmentStart);
}
var queryParamsPrefix = preFragment.indexOf("?") === -1 ? "?" : "&";
var newURI = preFragment + queryParamsPrefix + queryParams.join("&") + fragment;
return { newURI: newURI };
}
var backupFetch = utilities.maybe(function () { return fetch; });
var createHttpLink = function (linkOptions) {
if (linkOptions === void 0) { linkOptions = {}; }
var _a = linkOptions.uri, uri = _a === void 0 ? "/graphql" : _a,
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"]);
if (globalThis.__DEV__ !== false) {
checkFetcher(preferredFetch || backupFetch);
}
var linkConfig = {
http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
return new core.ApolloLink(function (operation) {
var chosenURI = selectURI(operation, uri);
var context = operation.getContext();
var clientAwarenessHeaders = {};
if (context.clientAwareness) {
var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
if (name_1) {
clientAwarenessHeaders["apollographql-client-name"] = name_1;
}
if (version) {
clientAwarenessHeaders["apollographql-client-version"] = version;
}
}
var contextHeaders = tslib.__assign(tslib.__assign({}, clientAwarenessHeaders), context.headers);
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: contextHeaders,
};
if (utilities.hasDirectives(["client"], operation.query)) {
var transformedQuery = utilities.removeClientSetsFromDocument(operation.query);
if (!transformedQuery) {
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`."));
}
operation.query = transformedQuery;
}
var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;
if (body.variables && !includeUnusedVariables) {
body.variables = utils.filterOperationVariables(body.variables, operation.query);
}
var controller;
if (!options.signal && typeof AbortController !== "undefined") {
controller = new AbortController();
options.signal = controller.signal;
}
var definitionIsMutation = function (d) {
return d.kind === "OperationDefinition" && d.operation === "mutation";
};
var definitionIsSubscription = function (d) {
return d.kind === "OperationDefinition" && d.operation === "subscription";
};
var isSubscription = definitionIsSubscription(utilities.getMainDefinition(operation.query));
var hasDefer = utilities.hasDirectives(["defer"], operation.query);
if (useGETForQueries &&
!operation.query.definitions.some(definitionIsMutation)) {
options.method = "GET";
}
if (hasDefer || isSubscription) {
options.headers = options.headers || {};
var acceptHeader = "multipart/mixed;";
if (isSubscription && hasDefer) {
globalThis.__DEV__ !== false && globals.invariant.warn(38);
}
if (isSubscription) {
acceptHeader +=
"boundary=graphql;subscriptionSpec=1.0,application/json";
}
else if (hasDefer) {
acceptHeader += "deferSpec=20220824,application/json";
}
options.headers.accept = acceptHeader;
}
if (options.method === "GET") {
var _c = rewriteURIForGET(chosenURI, body), newURI = _c.newURI, parseError = _c.parseError;
if (parseError) {
return utils.fromError(parseError);
}
chosenURI = newURI;
}
else {
try {
options.body = serializeFetchParameter(body, "Payload");
}
catch (parseError) {
return utils.fromError(parseError);
}
}
return new utilities.Observable(function (observer) {
var currentFetch = preferredFetch || utilities.maybe(function () { return fetch; }) || backupFetch;
var observerNext = observer.next.bind(observer);
currentFetch(chosenURI, options)
.then(function (response) {
var _a;
operation.setContext({ response: response });
var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
return readMultipartBody(response, observerNext);
}
else {
return parseAndCheckHttpResponse(operation)(response).then(observerNext);
}
})
.then(function () {
controller = undefined;
observer.complete();
})
.catch(function (err) {
controller = undefined;
handleError(err, observer);
});
return function () {
if (controller)
controller.abort();
};
});
});
};
var HttpLink = (function (_super) {
tslib.__extends(HttpLink, _super);
function HttpLink(options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, createHttpLink(options).request) || this;
_this.options = options;
return _this;
}
return HttpLink;
}(core.ApolloLink));
exports.HttpLink = HttpLink;
exports.checkFetcher = checkFetcher;
exports.createHttpLink = createHttpLink;
exports.createSignalIfSupported = createSignalIfSupported;
exports.defaultPrinter = defaultPrinter;
exports.fallbackHttpConfig = fallbackHttpConfig;
exports.parseAndCheckHttpResponse = parseAndCheckHttpResponse;
exports.rewriteURIForGET = rewriteURIForGET;
exports.selectHttpOptionsAndBody = selectHttpOptionsAndBody;
exports.selectHttpOptionsAndBodyInternal = selectHttpOptionsAndBodyInternal;
exports.selectURI = selectURI;
exports.serializeFetchParameter = serializeFetchParameter;
//# sourceMappingURL=http.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,631 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var globals = require('../../utilities/globals');
var tslib = require('tslib');
var utilities = require('../../utilities');
var utils = require('../utils');
var errors = require('../../errors');
var core = require('../core');
function asyncIterator(source) {
var _a;
var iterator = source[Symbol.asyncIterator]();
return _a = {
next: function () {
return iterator.next();
}
},
_a[Symbol.asyncIterator] = function () {
return this;
},
_a;
}
function nodeStreamIterator(stream) {
var cleanup = null;
var error = null;
var done = false;
var data = [];
var waiting = [];
function onData(chunk) {
if (error)
return;
if (waiting.length) {
var shiftedArr = waiting.shift();
if (Array.isArray(shiftedArr) && shiftedArr[0]) {
return shiftedArr[0]({ value: chunk, done: false });
}
}
data.push(chunk);
}
function onError(err) {
error = err;
var all = waiting.slice();
all.forEach(function (pair) {
pair[1](err);
});
!cleanup || cleanup();
}
function onEnd() {
done = true;
var all = waiting.slice();
all.forEach(function (pair) {
pair[0]({ value: undefined, done: true });
});
!cleanup || cleanup();
}
cleanup = function () {
cleanup = null;
stream.removeListener("data", onData);
stream.removeListener("error", onError);
stream.removeListener("end", onEnd);
stream.removeListener("finish", onEnd);
stream.removeListener("close", onEnd);
};
stream.on("data", onData);
stream.on("error", onError);
stream.on("end", onEnd);
stream.on("finish", onEnd);
stream.on("close", onEnd);
function getNext() {
return new Promise(function (resolve, reject) {
if (error)
return reject(error);
if (data.length)
return resolve({ value: data.shift(), done: false });
if (done)
return resolve({ value: undefined, done: true });
waiting.push([resolve, reject]);
});
}
var iterator = {
next: function () {
return getNext();
},
};
if (utilities.canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
function promiseIterator(promise) {
var resolved = false;
var iterator = {
next: function () {
if (resolved)
return Promise.resolve({
value: undefined,
done: true,
});
resolved = true;
return new Promise(function (resolve, reject) {
promise
.then(function (value) {
resolve({ value: value, done: false });
})
.catch(reject);
});
},
};
if (utilities.canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
function readerIterator(reader) {
var iterator = {
next: function () {
return reader.read();
},
};
if (utilities.canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
function isNodeResponse(value) {
return !!value.body;
}
function isReadableStream(value) {
return !!value.getReader;
}
function isAsyncIterableIterator(value) {
return !!(utilities.canUseAsyncIteratorSymbol &&
value[Symbol.asyncIterator]);
}
function isStreamableBlob(value) {
return !!value.stream;
}
function isBlob(value) {
return !!value.arrayBuffer;
}
function isNodeReadableStream(value) {
return !!value.pipe;
}
function responseIterator(response) {
var body = response;
if (isNodeResponse(response))
body = response.body;
if (isAsyncIterableIterator(body))
return asyncIterator(body);
if (isReadableStream(body))
return readerIterator(body.getReader());
if (isStreamableBlob(body)) {
return readerIterator(body.stream().getReader());
}
if (isBlob(body))
return promiseIterator(body.arrayBuffer());
if (isNodeReadableStream(body))
return nodeStreamIterator(body);
throw new Error("Unknown body type for responseIterator. Please pass a streamable response.");
}
function isNonNullObject(obj) {
return obj !== null && typeof obj === "object";
}
function isApolloPayloadResult(value) {
return isNonNullObject(value) && "payload" in value;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function readMultipartBody(response, nextValue) {
var _a;
return tslib.__awaiter(this, void 0, void 0, function () {
var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _b, value, done, chunk, searchFrom, bi, message, i, headers, contentType_1, body, result, next;
var _c, _d;
return tslib.__generator(this, function (_e) {
switch (_e.label) {
case 0:
if (TextDecoder === undefined) {
throw new Error("TextDecoder must be defined in the environment: please import a polyfill.");
}
decoder = new TextDecoder("utf-8");
contentType = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
delimiter = "boundary=";
boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter)) ?
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()
: "-";
boundary = "\r\n--".concat(boundaryVal);
buffer = "";
iterator = responseIterator(response);
running = true;
_e.label = 1;
case 1:
if (!running) return [3 , 3];
return [4 , iterator.next()];
case 2:
_b = _e.sent(), value = _b.value, done = _b.done;
chunk = typeof value === "string" ? value : decoder.decode(value);
searchFrom = buffer.length - boundary.length + 1;
running = !done;
buffer += chunk;
bi = buffer.indexOf(boundary, searchFrom);
while (bi > -1) {
message = void 0;
_c = [
buffer.slice(0, bi),
buffer.slice(bi + boundary.length),
], message = _c[0], buffer = _c[1];
i = message.indexOf("\r\n\r\n");
headers = parseHeaders(message.slice(0, i));
contentType_1 = headers["content-type"];
if (contentType_1 &&
contentType_1.toLowerCase().indexOf("application/json") === -1) {
throw new Error("Unsupported patch content type: application/json is required.");
}
body = message.slice(i);
if (body) {
result = parseJsonBody(response, body);
if (Object.keys(result).length > 1 ||
"data" in result ||
"incremental" in result ||
"errors" in result ||
"payload" in result) {
if (isApolloPayloadResult(result)) {
next = {};
if ("payload" in result) {
next = tslib.__assign({}, result.payload);
}
if ("errors" in result) {
next = tslib.__assign(tslib.__assign({}, next), { extensions: tslib.__assign(tslib.__assign({}, ("extensions" in next ? next.extensions : null)), (_d = {}, _d[errors.PROTOCOL_ERRORS_SYMBOL] = result.errors, _d)) });
}
nextValue(next);
}
else {
nextValue(result);
}
}
else if (
Object.keys(result).length === 1 &&
"hasNext" in result &&
!result.hasNext) {
return [2 ];
}
}
bi = buffer.indexOf(boundary);
}
return [3 , 1];
case 3: return [2 ];
}
});
});
}
function parseHeaders(headerText) {
var headersInit = {};
headerText.split("\n").forEach(function (line) {
var i = line.indexOf(":");
if (i > -1) {
var name_1 = line.slice(0, i).trim().toLowerCase();
var value = line.slice(i + 1).trim();
headersInit[name_1] = value;
}
});
return headersInit;
}
function parseJsonBody(response, bodyText) {
if (response.status >= 300) {
var getResult = function () {
try {
return JSON.parse(bodyText);
}
catch (err) {
return bodyText;
}
};
utils.throwServerError(response, getResult(), "Response not successful: Received status code ".concat(response.status));
}
try {
return JSON.parse(bodyText);
}
catch (err) {
var parseError = err;
parseError.name = "ServerParseError";
parseError.response = response;
parseError.statusCode = response.status;
parseError.bodyText = bodyText;
throw parseError;
}
}
function handleError(err, observer) {
if (err.result && err.result.errors && err.result.data) {
observer.next(err.result);
}
observer.error(err);
}
function parseAndCheckHttpResponse(operations) {
return function (response) {
return response
.text()
.then(function (bodyText) { return parseJsonBody(response, bodyText); })
.then(function (result) {
if (!Array.isArray(result) &&
!hasOwnProperty.call(result, "data") &&
!hasOwnProperty.call(result, "errors")) {
utils.throwServerError(response, result, "Server response was missing for query '".concat(Array.isArray(operations) ?
operations.map(function (op) { return op.operationName; })
: operations.operationName, "'."));
}
return result;
});
};
}
var serializeFetchParameter = function (p, label) {
var serialized;
try {
serialized = JSON.stringify(p);
}
catch (e) {
var parseError = globals.newInvariantError(39, label, e.message);
parseError.parseError = e;
throw parseError;
}
return serialized;
};
var defaultHttpOptions = {
includeQuery: true,
includeExtensions: false,
preserveHeaderCase: false,
};
var defaultHeaders = {
accept: "*/*",
"content-type": "application/json",
};
var defaultOptions = {
method: "POST",
};
var fallbackHttpConfig = {
http: defaultHttpOptions,
headers: defaultHeaders,
options: defaultOptions,
};
var defaultPrinter = function (ast, printer) { return printer(ast); };
function selectHttpOptionsAndBody(operation, fallbackConfig) {
var configs = [];
for (var _i = 2; _i < arguments.length; _i++) {
configs[_i - 2] = arguments[_i];
}
configs.unshift(fallbackConfig);
return selectHttpOptionsAndBodyInternal.apply(void 0, tslib.__spreadArray([operation,
defaultPrinter], configs, false));
}
function selectHttpOptionsAndBodyInternal(operation, printer) {
var configs = [];
for (var _i = 2; _i < arguments.length; _i++) {
configs[_i - 2] = arguments[_i];
}
var options = {};
var http = {};
configs.forEach(function (config) {
options = tslib.__assign(tslib.__assign(tslib.__assign({}, options), config.options), { headers: tslib.__assign(tslib.__assign({}, options.headers), config.headers) });
if (config.credentials) {
options.credentials = config.credentials;
}
http = tslib.__assign(tslib.__assign({}, http), config.http);
});
if (options.headers) {
options.headers = removeDuplicateHeaders(options.headers, http.preserveHeaderCase);
}
var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;
var body = { operationName: operationName, variables: variables };
if (http.includeExtensions)
body.extensions = extensions;
if (http.includeQuery)
body.query = printer(query, utilities.print);
return {
options: options,
body: body,
};
}
function removeDuplicateHeaders(headers, preserveHeaderCase) {
if (!preserveHeaderCase) {
var normalizedHeaders_1 = Object.create(null);
Object.keys(Object(headers)).forEach(function (name) {
normalizedHeaders_1[name.toLowerCase()] = headers[name];
});
return normalizedHeaders_1;
}
var headerData = Object.create(null);
Object.keys(Object(headers)).forEach(function (name) {
headerData[name.toLowerCase()] = {
originalName: name,
value: headers[name],
};
});
var normalizedHeaders = Object.create(null);
Object.keys(headerData).forEach(function (name) {
normalizedHeaders[headerData[name].originalName] = headerData[name].value;
});
return normalizedHeaders;
}
var checkFetcher = function (fetcher) {
if (!fetcher && typeof fetch === "undefined") {
throw globals.newInvariantError(37);
}
};
var createSignalIfSupported = function () {
if (typeof AbortController === "undefined")
return { controller: false, signal: false };
var controller = new AbortController();
var signal = controller.signal;
return { controller: controller, signal: signal };
};
var selectURI = function (operation, fallbackURI) {
var context = operation.getContext();
var contextURI = context.uri;
if (contextURI) {
return contextURI;
}
else if (typeof fallbackURI === "function") {
return fallbackURI(operation);
}
else {
return fallbackURI || "/graphql";
}
};
function rewriteURIForGET(chosenURI, body) {
var queryParams = [];
var addQueryParam = function (key, value) {
queryParams.push("".concat(key, "=").concat(encodeURIComponent(value)));
};
if ("query" in body) {
addQueryParam("query", body.query);
}
if (body.operationName) {
addQueryParam("operationName", body.operationName);
}
if (body.variables) {
var serializedVariables = void 0;
try {
serializedVariables = serializeFetchParameter(body.variables, "Variables map");
}
catch (parseError) {
return { parseError: parseError };
}
addQueryParam("variables", serializedVariables);
}
if (body.extensions) {
var serializedExtensions = void 0;
try {
serializedExtensions = serializeFetchParameter(body.extensions, "Extensions map");
}
catch (parseError) {
return { parseError: parseError };
}
addQueryParam("extensions", serializedExtensions);
}
var fragment = "", preFragment = chosenURI;
var fragmentStart = chosenURI.indexOf("#");
if (fragmentStart !== -1) {
fragment = chosenURI.substr(fragmentStart);
preFragment = chosenURI.substr(0, fragmentStart);
}
var queryParamsPrefix = preFragment.indexOf("?") === -1 ? "?" : "&";
var newURI = preFragment + queryParamsPrefix + queryParams.join("&") + fragment;
return { newURI: newURI };
}
var backupFetch = utilities.maybe(function () { return fetch; });
var createHttpLink = function (linkOptions) {
if (linkOptions === void 0) { linkOptions = {}; }
var _a = linkOptions.uri, uri = _a === void 0 ? "/graphql" : _a,
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"]);
if (globalThis.__DEV__ !== false) {
checkFetcher(preferredFetch || backupFetch);
}
var linkConfig = {
http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
return new core.ApolloLink(function (operation) {
var chosenURI = selectURI(operation, uri);
var context = operation.getContext();
var clientAwarenessHeaders = {};
if (context.clientAwareness) {
var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
if (name_1) {
clientAwarenessHeaders["apollographql-client-name"] = name_1;
}
if (version) {
clientAwarenessHeaders["apollographql-client-version"] = version;
}
}
var contextHeaders = tslib.__assign(tslib.__assign({}, clientAwarenessHeaders), context.headers);
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: contextHeaders,
};
if (utilities.hasDirectives(["client"], operation.query)) {
var transformedQuery = utilities.removeClientSetsFromDocument(operation.query);
if (!transformedQuery) {
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`."));
}
operation.query = transformedQuery;
}
var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;
if (body.variables && !includeUnusedVariables) {
body.variables = utils.filterOperationVariables(body.variables, operation.query);
}
var controller;
if (!options.signal && typeof AbortController !== "undefined") {
controller = new AbortController();
options.signal = controller.signal;
}
var definitionIsMutation = function (d) {
return d.kind === "OperationDefinition" && d.operation === "mutation";
};
var definitionIsSubscription = function (d) {
return d.kind === "OperationDefinition" && d.operation === "subscription";
};
var isSubscription = definitionIsSubscription(utilities.getMainDefinition(operation.query));
var hasDefer = utilities.hasDirectives(["defer"], operation.query);
if (useGETForQueries &&
!operation.query.definitions.some(definitionIsMutation)) {
options.method = "GET";
}
if (hasDefer || isSubscription) {
options.headers = options.headers || {};
var acceptHeader = "multipart/mixed;";
if (isSubscription && hasDefer) {
globalThis.__DEV__ !== false && globals.invariant.warn(38);
}
if (isSubscription) {
acceptHeader +=
"boundary=graphql;subscriptionSpec=1.0,application/json";
}
else if (hasDefer) {
acceptHeader += "deferSpec=20220824,application/json";
}
options.headers.accept = acceptHeader;
}
if (options.method === "GET") {
var _c = rewriteURIForGET(chosenURI, body), newURI = _c.newURI, parseError = _c.parseError;
if (parseError) {
return utils.fromError(parseError);
}
chosenURI = newURI;
}
else {
try {
options.body = serializeFetchParameter(body, "Payload");
}
catch (parseError) {
return utils.fromError(parseError);
}
}
return new utilities.Observable(function (observer) {
var currentFetch = preferredFetch || utilities.maybe(function () { return fetch; }) || backupFetch;
var observerNext = observer.next.bind(observer);
currentFetch(chosenURI, options)
.then(function (response) {
var _a;
operation.setContext({ response: response });
var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
return readMultipartBody(response, observerNext);
}
else {
return parseAndCheckHttpResponse(operation)(response).then(observerNext);
}
})
.then(function () {
controller = undefined;
observer.complete();
})
.catch(function (err) {
controller = undefined;
handleError(err, observer);
});
return function () {
if (controller)
controller.abort();
};
});
});
};
var HttpLink = (function (_super) {
tslib.__extends(HttpLink, _super);
function HttpLink(options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, createHttpLink(options).request) || this;
_this.options = options;
return _this;
}
return HttpLink;
}(core.ApolloLink));
exports.HttpLink = HttpLink;
exports.checkFetcher = checkFetcher;
exports.createHttpLink = createHttpLink;
exports.createSignalIfSupported = createSignalIfSupported;
exports.defaultPrinter = defaultPrinter;
exports.fallbackHttpConfig = fallbackHttpConfig;
exports.parseAndCheckHttpResponse = parseAndCheckHttpResponse;
exports.rewriteURIForGET = rewriteURIForGET;
exports.selectHttpOptionsAndBody = selectHttpOptionsAndBody;
exports.selectHttpOptionsAndBodyInternal = selectHttpOptionsAndBodyInternal;
exports.selectURI = selectURI;
exports.serializeFetchParameter = serializeFetchParameter;
//# sourceMappingURL=http.cjs.map

View File

@@ -0,0 +1,14 @@
import "../../utilities/globals/index.js";
export type { ServerParseError } from "./parseAndCheckHttpResponse.js";
export { parseAndCheckHttpResponse } from "./parseAndCheckHttpResponse.js";
export type { ClientParseError } from "./serializeFetchParameter.js";
export { serializeFetchParameter } from "./serializeFetchParameter.js";
export type { HttpOptions, UriFunction } from "./selectHttpOptionsAndBody.js";
export { fallbackHttpConfig, defaultPrinter, selectHttpOptionsAndBody, selectHttpOptionsAndBodyInternal, } from "./selectHttpOptionsAndBody.js";
export { checkFetcher } from "./checkFetcher.js";
export { createSignalIfSupported } from "./createSignalIfSupported.js";
export { selectURI } from "./selectURI.js";
export { createHttpLink } from "./createHttpLink.js";
export { HttpLink } from "./HttpLink.js";
export { rewriteURIForGET } from "./rewriteURIForGET.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,12 @@
import "../../utilities/globals/index.js";
export { parseAndCheckHttpResponse } from "./parseAndCheckHttpResponse.js";
export { serializeFetchParameter } from "./serializeFetchParameter.js";
export { fallbackHttpConfig, defaultPrinter, selectHttpOptionsAndBody, selectHttpOptionsAndBodyInternal, // needed by ../batch-http but not public
} from "./selectHttpOptionsAndBody.js";
export { checkFetcher } from "./checkFetcher.js";
export { createSignalIfSupported } from "./createSignalIfSupported.js";
export { selectURI } from "./selectURI.js";
export { createHttpLink } from "./createHttpLink.js";
export { HttpLink } from "./HttpLink.js";
export { rewriteURIForGET } from "./rewriteURIForGET.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/link/http/index.ts"],"names":[],"mappings":"AAAA,OAAO,kCAAkC,CAAC;AAG1C,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAE3E,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAEvE,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,wBAAwB,EACxB,gCAAgC,EAAE,yCAAyC;EAC5E,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["import \"../../utilities/globals/index.js\";\n\nexport type { ServerParseError } from \"./parseAndCheckHttpResponse.js\";\nexport { parseAndCheckHttpResponse } from \"./parseAndCheckHttpResponse.js\";\nexport type { ClientParseError } from \"./serializeFetchParameter.js\";\nexport { serializeFetchParameter } from \"./serializeFetchParameter.js\";\nexport type { HttpOptions, UriFunction } from \"./selectHttpOptionsAndBody.js\";\nexport {\n fallbackHttpConfig,\n defaultPrinter,\n selectHttpOptionsAndBody,\n selectHttpOptionsAndBodyInternal, // needed by ../batch-http but not public\n} from \"./selectHttpOptionsAndBody.js\";\nexport { checkFetcher } from \"./checkFetcher.js\";\nexport { createSignalIfSupported } from \"./createSignalIfSupported.js\";\nexport { selectURI } from \"./selectURI.js\";\nexport { createHttpLink } from \"./createHttpLink.js\";\nexport { HttpLink } from \"./HttpLink.js\";\nexport { rewriteURIForGET } from \"./rewriteURIForGET.js\";\n"]}

View File

@@ -0,0 +1,6 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts
*/
export default function asyncIterator<T>(source: AsyncIterableIterator<T>): AsyncIterableIterator<T>;
//# sourceMappingURL=async.d.ts.map

View File

@@ -0,0 +1,18 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts
*/
export default function asyncIterator(source) {
var _a;
var iterator = source[Symbol.asyncIterator]();
return _a = {
next: function () {
return iterator.next();
}
},
_a[Symbol.asyncIterator] = function () {
return this;
},
_a;
}
//# sourceMappingURL=async.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"async.js","sourceRoot":"","sources":["../../../../src/link/http/iterators/async.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,CAAC,OAAO,UAAU,aAAa,CACnC,MAAgC;;IAEhC,IAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;IAChD;YACE,IAAI;gBACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;YACzB,CAAC;;QACD,GAAC,MAAM,CAAC,aAAa,IAArB;YACE,OAAO,IAAI,CAAC;QACd,CAAC;WACD;AACJ,CAAC","sourcesContent":["/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts\n */\n\nexport default function asyncIterator<T>(\n source: AsyncIterableIterator<T>\n): AsyncIterableIterator<T> {\n const iterator = source[Symbol.asyncIterator]();\n return {\n next(): Promise<IteratorResult<T, boolean>> {\n return iterator.next();\n },\n [Symbol.asyncIterator](): AsyncIterableIterator<T> {\n return this;\n },\n };\n}\n"]}

View File

@@ -0,0 +1,8 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/nodeStream.ts
*/
/// <reference types="node" />
import type { Readable as NodeReadableStream } from "stream";
export default function nodeStreamIterator<T>(stream: NodeReadableStream): AsyncIterableIterator<T>;
//# sourceMappingURL=nodeStream.d.ts.map

View File

@@ -0,0 +1,75 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/nodeStream.ts
*/
import { canUseAsyncIteratorSymbol } from "../../../utilities/index.js";
export default function nodeStreamIterator(stream) {
var cleanup = null;
var error = null;
var done = false;
var data = [];
var waiting = [];
function onData(chunk) {
if (error)
return;
if (waiting.length) {
var shiftedArr = waiting.shift();
if (Array.isArray(shiftedArr) && shiftedArr[0]) {
return shiftedArr[0]({ value: chunk, done: false });
}
}
data.push(chunk);
}
function onError(err) {
error = err;
var all = waiting.slice();
all.forEach(function (pair) {
pair[1](err);
});
!cleanup || cleanup();
}
function onEnd() {
done = true;
var all = waiting.slice();
all.forEach(function (pair) {
pair[0]({ value: undefined, done: true });
});
!cleanup || cleanup();
}
cleanup = function () {
cleanup = null;
stream.removeListener("data", onData);
stream.removeListener("error", onError);
stream.removeListener("end", onEnd);
stream.removeListener("finish", onEnd);
stream.removeListener("close", onEnd);
};
stream.on("data", onData);
stream.on("error", onError);
stream.on("end", onEnd);
stream.on("finish", onEnd);
stream.on("close", onEnd);
function getNext() {
return new Promise(function (resolve, reject) {
if (error)
return reject(error);
if (data.length)
return resolve({ value: data.shift(), done: false });
if (done)
return resolve({ value: undefined, done: true });
waiting.push([resolve, reject]);
});
}
var iterator = {
next: function () {
return getNext();
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=nodeStream.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/promise.ts
*/
export default function promiseIterator<T = ArrayBuffer>(promise: Promise<ArrayBuffer>): AsyncIterableIterator<T>;
//# sourceMappingURL=promise.d.ts.map

View File

@@ -0,0 +1,32 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/promise.ts
*/
import { canUseAsyncIteratorSymbol } from "../../../utilities/index.js";
export default function promiseIterator(promise) {
var resolved = false;
var iterator = {
next: function () {
if (resolved)
return Promise.resolve({
value: undefined,
done: true,
});
resolved = true;
return new Promise(function (resolve, reject) {
promise
.then(function (value) {
resolve({ value: value, done: false });
})
.catch(reject);
});
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=promise.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"promise.js","sourceRoot":"","sources":["../../../../src/link/http/iterators/promise.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAOxE,MAAM,CAAC,OAAO,UAAU,eAAe,CACrC,OAA6B;IAE7B,IAAI,QAAQ,GAAG,KAAK,CAAC;IAErB,IAAM,QAAQ,GAAuB;QACnC,IAAI;YACF,IAAI,QAAQ;gBACV,OAAO,OAAO,CAAC,OAAO,CAAC;oBACrB,KAAK,EAAE,SAAS;oBAChB,IAAI,EAAE,IAAI;iBACX,CAAC,CAAC;YACL,QAAQ,GAAG,IAAI,CAAC;YAChB,OAAO,IAAI,OAAO,CAAC,UAAU,OAAO,EAAE,MAAM;gBAC1C,OAAO;qBACJ,IAAI,CAAC,UAAU,KAAK;oBACnB,OAAO,CAAC,EAAE,KAAK,EAAE,KAAqB,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;gBACzD,CAAC,CAAC;qBACD,KAAK,CAAC,MAAM,CAAC,CAAC;YACnB,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;IAEF,IAAI,yBAAyB,EAAE,CAAC;QAC9B,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG;YAC/B,OAAO,IAAI,CAAC;QACd,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,QAAoC,CAAC;AAC9C,CAAC","sourcesContent":["/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/promise.ts\n */\n\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\n\ninterface PromiseIterator<T> {\n next(): Promise<IteratorResult<T, ArrayBuffer | undefined>>;\n [Symbol.asyncIterator]?(): AsyncIterator<T>;\n}\n\nexport default function promiseIterator<T = ArrayBuffer>(\n promise: Promise<ArrayBuffer>\n): AsyncIterableIterator<T> {\n let resolved = false;\n\n const iterator: PromiseIterator<T> = {\n next(): Promise<IteratorResult<T, ArrayBuffer | undefined>> {\n if (resolved)\n return Promise.resolve({\n value: undefined,\n done: true,\n });\n resolved = true;\n return new Promise(function (resolve, reject) {\n promise\n .then(function (value) {\n resolve({ value: value as unknown as T, done: false });\n })\n .catch(reject);\n });\n },\n };\n\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function (): AsyncIterator<T> {\n return this;\n };\n }\n\n return iterator as AsyncIterableIterator<T>;\n}\n"]}

View File

@@ -0,0 +1,6 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/reader.ts
*/
export default function readerIterator<T>(reader: ReadableStreamDefaultReader<T>): AsyncIterableIterator<T>;
//# sourceMappingURL=reader.d.ts.map

View File

@@ -0,0 +1,19 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/reader.ts
*/
import { canUseAsyncIteratorSymbol } from "../../../utilities/index.js";
export default function readerIterator(reader) {
var iterator = {
next: function () {
return reader.read();
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=reader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"reader.js","sourceRoot":"","sources":["../../../../src/link/http/iterators/reader.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAOxE,MAAM,CAAC,OAAO,UAAU,cAAc,CACpC,MAAsC;IAEtC,IAAM,QAAQ,GAAsB;QAClC,IAAI;YACF,OAAO,MAAM,CAAC,IAAI,EAKjB,CAAC;QACJ,CAAC;KACF,CAAC;IAEF,IAAI,yBAAyB,EAAE,CAAC;QAC9B,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG;YAI/B,OAAO,IAAI,CAAC;QACd,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,QAAoC,CAAC;AAC9C,CAAC","sourcesContent":["/**\n * Original source:\n * https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/reader.ts\n */\n\nimport { canUseAsyncIteratorSymbol } from \"../../../utilities/index.js\";\n\ninterface ReaderIterator<T> {\n next(): Promise<IteratorResult<T, T | undefined>>;\n [Symbol.asyncIterator]?(): AsyncIterator<T>;\n}\n\nexport default function readerIterator<T>(\n reader: ReadableStreamDefaultReader<T>\n): AsyncIterableIterator<T> {\n const iterator: ReaderIterator<T> = {\n next() {\n return reader.read() as Promise<\n | ReadableStreamReadValueResult<T>\n // DoneResult has `value` optional, which doesn't comply with an\n // `IteratorResult`, so we assert it to `T | undefined` instead\n | Required<ReadableStreamReadDoneResult<T | undefined>>\n >;\n },\n };\n\n if (canUseAsyncIteratorSymbol) {\n iterator[Symbol.asyncIterator] = function (): AsyncIterator<\n T,\n T | undefined\n > {\n return this;\n };\n }\n\n return iterator as AsyncIterableIterator<T>;\n}\n"]}

View File

@@ -0,0 +1,8 @@
{
"name": "@apollo/client/link/http",
"type": "module",
"main": "http.cjs",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false
}

View File

@@ -0,0 +1,13 @@
import type { Operation } from "../core/index.js";
import type { SubscriptionObserver } from "zen-observable-ts";
export type ServerParseError = Error & {
response: Response;
statusCode: number;
bodyText: string;
};
export declare function readMultipartBody<T extends object = Record<string, unknown>>(response: Response, nextValue: (value: T) => void): Promise<void>;
export declare function parseHeaders(headerText: string): Record<string, string>;
export declare function parseJsonBody<T>(response: Response, bodyText: string): T;
export declare function handleError(err: any, observer: SubscriptionObserver<any>): void;
export declare function parseAndCheckHttpResponse(operations: Operation | Operation[]): (response: Response) => Promise<any>;
//# sourceMappingURL=parseAndCheckHttpResponse.d.ts.map

View File

@@ -0,0 +1,187 @@
import { __assign, __awaiter, __generator } from "tslib";
import { responseIterator } from "./responseIterator.js";
import { throwServerError } from "../utils/index.js";
import { PROTOCOL_ERRORS_SYMBOL } from "../../errors/index.js";
import { isApolloPayloadResult } from "../../utilities/common/incrementalResult.js";
var hasOwnProperty = Object.prototype.hasOwnProperty;
export function readMultipartBody(response, nextValue) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _b, value, done, chunk, searchFrom, bi, message, i, headers, contentType_1, body, result, next;
var _c, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
if (TextDecoder === undefined) {
throw new Error("TextDecoder must be defined in the environment: please import a polyfill.");
}
decoder = new TextDecoder("utf-8");
contentType = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
delimiter = "boundary=";
boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter)) ?
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()
: "-";
boundary = "\r\n--".concat(boundaryVal);
buffer = "";
iterator = responseIterator(response);
running = true;
_e.label = 1;
case 1:
if (!running) return [3 /*break*/, 3];
return [4 /*yield*/, iterator.next()];
case 2:
_b = _e.sent(), value = _b.value, done = _b.done;
chunk = typeof value === "string" ? value : decoder.decode(value);
searchFrom = buffer.length - boundary.length + 1;
running = !done;
buffer += chunk;
bi = buffer.indexOf(boundary, searchFrom);
while (bi > -1) {
message = void 0;
_c = [
buffer.slice(0, bi),
buffer.slice(bi + boundary.length),
], message = _c[0], buffer = _c[1];
i = message.indexOf("\r\n\r\n");
headers = parseHeaders(message.slice(0, i));
contentType_1 = headers["content-type"];
if (contentType_1 &&
contentType_1.toLowerCase().indexOf("application/json") === -1) {
throw new Error("Unsupported patch content type: application/json is required.");
}
body = message.slice(i);
if (body) {
result = parseJsonBody(response, body);
if (Object.keys(result).length > 1 ||
"data" in result ||
"incremental" in result ||
"errors" in result ||
"payload" in result) {
if (isApolloPayloadResult(result)) {
next = {};
if ("payload" in result) {
next = __assign({}, result.payload);
}
if ("errors" in result) {
next = __assign(__assign({}, next), { extensions: __assign(__assign({}, ("extensions" in next ? next.extensions : null)), (_d = {}, _d[PROTOCOL_ERRORS_SYMBOL] = result.errors, _d)) });
}
nextValue(next);
}
else {
// for the last chunk with only `hasNext: false`
// we don't need to call observer.next as there is no data/errors
nextValue(result);
}
}
else if (
// If the chunk contains only a "hasNext: false", we can call
// observer.complete() immediately.
Object.keys(result).length === 1 &&
"hasNext" in result &&
!result.hasNext) {
return [2 /*return*/];
}
}
bi = buffer.indexOf(boundary);
}
return [3 /*break*/, 1];
case 3: return [2 /*return*/];
}
});
});
}
export function parseHeaders(headerText) {
var headersInit = {};
headerText.split("\n").forEach(function (line) {
var i = line.indexOf(":");
if (i > -1) {
// normalize headers to lowercase
var name_1 = line.slice(0, i).trim().toLowerCase();
var value = line.slice(i + 1).trim();
headersInit[name_1] = value;
}
});
return headersInit;
}
export function parseJsonBody(response, bodyText) {
if (response.status >= 300) {
// Network error
var getResult = function () {
try {
return JSON.parse(bodyText);
}
catch (err) {
return bodyText;
}
};
throwServerError(response, getResult(), "Response not successful: Received status code ".concat(response.status));
}
try {
return JSON.parse(bodyText);
}
catch (err) {
var parseError = err;
parseError.name = "ServerParseError";
parseError.response = response;
parseError.statusCode = response.status;
parseError.bodyText = bodyText;
throw parseError;
}
}
export function handleError(err, observer) {
// if it is a network error, BUT there is graphql result info fire
// the next observer before calling error this gives apollo-client
// (and react-apollo) the `graphqlErrors` and `networkErrors` to
// pass to UI this should only happen if we *also* have data as
// part of the response key per the spec
if (err.result && err.result.errors && err.result.data) {
// if we don't call next, the UI can only show networkError
// because AC didn't get any graphqlErrors this is graphql
// execution result info (i.e errors and possibly data) this is
// because there is no formal spec how errors should translate to
// http status codes. So an auth error (401) could have both data
// from a public field, errors from a private field, and a status
// of 401
// {
// user { // this will have errors
// firstName
// }
// products { // this is public so will have data
// cost
// }
// }
//
// the result of above *could* look like this:
// {
// data: { products: [{ cost: "$10" }] },
// errors: [{
// message: 'your session has timed out',
// path: []
// }]
// }
// status code of above would be a 401
// in the UI you want to show data where you can, errors as data where you can
// and use correct http status codes
observer.next(err.result);
}
observer.error(err);
}
export function parseAndCheckHttpResponse(operations) {
return function (response) {
return response
.text()
.then(function (bodyText) { return parseJsonBody(response, bodyText); })
.then(function (result) {
if (!Array.isArray(result) &&
!hasOwnProperty.call(result, "data") &&
!hasOwnProperty.call(result, "errors")) {
// Data error
throwServerError(response, result, "Server response was missing for query '".concat(Array.isArray(operations) ?
operations.map(function (op) { return op.operationName; })
: operations.operationName, "'."));
}
return result;
});
};
}
//# sourceMappingURL=parseAndCheckHttpResponse.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/index.ts
*/
import type { Response as NodeResponse } from "node-fetch";
export declare function responseIterator<T>(response: Response | NodeResponse): AsyncIterableIterator<T>;
//# sourceMappingURL=responseIterator.d.ts.map

Some files were not shown because too many files have changed in this diff Show More