Socket
Socket
Sign inDemoInstall

@apollo/client

Package Overview
Dependencies
Maintainers
4
Versions
575
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@apollo/client - npm Package Compare versions

Comparing version 0.0.0-pr-11670-20240314104411 to 0.0.0-pr-11698-20240415134929

dev/setErrorMessageHandler.d.ts

84

cache/core/cache.d.ts
import type { DocumentNode } from "graphql";
import type { StoreObject, Reference } from "../../utilities/index.js";
import type { StoreObject, Reference, DeepPartial } from "../../utilities/index.js";
import { Observable } from "../../utilities/index.js";
import type { DataProxy } from "./types/DataProxy.js";
import type { Cache } from "./types/Cache.js";
import { getApolloCacheMemoryInternals } from "../../utilities/caching/getMemoryInternals.js";
import type { OperationVariables, TypedDocumentNode } from "../../core/types.js";
import type { MissingTree } from "./types/common.js";
export type Transaction<T> = (c: ApolloCache<T>) => void;
/**
* Watched fragment options.
*/
export interface WatchFragmentOptions<TData, TVars> {
/**
* A GraphQL fragment document parsed into an AST with the `gql`
* template literal.
*
* @docGroup 1. Required options
*/
fragment: DocumentNode | TypedDocumentNode<TData, TVars>;
/**
* An object containing a `__typename` and primary key fields
* (such as `id`) identifying the entity object from which the fragment will
* be retrieved, or a `{ __ref: "..." }` reference, or a `string` ID
* (uncommon).
*
* @docGroup 1. Required options
*/
from: StoreObject | Reference | string;
/**
* Any variables that the GraphQL fragment may depend on.
*
* @docGroup 2. Cache options
*/
variables?: TVars;
/**
* The name of the fragment defined in the fragment document.
*
* Required if the fragment document includes more than one fragment,
* optional otherwise.
*
* @docGroup 2. Cache options
*/
fragmentName?: string;
/**
* If `true`, `watchFragment` returns optimistic results.
*
* The default value is `true`.
*
* @docGroup 2. Cache options
*/
optimistic?: boolean;
/**
* @deprecated
* Using `canonizeResults` can result in memory leaks so we generally do not
* recommend using this option anymore.
* A future version of Apollo Client will contain a similar feature.
*
* Whether to canonize cache results before returning them. Canonization
* takes some extra time, but it speeds up future deep equality comparisons.
* Defaults to false.
*/
canonizeResults?: boolean;
}
/**
* Watched fragment results.
*/
export type WatchFragmentResult<TData> = {
data: TData;
complete: true;
missing?: never;
} | {
data: DeepPartial<TData>;
complete: false;
missing: MissingTree;
};
export declare abstract class ApolloCache<TSerialized> implements DataProxy {

@@ -37,2 +107,14 @@ readonly assumeImmutableResults: boolean;

readQuery<QueryType, TVariables = any>(options: Cache.ReadQueryOptions<QueryType, TVariables>, optimistic?: boolean): QueryType | null;
/**
* Watches the cache store of the fragment according to the options specified and returns an `Observable`. We can subscribe to this `Observable` and receive updated results through an observer when the cache store changes.
*
* You must pass in a GraphQL document with a single fragment or a document with multiple fragments that represent what you are reading. If you pass in a document with multiple fragments then you must also specify a `fragmentName`.
*
* @param options - An object of type `WatchFragmentOptions` that allows the cache to identify the fragment and optionally specify whether to react to optimistic updates.
*
* @since
*
* 3.10.0
*/
watchFragment<TData = any, TVars = OperationVariables>(options: WatchFragmentOptions<TData, TVars>): Observable<WatchFragmentResult<TData>>;
private getFragmentDoc;

@@ -39,0 +121,0 @@ readFragment<FragmentType, TVariables = any>(options: Cache.ReadFragmentOptions<FragmentType, TVariables>, optimistic?: boolean): FragmentType | null;

import { __assign, __rest } from "tslib";
import { wrap } from "optimism";
import { cacheSizes, getFragmentQueryDocument, } from "../../utilities/index.js";
import { Observable, cacheSizes, getFragmentQueryDocument, mergeDeepArray, } from "../../utilities/index.js";
import { WeakCache } from "@wry/caches";
import { getApolloCacheMemoryInternals } from "../../utilities/caching/getMemoryInternals.js";
import { equal } from "@wry/equality";
var ApolloCache = /** @class */ (function () {

@@ -60,2 +61,30 @@ function ApolloCache() {

};
/** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */
ApolloCache.prototype.watchFragment = function (options) {
var _this = this;
var fragment = options.fragment, fragmentName = options.fragmentName, from = options.from, _a = options.optimistic, optimistic = _a === void 0 ? true : _a;
var diffOptions = {
returnPartialData: true,
id: typeof from === "string" ? from : this.identify(from),
query: this.getFragmentDoc(fragment, fragmentName),
optimistic: optimistic,
};
var latestDiff;
return new Observable(function (observer) {
return _this.watch(__assign(__assign({}, diffOptions), { immediate: true, query: _this.getFragmentDoc(fragment, fragmentName), callback: function (diff) {
if (equal(diff, latestDiff)) {
return;
}
var result = {
data: diff.result,
complete: !!diff.complete,
};
if (diff.missing) {
result.missing = mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));
}
latestDiff = diff;
observer.next(result);
} }));
});
};
ApolloCache.prototype.readFragment = function (options, optimistic) {

@@ -62,0 +91,0 @@ if (optimistic === void 0) { optimistic = !!options.optimistic; }

2

cache/index.d.ts
import "../utilities/globals/index.js";
export type { Transaction } from "./core/cache.js";
export type { Transaction, WatchFragmentOptions, WatchFragmentResult, } from "./core/cache.js";
export { ApolloCache } from "./core/cache.js";

@@ -4,0 +4,0 @@ export { Cache } from "./core/types/Cache.js";

@@ -194,11 +194,10 @@ import { __assign } from "tslib";

else if (isArray(fieldValue)) {
fieldValue =
fieldValue.length === 0 ?
fieldValue
: handleMissing(_this.executeSubSelectedArray({
field: selection,
array: fieldValue,
enclosingRef: enclosingRef,
context: context,
}), resultName);
if (fieldValue.length > 0) {
fieldValue = handleMissing(_this.executeSubSelectedArray({
field: selection,
array: fieldValue,
enclosingRef: enclosingRef,
context: context,
}), resultName);
}
}

@@ -205,0 +204,0 @@ else if (!selection.selectionSet) {

@@ -31,3 +31,3 @@ import type { ExecutionResult, DocumentNode } from "graphql";

/**
* You can provide an {@link ApolloLink} instance to serve as Apollo Client's network layer. For more information, see [Advanced HTTP networking](https://www.apollographql.com/docs/react/networking/advanced-http-networking/).
* You can provide an `ApolloLink` instance to serve as Apollo Client's network layer. For more information, see [Advanced HTTP networking](https://www.apollographql.com/docs/react/networking/advanced-http-networking/).
*

@@ -97,8 +97,9 @@ * One of `uri` or `link` is **required**. If you provide both, `link` takes precedence.

import { getApolloClientMemoryInternals } from "../utilities/caching/getMemoryInternals.js";
import type { WatchFragmentOptions, WatchFragmentResult } from "../cache/core/cache.js";
export { mergeOptions };
/**
* This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries
* and mutations) to a GraphQL spec-compliant server over an {@link ApolloLink} instance,
* and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,
* receive results from the server and cache the results in a store. It also delivers updates
* to GraphQL queries through {@link Observable} instances.
* to GraphQL queries through `Observable` instances.
*/

@@ -119,3 +120,3 @@ export declare class ApolloClient<TCacheShape> implements DataProxy {

/**
* Constructs an instance of {@link ApolloClient}.
* Constructs an instance of `ApolloClient`.
*

@@ -160,4 +161,4 @@ * @example

* This watches the cache store of the query according to the options specified and
* returns an {@link ObservableQuery}. We can subscribe to this {@link ObservableQuery} and
* receive updated results through a GraphQL observer when the cache store changes.
* returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and
* receive updated results through an observer when the cache store changes.
*

@@ -184,3 +185,3 @@ * Note that this method is not an implementation of GraphQL subscriptions. Rather,

*
* @param options - An object of type {@link QueryOptions} that allows us to
* @param options - An object of type `QueryOptions` that allows us to
* describe how this query should be treated e.g. whether it should hit the

@@ -201,3 +202,3 @@ * server at all or just resolve from the cache, etc.

* This subscribes to a graphql subscription according to the options specified and returns an
* {@link Observable} which either emits received data or an error.
* `Observable` which either emits received data or an error.
*/

@@ -216,2 +217,19 @@ subscribe<T = any, TVariables extends OperationVariables = OperationVariables>(options: SubscriptionOptions<TVariables, T>): Observable<FetchResult<T>>;

/**
* Watches the cache store of the fragment according to the options specified
* and returns an `Observable`. We can subscribe to this
* `Observable` and receive updated results through an
* observer when the cache store changes.
*
* You must pass in a GraphQL document with a single fragment or a document
* with multiple fragments that represent what you are reading. If you pass
* in a document with multiple fragments then you must also specify a
* `fragmentName`.
*
* @since 3.10.0
* @param options - An object of type `WatchFragmentOptions` that allows
* the cache to identify the fragment and optionally specify whether to react
* to optimistic updates.
*/
watchFragment<TFragmentData = unknown, TVariables = OperationVariables>(options: WatchFragmentOptions<TFragmentData, TVariables>): Observable<WatchFragmentResult<TFragmentData>>;
/**
* Tries to read some data from the store in the shape of the provided

@@ -218,0 +236,0 @@ * GraphQL fragment without making a network request. This method will read a

@@ -18,9 +18,9 @@ import { __assign } from "tslib";

* This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries
* and mutations) to a GraphQL spec-compliant server over an {@link ApolloLink} instance,
* and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,
* receive results from the server and cache the results in a store. It also delivers updates
* to GraphQL queries through {@link Observable} instances.
* to GraphQL queries through `Observable` instances.
*/
var ApolloClient = /** @class */ (function () {
/**
* Constructs an instance of {@link ApolloClient}.
* Constructs an instance of `ApolloClient`.
*

@@ -85,2 +85,3 @@ * @example

this.mutate = this.mutate.bind(this);
this.watchFragment = this.watchFragment.bind(this);
this.resetStore = this.resetStore.bind(this);

@@ -188,4 +189,4 @@ this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);

* This watches the cache store of the query according to the options specified and
* returns an {@link ObservableQuery}. We can subscribe to this {@link ObservableQuery} and
* receive updated results through a GraphQL observer when the cache store changes.
* returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and
* receive updated results through an observer when the cache store changes.
*

@@ -223,3 +224,3 @@ * Note that this method is not an implementation of GraphQL subscriptions. Rather,

*
* @param options - An object of type {@link QueryOptions} that allows us to
* @param options - An object of type `QueryOptions` that allows us to
* describe how this query should be treated e.g. whether it should hit the

@@ -254,3 +255,3 @@ * server at all or just resolve from the cache, etc.

* This subscribes to a graphql subscription according to the options specified and returns an
* {@link Observable} which either emits received data or an error.
* `Observable` which either emits received data or an error.
*/

@@ -274,2 +275,21 @@ ApolloClient.prototype.subscribe = function (options) {

/**
* Watches the cache store of the fragment according to the options specified
* and returns an `Observable`. We can subscribe to this
* `Observable` and receive updated results through an
* observer when the cache store changes.
*
* You must pass in a GraphQL document with a single fragment or a document
* with multiple fragments that represent what you are reading. If you pass
* in a document with multiple fragments then you must also specify a
* `fragmentName`.
*
* @since 3.10.0
* @param options - An object of type `WatchFragmentOptions` that allows
* the cache to identify the fragment and optionally specify whether to react
* to optimistic updates.
*/
ApolloClient.prototype.watchFragment = function (options) {
return this.cache.watchFragment(options);
};
/**
* Tries to read some data from the store in the shape of the provided

@@ -276,0 +296,0 @@ * GraphQL fragment without making a network request. This method will read a

@@ -10,3 +10,3 @@ export type { ApolloClientOptions, DefaultOptions } from "./ApolloClient.js";

export { isApolloError, ApolloError } from "../errors/index.js";
export type { Transaction, DataProxy, InMemoryCacheConfig, ReactiveVar, TypePolicies, TypePolicy, FieldPolicy, FieldReadFunction, FieldMergeFunction, FieldFunctionOptions, PossibleTypesMap, } from "../cache/index.js";
export type { Transaction, DataProxy, InMemoryCacheConfig, ReactiveVar, TypePolicies, TypePolicy, FieldPolicy, FieldReadFunction, FieldMergeFunction, FieldFunctionOptions, PossibleTypesMap, WatchFragmentOptions, WatchFragmentResult, } from "../cache/index.js";
export { Cache, ApolloCache, InMemoryCache, MissingFieldError, defaultDataIdFromObject, makeVar, } from "../cache/index.js";

@@ -13,0 +13,0 @@ export * from "../cache/inmemory/types.js";

@@ -158,3 +158,3 @@ import type { DocumentNode } from "graphql";

/**
* Specifies the {@link FetchPolicy} to be used after this query has completed.
* Specifies the `FetchPolicy` to be used after this query has completed.
*

@@ -323,3 +323,3 @@ * @docGroup

/**
* Specifies the {@link ErrorPolicy} to be used for this operation
* Specifies the `ErrorPolicy` to be used for this operation
*/

@@ -346,3 +346,3 @@ errorPolicy?: ErrorPolicy;

/**
* A {@link MutationQueryReducersMap}, which is map from query names to mutation query reducers. Briefly, this map defines how to incorporate the results of the mutation into the results of queries that are currently being watched by your application.
* A `MutationQueryReducersMap`, which is map from query names to mutation query reducers. Briefly, this map defines how to incorporate the results of the mutation into the results of queries that are currently being watched by your application.
*/

@@ -349,0 +349,0 @@ updateQueries?: MutationQueryReducersMap<TData>;

@@ -431,3 +431,3 @@ 'use strict';

var version = "0.0.0-pr-11670-20240314104411";
var version = "0.0.0-pr-11698-20240415134929";

@@ -519,2 +519,6 @@ function maybe(thunk) {

function setErrorMessageHandler(handler) {
globals.global[ApolloErrorMessageHandler] = handler;
}
function loadErrorMessageHandler() {

@@ -525,20 +529,18 @@ var errorCodes = [];

}
if (!globals.global[ApolloErrorMessageHandler]) {
globals.global[ApolloErrorMessageHandler] = handler;
}
setErrorMessageHandler(handler);
for (var _a = 0, errorCodes_1 = errorCodes; _a < errorCodes_1.length; _a++) {
var codes = errorCodes_1[_a];
Object.assign(globals.global[ApolloErrorMessageHandler], codes);
Object.assign(handler, codes);
}
return globals.global[ApolloErrorMessageHandler];
function handler(message, args) {
if (typeof message === "number") {
var definition = globals.global[ApolloErrorMessageHandler][message];
if (!message || !(definition === null || definition === void 0 ? void 0 : definition.message))
return;
message = definition.message;
}
return args.reduce(function (msg, arg) { return msg.replace(/%[sdfo]/, String(arg)); }, String(message));
return handler;
}
var handler = (function (message, args) {
if (typeof message === "number") {
var definition = globals.global[ApolloErrorMessageHandler][message];
if (!message || !(definition === null || definition === void 0 ? void 0 : definition.message))
return;
message = definition.message;
}
}
return args.reduce(function (msg, arg) { return msg.replace(/%[sdfo]/, String(arg)); }, String(message));
});

@@ -556,2 +558,3 @@ function loadDevMessages() {

exports.loadErrorMessages = loadErrorMessages;
exports.setErrorMessageHandler = setErrorMessageHandler;
//# sourceMappingURL=dev.cjs.map
export { loadDevMessages } from "./loadDevMessages.js";
export { loadErrorMessageHandler } from "./loadErrorMessageHandler.js";
export { loadErrorMessages } from "./loadErrorMessages.js";
export { setErrorMessageHandler } from "./setErrorMessageHandler.js";
export type { ErrorMessageHandler } from "./setErrorMessageHandler.js";
//# sourceMappingURL=index.d.ts.map
export { loadDevMessages } from "./loadDevMessages.js";
export { loadErrorMessageHandler } from "./loadErrorMessageHandler.js";
export { loadErrorMessages } from "./loadErrorMessages.js";
export { setErrorMessageHandler } from "./setErrorMessageHandler.js";
//# sourceMappingURL=index.js.map
import type { ErrorCodes } from "../invariantErrorCodes.js";
export declare function loadErrorMessageHandler(...errorCodes: ErrorCodes[]): ((message: string | number, args: unknown[]) => string | undefined) & ErrorCodes;
import type { ErrorMessageHandler } from "./setErrorMessageHandler.js";
/**
* Injects Apollo Client's default error message handler into the application and
* also loads the error codes that are passed in as arguments.
*/
export declare function loadErrorMessageHandler(...errorCodes: ErrorCodes[]): ErrorMessageHandler & ErrorCodes;
//# sourceMappingURL=loadErrorMessageHandler.d.ts.map
import { global } from "../utilities/globals/index.js";
import { ApolloErrorMessageHandler } from "../utilities/globals/invariantWrappers.js";
import { setErrorMessageHandler } from "./setErrorMessageHandler.js";
/**
* Injects Apollo Client's default error message handler into the application and
* also loads the error codes that are passed in as arguments.
*/
export function loadErrorMessageHandler() {

@@ -8,20 +13,18 @@ var errorCodes = [];

}
if (!global[ApolloErrorMessageHandler]) {
global[ApolloErrorMessageHandler] = handler;
}
setErrorMessageHandler(handler);
for (var _a = 0, errorCodes_1 = errorCodes; _a < errorCodes_1.length; _a++) {
var codes = errorCodes_1[_a];
Object.assign(global[ApolloErrorMessageHandler], codes);
Object.assign(handler, codes);
}
return global[ApolloErrorMessageHandler];
function handler(message, args) {
if (typeof message === "number") {
var definition = global[ApolloErrorMessageHandler][message];
if (!message || !(definition === null || definition === void 0 ? void 0 : definition.message))
return;
message = definition.message;
}
return args.reduce(function (msg, arg) { return msg.replace(/%[sdfo]/, String(arg)); }, String(message));
return handler;
}
var handler = (function (message, args) {
if (typeof message === "number") {
var definition = global[ApolloErrorMessageHandler][message];
if (!message || !(definition === null || definition === void 0 ? void 0 : definition.message))
return;
message = definition.message;
}
}
return args.reduce(function (msg, arg) { return msg.replace(/%[sdfo]/, String(arg)); }, String(message));
});
//# sourceMappingURL=loadErrorMessageHandler.js.map
{
"name": "@apollo/client",
"version": "0.0.0-pr-11670-20240314104411",
"version": "0.0.0-pr-11698-20240415134929",
"description": "A fully-featured caching GraphQL client.",

@@ -70,16 +70,17 @@ "private": false,

"devDependencies": {
"@arethetypeswrong/cli": "0.15.1",
"@babel/parser": "7.24.0",
"@arethetypeswrong/cli": "0.15.2",
"@babel/parser": "7.24.1",
"@changesets/changelog-github": "0.5.0",
"@changesets/cli": "2.27.1",
"@graphql-tools/schema": "10.0.3",
"@graphql-tools/utils": "10.0.13",
"@microsoft/api-extractor": "7.42.3",
"@rollup/plugin-node-resolve": "11.2.1",
"@size-limit/esbuild-why": "11.0.2",
"@size-limit/preset-small-lib": "11.0.2",
"@size-limit/esbuild-why": "11.1.2",
"@size-limit/preset-small-lib": "11.1.2",
"@testing-library/jest-dom": "6.4.2",
"@testing-library/react": "14.2.1",
"@testing-library/react": "14.2.2",
"@testing-library/react-12": "npm:@testing-library/react@^12",
"@testing-library/user-event": "14.5.2",
"@tsconfig/node20": "20.1.2",
"@tsconfig/node20": "20.1.4",
"@types/bytes": "3.1.4",

@@ -90,14 +91,14 @@ "@types/fetch-mock": "7.3.8",

"@types/jest": "29.5.12",
"@types/lodash": "4.14.202",
"@types/node": "20.11.25",
"@types/lodash": "4.17.0",
"@types/node": "20.11.30",
"@types/node-fetch": "2.6.11",
"@types/react": "18.2.64",
"@types/react-dom": "18.2.21",
"@types/react": "18.2.73",
"@types/react-dom": "18.2.23",
"@types/relay-runtime": "14.1.23",
"@types/use-sync-external-store": "0.0.6",
"@typescript-eslint/eslint-plugin": "7.1.1",
"@typescript-eslint/parser": "7.1.1",
"@typescript-eslint/rule-tester": "7.1.1",
"@typescript-eslint/types": "7.1.1",
"@typescript-eslint/utils": "7.1.1",
"@typescript-eslint/eslint-plugin": "7.3.1",
"@typescript-eslint/parser": "7.3.1",
"@typescript-eslint/rule-tester": "7.3.1",
"@typescript-eslint/types": "7.3.1",
"@typescript-eslint/utils": "7.3.1",
"acorn": "8.11.3",

@@ -135,14 +136,14 @@ "blob-polyfill": "7.0.20220408",

"rxjs": "7.8.1",
"size-limit": "11.0.2",
"size-limit": "11.1.2",
"subscriptions-transport-ws": "0.11.0",
"terser": "5.29.1",
"terser": "5.29.2",
"ts-api-utils": "1.3.0",
"ts-jest": "29.1.2",
"ts-jest-resolver": "2.0.1",
"ts-morph": "21.0.1",
"ts-morph": "22.0.0",
"ts-node": "10.9.2",
"typedoc": "0.25.0",
"typescript": "5.4.2",
"typescript": "5.4.3",
"wait-for-observables": "1.0.3",
"web-streams-polyfill": "3.3.3",
"web-streams-polyfill": "4.0.0",
"whatwg-fetch": "3.6.20"

@@ -149,0 +150,0 @@ },

@@ -10,3 +10,3 @@ 'use strict';

var utilities = require('../../utilities');
var equality = require('@wry/equality');
var equal = require('@wry/equality');
var errors = require('../../errors');

@@ -18,2 +18,4 @@ var core = require('../../core');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
function _interopNamespace(e) {

@@ -32,2 +34,3 @@ if (e && e.__esModule) return e;

var React__namespace = /*#__PURE__*/_interopNamespace(React);
var equal__default = /*#__PURE__*/_interopDefaultLegacy(equal);

@@ -92,3 +95,3 @@ function useApolloClient(override) {

var ref = React__namespace.useRef();
if (!ref.current || !equality.equal(ref.current.deps, deps)) {
if (!ref.current || !equal.equal(ref.current.deps, deps)) {
ref.current = { value: memoFn(), deps: deps };

@@ -233,3 +236,3 @@ }

previousResult.networkStatus === result.networkStatus &&
equality.equal(previousResult.data, result.data)) {
equal.equal(previousResult.data, result.data)) {
return;

@@ -248,3 +251,3 @@ }

(previousResult && previousResult.loading) ||
!equality.equal(error, previousResult.error)) {
!equal.equal(error, previousResult.error)) {
_this.setResult({

@@ -275,3 +278,3 @@ data: (previousResult && previousResult.data),

var currentWatchQueryOptions = this.watchQueryOptions;
if (!equality.equal(watchQueryOptions, currentWatchQueryOptions)) {
if (!equal.equal(watchQueryOptions, currentWatchQueryOptions)) {
this.watchQueryOptions = watchQueryOptions;

@@ -555,3 +558,3 @@ if (currentWatchQueryOptions && this.observable) {

};
if (ref.current.isMounted && !equality.equal(ref.current.result, result_1)) {
if (ref.current.isMounted && !equal.equal(ref.current.result, result_1)) {
setResult((ref.current.result = result_1));

@@ -576,3 +579,3 @@ }

};
if (!equality.equal(ref.current.result, result_2)) {
if (!equal.equal(ref.current.result, result_2)) {
setResult((ref.current.result = result_2));

@@ -666,3 +669,3 @@ }

!(options === null || options === void 0 ? void 0 : options.skip) !== !((_c = ref.current.options) === null || _c === void 0 ? void 0 : _c.skip) ||
!equality.equal(options === null || options === void 0 ? void 0 : options.variables, (_d = ref.current.options) === null || _d === void 0 ? void 0 : _d.variables))) ||
!equal.equal(options === null || options === void 0 ? void 0 : options.variables, (_d = ref.current.options) === null || _d === void 0 ? void 0 : _d.variables))) ||
canResetObservableRef.current) {

@@ -771,17 +774,23 @@ setResult({

});
var stableOptions = useDeepMemo(function () { return options; }, [options]);
React__namespace.useMemo(function () {
resultRef.current = diffToResult(cache.diff(diffOptions));
}, [diffOptions, cache]);
var getSnapshot = React__namespace.useCallback(function () { return resultRef.current; }, []);
return useSyncExternalStore(React__namespace.useCallback(function (forceUpdate) {
var lastTimeout = 0;
var unsubscribe = cache.watch(tslib.__assign(tslib.__assign({}, diffOptions), { immediate: true, callback: function (diff) {
if (!equality.equal(diff.result, resultRef.current.data)) {
resultRef.current = diffToResult(diff);
clearTimeout(lastTimeout);
lastTimeout = setTimeout(forceUpdate);
}
} }));
var subscription = cache.watchFragment(stableOptions).subscribe({
next: function (result) {
if (equal__default(result, resultRef.current))
return;
resultRef.current = result;
clearTimeout(lastTimeout);
lastTimeout = setTimeout(forceUpdate);
},
});
return function () {
unsubscribe();
subscription.unsubscribe();
clearTimeout(lastTimeout);
};
}, [cache, diffOptions]), getSnapshot, getSnapshot);
}, [cache, stableOptions]), getSnapshot, getSnapshot);
}

@@ -841,2 +850,8 @@ function diffToResult(diff) {

}, [queryRef]);
React__namespace.useEffect(function () {
if (queryRef.disposed) {
suspenseCache.add(cacheKey, queryRef);
queryRef.reinitialize();
}
});
var skipResult = React__namespace.useMemo(function () {

@@ -949,2 +964,7 @@ var error = toApolloError(queryRef.result);

}
React__namespace.useEffect(function () {
if (queryRef.disposed) {
suspenseCache.add(cacheKey, queryRef);
}
});
var fetchMore = React__namespace.useCallback(function (options) {

@@ -960,2 +980,3 @@ var promise = queryRef.fetchMore(options);

}, [queryRef]);
React__namespace.useEffect(function () { return queryRef.softRetain(); }, [queryRef]);
return [

@@ -1019,2 +1040,8 @@ didFetchResult.current ? wrappedQueryRef : void 0,

function useQueryRefHandlers(queryRef) {
var unwrapped = internal.unwrapQueryRef(queryRef);
return wrapHook("useQueryRefHandlers", _useQueryRefHandlers, unwrapped ?
unwrapped["observable"]
: useApolloClient())(queryRef);
}
function _useQueryRefHandlers(queryRef) {
var _a = React__namespace.useState(queryRef), previousQueryRef = _a[0], setPreviousQueryRef = _a[1];

@@ -1044,3 +1071,6 @@ var _b = React__namespace.useState(queryRef), wrappedQueryRef = _b[0], setWrappedQueryRef = _b[1];

function useReadQuery(queryRef) {
return wrapHook("useReadQuery", _useReadQuery, internal.unwrapQueryRef(queryRef)["observable"])(queryRef);
var unwrapped = internal.unwrapQueryRef(queryRef);
return wrapHook("useReadQuery", _useReadQuery, unwrapped ?
unwrapped["observable"]
: useApolloClient())(queryRef);
}

@@ -1054,3 +1084,8 @@ function _useReadQuery(queryRef) {

}
React__namespace.useEffect(function () { return internalQueryRef.retain(); }, [internalQueryRef]);
React__namespace.useEffect(function () {
if (internalQueryRef.disposed) {
internalQueryRef.reinitialize();
}
return internalQueryRef.retain();
}, [internalQueryRef]);
var promise = useSyncExternalStore(React__namespace.useCallback(function (forceUpdate) {

@@ -1057,0 +1092,0 @@ return internalQueryRef.listen(function (promise) {

@@ -1,2 +0,2 @@

import type { useQuery, useSuspenseQuery, useBackgroundQuery, useReadQuery, useFragment } from "../index.js";
import type { useQuery, useSuspenseQuery, useBackgroundQuery, useReadQuery, useFragment, useQueryRefHandlers } from "../index.js";
import type { ApolloClient } from "../../../core/ApolloClient.js";

@@ -10,2 +10,3 @@ import type { ObservableQuery } from "../../../core/ObservableQuery.js";

useFragment: typeof useFragment;
useQueryRefHandlers: typeof useQueryRefHandlers;
}

@@ -12,0 +13,0 @@ /**

@@ -41,2 +41,15 @@ import { __spreadArray } from "tslib";

}
// Handle strict mode where the query ref might be disposed when useEffect
// runs twice. We add the queryRef back in the suspense cache so that the next
// render will reuse this queryRef rather than initializing a new instance.
// This also prevents issues where rerendering useBackgroundQuery after the
// queryRef has been disposed, either automatically or by unmounting
// useReadQuery will ensure the same queryRef is maintained.
React.useEffect(function () {
if (queryRef.disposed) {
suspenseCache.add(cacheKey, queryRef);
}
// Omitting the deps is intentional. This avoids stale closures and the
// conditional ensures we aren't running the logic on each render.
});
var fetchMore = React.useCallback(function (options) {

@@ -52,2 +65,3 @@ var promise = queryRef.fetchMore(options);

}, [queryRef]);
React.useEffect(function () { return queryRef.softRetain(); }, [queryRef]);
return [

@@ -54,0 +68,0 @@ didFetchResult.current ? wrappedQueryRef : void 0,

@@ -9,3 +9,3 @@ import type { DeepPartial } from "../../utilities/index.js";

/**
* The instance of {@link ApolloClient} to use to look up the fragment.
* The instance of `ApolloClient` to use to look up the fragment.
*

@@ -12,0 +12,0 @@ * By default, the instance that's passed down via context is used, but you

import { __assign, __rest } from "tslib";
import * as React from "rehackt";
import { equal } from "@wry/equality";
import { mergeDeepArray } from "../../utilities/index.js";

@@ -8,2 +7,3 @@ import { useApolloClient } from "./useApolloClient.js";

import { useDeepMemo, useLazyRef, wrapHook } from "./internal/index.js";
import equal from "@wry/equality";
export function useFragment(options) {

@@ -21,2 +21,8 @@ return wrapHook("useFragment", _useFragment, useApolloClient(options.client))(options);

});
var stableOptions = useDeepMemo(function () { return options; }, [options]);
// Since .next is async, we need to make sure that we
// get the correct diff on the next render given new diffOptions
React.useMemo(function () {
resultRef.current = diffToResult(cache.diff(diffOptions));
}, [diffOptions, cache]);
// Used for both getSnapshot and getServerSnapshot

@@ -26,18 +32,20 @@ var getSnapshot = React.useCallback(function () { return resultRef.current; }, []);

var lastTimeout = 0;
var unsubscribe = cache.watch(__assign(__assign({}, diffOptions), { immediate: true, callback: function (diff) {
if (!equal(diff.result, resultRef.current.data)) {
resultRef.current = diffToResult(diff);
// If we get another update before we've re-rendered, bail out of
// the update and try again. This ensures that the relative timing
// between useQuery and useFragment stays roughly the same as
// fixed in https://github.com/apollographql/apollo-client/pull/11083
clearTimeout(lastTimeout);
lastTimeout = setTimeout(forceUpdate);
}
} }));
var subscription = cache.watchFragment(stableOptions).subscribe({
next: function (result) {
if (equal(result, resultRef.current))
return;
resultRef.current = result;
// If we get another update before we've re-rendered, bail out of
// the update and try again. This ensures that the relative timing
// between useQuery and useFragment stays roughly the same as
// fixed in https://github.com/apollographql/apollo-client/pull/11083
clearTimeout(lastTimeout);
lastTimeout = setTimeout(forceUpdate);
},
});
return function () {
unsubscribe();
subscription.unsubscribe();
clearTimeout(lastTimeout);
};
}, [cache, diffOptions]), getSnapshot, getSnapshot);
}, [cache, stableOptions]), getSnapshot, getSnapshot);
}

@@ -44,0 +52,0 @@ function diffToResult(diff) {

import * as React from "rehackt";
import { getWrappedPromise, unwrapQueryRef, updateWrappedQueryRef, wrapQueryRef, } from "../internal/index.js";
import { useApolloClient } from "./useApolloClient.js";
import { wrapHook } from "./internal/index.js";
/**

@@ -23,2 +25,12 @@ * A React hook that returns a `refetch` and `fetchMore` function for a given

export function useQueryRefHandlers(queryRef) {
var unwrapped = unwrapQueryRef(queryRef);
return wrapHook("useQueryRefHandlers", _useQueryRefHandlers, unwrapped ?
unwrapped["observable"]
// in the case of a "transported" queryRef object, we need to use the
// client that's available to us at the current position in the React tree
// that ApolloClient will then have the job to recreate a real queryRef from
// the transported object
: useApolloClient())(queryRef);
}
function _useQueryRefHandlers(queryRef) {
var _a = React.useState(queryRef), previousQueryRef = _a[0], setPreviousQueryRef = _a[1];

@@ -25,0 +37,0 @@ var _b = React.useState(queryRef), wrappedQueryRef = _b[0], setWrappedQueryRef = _b[1];

@@ -6,4 +6,12 @@ import * as React from "rehackt";

import { useSyncExternalStore } from "./useSyncExternalStore.js";
import { useApolloClient } from "./useApolloClient.js";
export function useReadQuery(queryRef) {
return wrapHook("useReadQuery", _useReadQuery, unwrapQueryRef(queryRef)["observable"])(queryRef);
var unwrapped = unwrapQueryRef(queryRef);
return wrapHook("useReadQuery", _useReadQuery, unwrapped ?
unwrapped["observable"]
// in the case of a "transported" queryRef object, we need to use the
// client that's available to us at the current position in the React tree
// that ApolloClient will then have the job to recreate a real queryRef from
// the transported object
: useApolloClient())(queryRef);
}

@@ -17,3 +25,12 @@ function _useReadQuery(queryRef) {

}
React.useEffect(function () { return internalQueryRef.retain(); }, [internalQueryRef]);
React.useEffect(function () {
// It may seem odd that we are trying to reinitialize the queryRef even
// though we reinitialize in render above, but this is necessary to
// handle strict mode where this useEffect will be run twice resulting in a
// disposed queryRef before the next render.
if (internalQueryRef.disposed) {
internalQueryRef.reinitialize();
}
return internalQueryRef.retain();
}, [internalQueryRef]);
var promise = useSyncExternalStore(React.useCallback(function (forceUpdate) {

@@ -20,0 +37,0 @@ return internalQueryRef.listen(function (promise) {

@@ -53,2 +53,29 @@ import { __assign, __spreadArray } from "tslib";

}, [queryRef]);
// This effect handles the case where strict mode causes the queryRef to get
// disposed early. Previously this was done by using a `setTimeout` inside the
// dispose function, but this could cause some issues in cases where someone
// might expect the queryRef to be disposed immediately. For example, when
// using the same client instance across multiple tests in a test suite, the
// `setTimeout` has the possibility of retaining the suspense cache entry for
// too long, which means that two tests might accidentally share the same
// `queryRef` instance. By immediately disposing, we can avoid this situation.
//
// Instead we can leverage the work done to allow the queryRef to "resume"
// after it has been disposed without executing an additional network request.
// This is done by calling the `initialize` function below.
React.useEffect(function () {
if (queryRef.disposed) {
// Calling the `dispose` function removes it from the suspense cache, so
// when the component rerenders, it instantiates a fresh query ref.
// We address this by adding the queryRef back to the suspense cache
// so that the lookup on the next render uses the existing queryRef rather
// than instantiating a new one.
suspenseCache.add(cacheKey, queryRef);
queryRef.reinitialize();
}
// We can omit the deps here to get a fresh closure each render since the
// conditional will prevent the logic from running in most cases. This
// should also be a touch faster since it should be faster to check the `if`
// statement than for React to compare deps on this effect.
});
var skipResult = React.useMemo(function () {

@@ -55,0 +82,0 @@ var error = toApolloError(queryRef.result);

@@ -10,4 +10,4 @@ import type { ApolloQueryResult, ObservableQuery, OperationVariables, WatchQueryOptions } from "../../../core/index.js";

/**
* A `QueryReference` is an opaque object returned by {@link useBackgroundQuery}.
* A child component reading the `QueryReference` via {@link useReadQuery} will
* A `QueryReference` is an opaque object returned by `useBackgroundQuery`.
* A child component reading the `QueryReference` via `useReadQuery` will
* suspend until the promise resolves.

@@ -55,3 +55,3 @@ */

*
* @alpha
* @since 3.9.0
*/

@@ -81,2 +81,3 @@ toPromise(): Promise<QueryReference<TData, TVariables>>;

private references;
private softReferences;
constructor(observable: ObservableQuery<TData, any>, options: InternalQueryReferenceOptions);

@@ -87,2 +88,3 @@ get disposed(): boolean;

retain(): () => void;
softRetain(): () => void;
didChangeOptions(watchQueryOptions: ObservedOptions): boolean;

@@ -89,0 +91,0 @@ applyOptions(watchQueryOptions: ObservedOptions): QueryRefPromise<TData>;

@@ -56,2 +56,3 @@ import { __assign } from "tslib";

this.references = 0;
this.softReferences = 0;
this.handleNext = this.handleNext.bind(this);

@@ -98,12 +99,13 @@ this.handleError = this.handleError.bind(this);

var originalFetchPolicy = this.watchQueryOptions.fetchPolicy;
var avoidNetworkRequests = originalFetchPolicy === "no-cache" || originalFetchPolicy === "standby";
try {
if (originalFetchPolicy !== "no-cache") {
if (avoidNetworkRequests) {
observable.silentSetOptions({ fetchPolicy: "standby" });
}
else {
observable.resetLastResults();
observable.silentSetOptions({ fetchPolicy: "cache-first" });
}
else {
observable.silentSetOptions({ fetchPolicy: "standby" });
}
this.subscribeToQuery();
if (originalFetchPolicy === "no-cache") {
if (avoidNetworkRequests) {
return;

@@ -129,5 +131,22 @@ }

_this.references--;
// Wait before fully disposing in case the app is running in strict mode.
if (!_this.references) {
_this.dispose();
}
};
};
InternalQueryReference.prototype.softRetain = function () {
var _this = this;
this.softReferences++;
var disposed = false;
return function () {
// Tracking if this has already been called helps ensure that
// multiple calls to this function won't decrement the reference
// counter more than it should. Subsequent calls just result in a noop.
if (disposed) {
return;
}
disposed = true;
_this.softReferences--;
setTimeout(function () {
if (!_this.references) {
if (!_this.softReferences && !_this.references) {
_this.dispose();

@@ -141,3 +160,4 @@ }

return OBSERVED_CHANGED_OPTIONS.some(function (option) {
return !equal(_this.watchQueryOptions[option], watchQueryOptions[option]);
return option in watchQueryOptions &&
!equal(_this.watchQueryOptions[option], watchQueryOptions[option]);
});

@@ -243,3 +263,3 @@ };

returnedPromise
.then(function (result) {
.then(function () {
// In the case of `fetchMore`, this promise is resolved before a cache

@@ -258,4 +278,12 @@ // result is emitted due to the fact that `fetchMore` sets a `no-cache`

if (_this.promise.status === "pending") {
_this.result = result;
(_a = _this.resolve) === null || _a === void 0 ? void 0 : _a.call(_this, result);
// Use the current result from the observable instead of the value
// resolved from the promise. This avoids issues in some cases where
// the raw resolved value should not be the emitted value, such as
// when a `fetchMore` call returns an empty array after it has
// reached the end of the list.
//
// See the following for more information:
// https://github.com/apollographql/apollo-client/issues/11642
_this.result = _this.observable.getCurrentResult();
(_a = _this.resolve) === null || _a === void 0 ? void 0 : _a.call(_this, _this.result);
}

@@ -262,0 +290,0 @@ });

@@ -22,3 +22,4 @@ import type { ObservableQuery } from "../../../core/index.js";

getQueryRef<TData = any>(cacheKey: CacheKey, createObservable: () => ObservableQuery<TData>): InternalQueryReference<TData>;
add(cacheKey: CacheKey, queryRef: InternalQueryReference<unknown>): void;
}
//# sourceMappingURL=SuspenseCache.d.ts.map

@@ -22,2 +22,6 @@ import { Trie } from "@wry/trie";

};
SuspenseCache.prototype.add = function (cacheKey, queryRef) {
var ref = this.queryRefs.lookupArray(cacheKey);
ref.current = queryRef;
};
return SuspenseCache;

@@ -24,0 +28,0 @@ }());

@@ -50,2 +50,3 @@ 'use strict';

this.references = 0;
this.softReferences = 0;
this.handleNext = this.handleNext.bind(this);

@@ -85,12 +86,13 @@ this.handleError = this.handleError.bind(this);

var originalFetchPolicy = this.watchQueryOptions.fetchPolicy;
var avoidNetworkRequests = originalFetchPolicy === "no-cache" || originalFetchPolicy === "standby";
try {
if (originalFetchPolicy !== "no-cache") {
if (avoidNetworkRequests) {
observable.silentSetOptions({ fetchPolicy: "standby" });
}
else {
observable.resetLastResults();
observable.silentSetOptions({ fetchPolicy: "cache-first" });
}
else {
observable.silentSetOptions({ fetchPolicy: "standby" });
}
this.subscribeToQuery();
if (originalFetchPolicy === "no-cache") {
if (avoidNetworkRequests) {
return;

@@ -116,4 +118,19 @@ }

_this.references--;
if (!_this.references) {
_this.dispose();
}
};
};
InternalQueryReference.prototype.softRetain = function () {
var _this = this;
this.softReferences++;
var disposed = false;
return function () {
if (disposed) {
return;
}
disposed = true;
_this.softReferences--;
setTimeout(function () {
if (!_this.references) {
if (!_this.softReferences && !_this.references) {
_this.dispose();

@@ -127,3 +144,4 @@ }

return OBSERVED_CHANGED_OPTIONS.some(function (option) {
return !equality.equal(_this.watchQueryOptions[option], watchQueryOptions[option]);
return option in watchQueryOptions &&
!equality.equal(_this.watchQueryOptions[option], watchQueryOptions[option]);
});

@@ -214,8 +232,8 @@ };

returnedPromise
.then(function (result) {
.then(function () {
setTimeout(function () {
var _a;
if (_this.promise.status === "pending") {
_this.result = result;
(_a = _this.resolve) === null || _a === void 0 ? void 0 : _a.call(_this, result);
_this.result = _this.observable.getCurrentResult();
(_a = _this.resolve) === null || _a === void 0 ? void 0 : _a.call(_this, _this.result);
}

@@ -273,2 +291,6 @@ });

};
SuspenseCache.prototype.add = function (cacheKey, queryRef) {
var ref = this.queryRefs.lookupArray(cacheKey);
ref.current = queryRef;
};
return SuspenseCache;

@@ -275,0 +297,0 @@ }());

@@ -111,3 +111,3 @@ import type { ApolloClient, DefaultContext, DocumentNode, ErrorPolicy, OperationVariables, RefetchWritePolicy, TypedDocumentNode, WatchQueryFetchPolicy } from "../../core/index.js";

* A function that will begin loading a query when called. It's result can be
* read by {@link useReadQuery} which will suspend until the query is loaded.
* read by `useReadQuery` which will suspend until the query is loaded.
* This is useful when you want to start loading a query as early as possible

@@ -138,3 +138,3 @@ * outside of a React component.

/**
* A function that will begin loading a query when called. It's result can be read by {@link useReadQuery} which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
* A function that will begin loading a query when called. It's result can be read by `useReadQuery` which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
*

@@ -163,3 +163,3 @@ * @example

/**
* A function that will begin loading a query when called. It's result can be read by {@link useReadQuery} which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
* A function that will begin loading a query when called. It's result can be read by `useReadQuery` which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
*

@@ -191,3 +191,3 @@ * @example

/**
* A function that will begin loading a query when called. It's result can be read by {@link useReadQuery} which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
* A function that will begin loading a query when called. It's result can be read by `useReadQuery` which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
*

@@ -218,3 +218,3 @@ * @example

/**
* A function that will begin loading a query when called. It's result can be read by {@link useReadQuery} which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
* A function that will begin loading a query when called. It's result can be read by `useReadQuery` which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
*

@@ -245,3 +245,3 @@ * @example

/**
* A function that will begin loading a query when called. It's result can be read by {@link useReadQuery} which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
* A function that will begin loading a query when called. It's result can be read by `useReadQuery` which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.
*

@@ -287,3 +287,2 @@ * @example

* @since 3.9.0
* @alpha
*/

@@ -290,0 +289,0 @@ export declare function createQueryPreloader(client: ApolloClient<any>): PreloadQueryFunction;

@@ -20,3 +20,2 @@ import { __assign } from "tslib";

* @since 3.9.0
* @alpha
*/

@@ -23,0 +22,0 @@ export function createQueryPreloader(client) {

@@ -24,3 +24,3 @@ import type * as ReactTypes from "react";

/**
* The instance of {@link ApolloClient} to use to execute the query.
* The instance of `ApolloClient` to use to execute the query.
*

@@ -270,3 +270,3 @@ * By default, the instance that's passed down via context is used, but you can provide a different instance here.

/**
* The instance of {@link ApolloClient} to use to execute the query.
* The instance of `ApolloClient` to use to execute the query.
*

@@ -421,3 +421,3 @@ * By default, the instance that's passed down via context is used, but you can provide a different instance here.

/**
* The instance of {@link ApolloClient} to use to execute the query.
* The instance of `ApolloClient` to use to execute the query.
*

@@ -424,0 +424,0 @@ * By default, the instance that's passed down via context is used, but you can provide a different instance here.

@@ -43,3 +43,3 @@ export interface QueryOptionsDocumentation {

/**
* Specifies the {@link FetchPolicy} to be used after this query has completed.
* Specifies the `FetchPolicy` to be used after this query has completed.
*

@@ -155,3 +155,3 @@ * @docGroup 3. Caching options

/**
* The instance of {@link ApolloClient} to use to execute the query.
* The instance of `ApolloClient` to use to execute the query.
*

@@ -345,3 +345,3 @@ * By default, the instance that's passed down via context is used, but you

/**
* A {@link MutationQueryReducersMap}, which is map from query names to
* A `MutationQueryReducersMap`, which is map from query names to
* mutation query reducers. Briefly, this map defines how to incorporate the

@@ -494,3 +494,3 @@ * results of the mutation into the results of queries that are currently

/**
* Specifies the {@link ErrorPolicy} to be used for this operation
* Specifies the `ErrorPolicy` to be used for this operation
*/

@@ -497,0 +497,0 @@ errorPolicy: unknown;

@@ -12,2 +12,5 @@ 'use strict';

var cache = require('../../cache');
var schema = require('@graphql-tools/schema');
var graphql = require('graphql');
var utils = require('@graphql-tools/utils');

@@ -300,2 +303,242 @@ function requestToKey(request, addTypename) {

var takeRandom = function (arr) { return arr[Math.floor(Math.random() * arr.length)]; };
var createMockSchema = function (staticSchema, mocks) {
var _a;
var getType = function (typeName) {
var type = staticSchema.getType(typeName);
if (!type || !(graphql.isObjectType(type) || graphql.isInterfaceType(type))) {
throw new Error("".concat(typeName, " does not exist on schema or is not an object or interface"));
}
return type;
};
var getFieldType = function (typeName, fieldName) {
if (fieldName === "__typename") {
return graphql.GraphQLString;
}
var type = getType(typeName);
var field = type.getFields()[fieldName];
if (!field) {
throw new Error("".concat(fieldName, " does not exist on type ").concat(typeName));
}
return field.type;
};
var generateValueFromType = function (fieldType) {
var nullableType = graphql.getNullableType(fieldType);
if (graphql.isScalarType(nullableType)) {
var mockFn = mocks[nullableType.name];
if (typeof mockFn !== "function") {
throw new Error("No mock defined for type \"".concat(nullableType.name, "\""));
}
return mockFn();
}
else if (graphql.isEnumType(nullableType)) {
var mockFn = mocks[nullableType.name];
if (typeof mockFn === "function")
return mockFn();
var values = nullableType.getValues().map(function (v) { return v.value; });
return takeRandom(values);
}
else if (graphql.isObjectType(nullableType)) {
return {};
}
else if (graphql.isListType(nullableType)) {
return tslib.__spreadArray([], new Array(2), true).map(function () {
return generateValueFromType(nullableType.ofType);
});
}
else if (graphql.isAbstractType(nullableType)) {
var mock = mocks[nullableType.name];
var typeName = void 0;
var values = {};
if (!mock) {
typeName = takeRandom(staticSchema.getPossibleTypes(nullableType).map(function (t) { return t.name; }));
}
else if (typeof mock === "function") {
var mockRes = mock();
if (mockRes === null)
return null;
if (!utilities.isNonNullObject(mockRes)) {
throw new Error("Value returned by the mock for ".concat(nullableType.name, " is not an object or null"));
}
values = mockRes;
if (typeof values["__typename"] !== "string") {
throw new Error("Please return a __typename in \"".concat(nullableType.name, "\""));
}
typeName = values["__typename"];
}
else if (utilities.isNonNullObject(mock) &&
typeof mock["__typename"] === "function") {
var mockRes = mock["__typename"]();
if (typeof mockRes !== "string") {
throw new Error("'__typename' returned by the mock for abstract type ".concat(nullableType.name, " is not a string"));
}
typeName = mockRes;
}
else {
throw new Error("Please return a __typename in \"".concat(nullableType.name, "\""));
}
return typeName;
}
else {
throw new Error("".concat(nullableType, " not implemented"));
}
};
var isRootType = function (type, schema) {
var rootTypeNames = utils.getRootTypeNames(schema);
return rootTypeNames.has(type.name);
};
var mockResolver = function (source, args, contex, info) {
var defaultResolvedValue = graphql.defaultFieldResolver(source, args, contex, info);
if (defaultResolvedValue !== undefined)
return defaultResolvedValue;
if (isRootType(info.parentType, info.schema)) {
return {
typeName: info.parentType.name,
key: "ROOT",
fieldName: info.fieldName,
fieldArgs: args,
};
}
if (defaultResolvedValue === undefined) {
var fieldType = getFieldType(info.parentType.name, info.fieldName);
return generateValueFromType(fieldType);
}
return undefined;
};
return utils.mapSchema(staticSchema, (_a = {},
_a[utils.MapperKind.OBJECT_FIELD] = function (fieldConfig) {
var newFieldConfig = tslib.__assign({}, fieldConfig);
var oldResolver = fieldConfig.resolve;
if (!oldResolver) {
newFieldConfig.resolve = mockResolver;
}
return newFieldConfig;
},
_a[utils.MapperKind.ABSTRACT_TYPE] = function (type) {
if (type.resolveType != null && type.resolveType.length) {
return;
}
var typeResolver = function (typename) {
return typename;
};
if (graphql.isUnionType(type)) {
return new graphql.GraphQLUnionType(tslib.__assign(tslib.__assign({}, type.toConfig()), { resolveType: typeResolver }));
}
else {
return new graphql.GraphQLInterfaceType(tslib.__assign(tslib.__assign({}, type.toConfig()), { resolveType: typeResolver }));
}
},
_a));
};
var createTestSchema = function (schemaWithTypeDefs, options) {
var _a;
var targetResolvers = tslib.__assign({}, options.resolvers);
var targetSchema = schema.addResolversToSchema({
schema: createMockSchema(schemaWithTypeDefs, (_a = options.scalars) !== null && _a !== void 0 ? _a : {}),
resolvers: targetResolvers,
});
var fns = {
add: function (_a) {
var newResolvers = _a.resolvers;
targetResolvers = tslib.__assign(tslib.__assign({}, targetResolvers), newResolvers);
targetSchema = schema.addResolversToSchema({
schema: targetSchema,
resolvers: targetResolvers,
});
return targetSchema;
},
fork: function (_a) {
var _b = _a === void 0 ? {} : _a, newResolvers = _b.resolvers;
return createTestSchema(targetSchema, {
resolvers: newResolvers !== null && newResolvers !== void 0 ? newResolvers : targetResolvers,
scalars: options.scalars,
});
},
reset: function () {
targetSchema = schema.addResolversToSchema({
schema: schemaWithTypeDefs,
resolvers: options.resolvers,
});
},
};
var schema$1 = new Proxy(targetSchema, {
get: function (_target, p) {
if (p in fns) {
return Reflect.get(fns, p);
}
var property = Reflect.get(targetSchema, p);
if (typeof property === "function") {
return property.bind(targetSchema);
}
return property;
},
});
return schema$1;
};
function withCleanup(item, cleanup) {
var _a;
return tslib.__assign(tslib.__assign({}, item), (_a = {}, _a[Symbol.dispose] = function () {
cleanup(item);
if (Symbol.dispose in item) {
item[Symbol.dispose]();
}
}, _a));
}
var createSchemaFetch = function (schema, mockFetchOpts) {
if (mockFetchOpts === void 0) { mockFetchOpts = { validate: true }; }
var prevFetch = window.fetch;
var mockFetch = function (_uri, options) {
return new Promise(function (resolve) { return tslib.__awaiter(void 0, void 0, void 0, function () {
var body, document, validationErrors, result, stringifiedResult;
return tslib.__generator(this, function (_a) {
switch (_a.label) {
case 0:
body = JSON.parse(options.body);
document = core$1.gql(body.query);
if (mockFetchOpts.validate) {
validationErrors = [];
try {
validationErrors = graphql.validate(schema, document);
}
catch (e) {
validationErrors = [
new core$1.ApolloError({ graphQLErrors: [e] }),
];
}
if ((validationErrors === null || validationErrors === void 0 ? void 0 : validationErrors.length) > 0) {
return [2 , resolve(new Response(JSON.stringify({ errors: validationErrors })))];
}
}
return [4 , graphql.execute({
schema: schema,
document: document,
variableValues: body.variables,
operationName: body.operationName,
})];
case 1:
result = _a.sent();
stringifiedResult = JSON.stringify(result);
resolve(new Response(stringifiedResult));
return [2 ];
}
});
}); });
};
function mockGlobal() {
window.fetch = mockFetch;
var restore = function () {
if (window.fetch === mockFetch) {
window.fetch = prevFetch;
}
};
return withCleanup({ restore: restore }, restore);
}
return Object.assign(mockFetch, {
mockGlobal: mockGlobal,
});
};
function wrapTestFunction(fn, consoleMethodName) {

@@ -346,2 +589,4 @@ return function () {

exports.createMockClient = createMockClient;
exports.createSchemaFetch = createSchemaFetch;
exports.createTestSchema = createTestSchema;
exports.itAsync = itAsync;

@@ -348,0 +593,0 @@ exports.mockObservableLink = mockObservableLink;

@@ -8,3 +8,5 @@ export type { MockedResponse, MockLinkOptions, ResultFunction, } from "./mocking/mockLink.js";

export { wait, tick } from "./wait.js";
export { createTestSchema } from "./createTestSchema.js";
export { createSchemaFetch } from "./createSchemaFetch.js";
export * from "./withConsoleSpy.js";
//# sourceMappingURL=index.d.ts.map

@@ -7,3 +7,5 @@ export { MockLink, mockSingleLink } from "./mocking/mockLink.js";

export { wait, tick } from "./wait.js";
export { createTestSchema } from "./createTestSchema.js";
export { createSchemaFetch } from "./createSchemaFetch.js";
export * from "./withConsoleSpy.js";
//# sourceMappingURL=index.js.map

@@ -7,3 +7,3 @@ 'use strict';

var version = "0.0.0-pr-11670-20240314104411";
var version = "0.0.0-pr-11698-20240415134929";

@@ -10,0 +10,0 @@ function maybe(thunk) {

@@ -59,3 +59,3 @@ import { InvariantError } from "ts-invariant";

[ApolloErrorMessageHandler]?: {
(message: string | number, args: unknown[]): string | undefined;
(message: string | number, args: string[]): string | undefined;
} & ErrorCodes;

@@ -62,0 +62,0 @@ }

@@ -1,2 +0,2 @@

export var version = "0.0.0-pr-11670-20240314104411";
export var version = "0.0.0-pr-11698-20240415134929";
//# sourceMappingURL=version.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc