inital upload

This commit is contained in:
jackbeeby
2025-05-15 13:35:49 +10:00
commit 8c53ff1000
9092 changed files with 1833300 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
import { WeakCache, StrongCache } from "@wry/caches";
/**
* @internal
* A version of WeakCache that will auto-schedule a cleanup of the cache when
* a new item is added and the cache reached maximum size.
* Throttled to once per 100ms.
*
* @privateRemarks
* Should be used throughout the rest of the codebase instead of WeakCache,
* with the notable exception of usage in `wrap` from `optimism` - that one
* already handles cleanup and should remain a `WeakCache`.
*/
export declare const AutoCleanedWeakCache: typeof WeakCache;
/**
* @internal
*/
export type AutoCleanedWeakCache<K extends object, V> = WeakCache<K, V>;
/**
* @internal
* A version of StrongCache that will auto-schedule a cleanup of the cache when
* a new item is added and the cache reached maximum size.
* Throttled to once per 100ms.
*
* @privateRemarks
* Should be used throughout the rest of the codebase instead of StrongCache,
* with the notable exception of usage in `wrap` from `optimism` - that one
* already handles cleanup and should remain a `StrongCache`.
*/
export declare const AutoCleanedStrongCache: typeof StrongCache;
/**
* @internal
*/
export type AutoCleanedStrongCache<K, V> = StrongCache<K, V>;
//# sourceMappingURL=caches.d.ts.map

View File

@@ -0,0 +1,69 @@
import { WeakCache, StrongCache } from "@wry/caches";
var scheduledCleanup = new WeakSet();
function schedule(cache) {
if (cache.size <= (cache.max || -1)) {
return;
}
if (!scheduledCleanup.has(cache)) {
scheduledCleanup.add(cache);
setTimeout(function () {
cache.clean();
scheduledCleanup.delete(cache);
}, 100);
}
}
/**
* @internal
* A version of WeakCache that will auto-schedule a cleanup of the cache when
* a new item is added and the cache reached maximum size.
* Throttled to once per 100ms.
*
* @privateRemarks
* Should be used throughout the rest of the codebase instead of WeakCache,
* with the notable exception of usage in `wrap` from `optimism` - that one
* already handles cleanup and should remain a `WeakCache`.
*/
export var AutoCleanedWeakCache = function (max, dispose) {
/*
Some builds of `WeakCache` are function prototypes, some are classes.
This library still builds with an ES5 target, so we can't extend the
real classes.
Instead, we have to use this workaround until we switch to a newer build
target.
*/
var cache = new WeakCache(max, dispose);
cache.set = function (key, value) {
var ret = WeakCache.prototype.set.call(this, key, value);
schedule(this);
return ret;
};
return cache;
};
/**
* @internal
* A version of StrongCache that will auto-schedule a cleanup of the cache when
* a new item is added and the cache reached maximum size.
* Throttled to once per 100ms.
*
* @privateRemarks
* Should be used throughout the rest of the codebase instead of StrongCache,
* with the notable exception of usage in `wrap` from `optimism` - that one
* already handles cleanup and should remain a `StrongCache`.
*/
export var AutoCleanedStrongCache = function (max, dispose) {
/*
Some builds of `StrongCache` are function prototypes, some are classes.
This library still builds with an ES5 target, so we can't extend the
real classes.
Instead, we have to use this workaround until we switch to a newer build
target.
*/
var cache = new StrongCache(max, dispose);
cache.set = function (key, value) {
var ret = StrongCache.prototype.set.call(this, key, value);
schedule(this);
return ret;
};
return cache;
};
//# sourceMappingURL=caches.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"caches.js","sourceRoot":"","sources":["../../../src/utilities/caching/caches.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAOrD,IAAM,gBAAgB,GAAG,IAAI,OAAO,EAAkB,CAAC;AACvD,SAAS,QAAQ,CAAC,KAAqB;IACrC,IAAI,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;QACpC,OAAO;IACT,CAAC;IACD,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QACjC,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC5B,UAAU,CAAC;YACT,KAAK,CAAC,KAAK,EAAE,CAAC;YACd,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACjC,CAAC,EAAE,GAAG,CAAC,CAAC;IACV,CAAC;AACH,CAAC;AACD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,IAAM,oBAAoB,GAAG,UAClC,GAAwB,EACxB,OAAsD;IAEtD;;;;;;MAME;IACF,IAAM,KAAK,GAAG,IAAI,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1C,KAAK,CAAC,GAAG,GAAG,UAAU,GAAQ,EAAE,KAAU;QACxC,IAAM,GAAG,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3D,QAAQ,CAAC,IAA6B,CAAC,CAAC;QACxC,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;IACF,OAAO,KAAK,CAAC;AACf,CAA4B,CAAC;AAM7B;;;;;;;;;;GAUG;AACH,MAAM,CAAC,IAAM,sBAAsB,GAAG,UACpC,GAAwB,EACxB,OAAsD;IAEtD;;;;;;MAME;IACF,IAAM,KAAK,GAAG,IAAI,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC5C,KAAK,CAAC,GAAG,GAAG,UAAU,GAAQ,EAAE,KAAU;QACxC,IAAM,GAAG,GAAG,WAAW,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;QAC7D,QAAQ,CAAC,IAA6B,CAAC,CAAC;QACxC,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;IACF,OAAO,KAAK,CAAC;AACf,CAA8B,CAAC","sourcesContent":["import { WeakCache, StrongCache } from \"@wry/caches\";\n\ninterface CleanableCache {\n size: number;\n max?: number;\n clean: () => void;\n}\nconst scheduledCleanup = new WeakSet<CleanableCache>();\nfunction schedule(cache: CleanableCache) {\n if (cache.size <= (cache.max || -1)) {\n return;\n }\n if (!scheduledCleanup.has(cache)) {\n scheduledCleanup.add(cache);\n setTimeout(() => {\n cache.clean();\n scheduledCleanup.delete(cache);\n }, 100);\n }\n}\n/**\n * @internal\n * A version of WeakCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of WeakCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `WeakCache`.\n */\nexport const AutoCleanedWeakCache = function (\n max?: number | undefined,\n dispose?: ((value: any, key: any) => void) | undefined\n) {\n /*\n Some builds of `WeakCache` are function prototypes, some are classes.\n This library still builds with an ES5 target, so we can't extend the\n real classes.\n Instead, we have to use this workaround until we switch to a newer build\n target.\n */\n const cache = new WeakCache(max, dispose);\n cache.set = function (key: any, value: any) {\n const ret = WeakCache.prototype.set.call(this, key, value);\n schedule(this as any as CleanableCache);\n return ret;\n };\n return cache;\n} as any as typeof WeakCache;\n/**\n * @internal\n */\nexport type AutoCleanedWeakCache<K extends object, V> = WeakCache<K, V>;\n\n/**\n * @internal\n * A version of StrongCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of StrongCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `StrongCache`.\n */\nexport const AutoCleanedStrongCache = function (\n max?: number | undefined,\n dispose?: ((value: any, key: any) => void) | undefined\n) {\n /*\n Some builds of `StrongCache` are function prototypes, some are classes.\n This library still builds with an ES5 target, so we can't extend the\n real classes.\n Instead, we have to use this workaround until we switch to a newer build\n target.\n */\n const cache = new StrongCache(max, dispose);\n cache.set = function (key: any, value: any) {\n const ret = StrongCache.prototype.set.call(this, key, value);\n schedule(this as any as CleanableCache);\n return ret;\n };\n return cache;\n} as any as typeof StrongCache;\n/**\n * @internal\n */\nexport type AutoCleanedStrongCache<K, V> = StrongCache<K, V>;\n"]}

View File

@@ -0,0 +1,76 @@
declare const globalCaches: {
print?: () => number;
parser?: () => number;
canonicalStringify?: () => number;
};
export declare function registerGlobalCache(name: keyof typeof globalCaches, getSize: () => number): void;
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export declare const getApolloClientMemoryInternals: (() => {
limits: {
[k: string]: number;
};
sizes: {
cache?: {
fragmentQueryDocuments: number | undefined;
} | undefined;
addTypenameDocumentTransform?: {
cache: number;
}[] | undefined;
inMemoryCache?: {
executeSelectionSet: number | undefined;
executeSubSelectedArray: number | undefined;
maybeBroadcastWatch: number | undefined;
} | undefined;
fragmentRegistry?: {
findFragmentSpreads: number | undefined;
lookup: number | undefined;
transform: number | undefined;
} | undefined;
print: number | undefined;
parser: number | undefined;
canonicalStringify: number | undefined;
links: unknown[];
queryManager: {
getDocumentInfo: number;
documentTransforms: {
cache: number;
}[];
};
};
}) | undefined;
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export declare const getInMemoryCacheMemoryInternals: (() => {
addTypenameDocumentTransform: {
cache: number;
}[];
inMemoryCache: {
executeSelectionSet: number | undefined;
executeSubSelectedArray: number | undefined;
maybeBroadcastWatch: number | undefined;
};
fragmentRegistry: {
findFragmentSpreads: number | undefined;
lookup: number | undefined;
transform: number | undefined;
};
cache: {
fragmentQueryDocuments: number | undefined;
};
}) | undefined;
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export declare const getApolloCacheMemoryInternals: (() => {
cache: {
fragmentQueryDocuments: number | undefined;
};
}) | undefined;
export {};
//# sourceMappingURL=getMemoryInternals.d.ts.map

View File

@@ -0,0 +1,112 @@
import { __assign, __spreadArray } from "tslib";
import { cacheSizes } from "./sizes.js";
var globalCaches = {};
export function registerGlobalCache(name, getSize) {
globalCaches[name] = getSize;
}
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export var getApolloClientMemoryInternals = globalThis.__DEV__ !== false ?
_getApolloClientMemoryInternals
: undefined;
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export var getInMemoryCacheMemoryInternals = globalThis.__DEV__ !== false ?
_getInMemoryCacheMemoryInternals
: undefined;
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export var getApolloCacheMemoryInternals = globalThis.__DEV__ !== false ?
_getApolloCacheMemoryInternals
: undefined;
function getCurrentCacheSizes() {
// `defaultCacheSizes` is a `const enum` that will be inlined during build, so we have to reconstruct it's shape here
var defaults = {
parser: 1000 /* defaultCacheSizes["parser"] */,
canonicalStringify: 1000 /* defaultCacheSizes["canonicalStringify"] */,
print: 2000 /* defaultCacheSizes["print"] */,
"documentTransform.cache": 2000 /* defaultCacheSizes["documentTransform.cache"] */,
"queryManager.getDocumentInfo": 2000 /* defaultCacheSizes["queryManager.getDocumentInfo"] */,
"PersistedQueryLink.persistedQueryHashes": 2000 /* defaultCacheSizes["PersistedQueryLink.persistedQueryHashes"] */,
"fragmentRegistry.transform": 2000 /* defaultCacheSizes["fragmentRegistry.transform"] */,
"fragmentRegistry.lookup": 1000 /* defaultCacheSizes["fragmentRegistry.lookup"] */,
"fragmentRegistry.findFragmentSpreads": 4000 /* defaultCacheSizes["fragmentRegistry.findFragmentSpreads"] */,
"cache.fragmentQueryDocuments": 1000 /* defaultCacheSizes["cache.fragmentQueryDocuments"] */,
"removeTypenameFromVariables.getVariableDefinitions": 2000 /* defaultCacheSizes["removeTypenameFromVariables.getVariableDefinitions"] */,
"inMemoryCache.maybeBroadcastWatch": 5000 /* defaultCacheSizes["inMemoryCache.maybeBroadcastWatch"] */,
"inMemoryCache.executeSelectionSet": 50000 /* defaultCacheSizes["inMemoryCache.executeSelectionSet"] */,
"inMemoryCache.executeSubSelectedArray": 10000 /* defaultCacheSizes["inMemoryCache.executeSubSelectedArray"] */,
};
return Object.fromEntries(Object.entries(defaults).map(function (_a) {
var k = _a[0], v = _a[1];
return [
k,
cacheSizes[k] || v,
];
}));
}
function _getApolloClientMemoryInternals() {
var _a, _b, _c, _d, _e;
if (!(globalThis.__DEV__ !== false))
throw new Error("only supported in development mode");
return {
limits: getCurrentCacheSizes(),
sizes: __assign({ print: (_a = globalCaches.print) === null || _a === void 0 ? void 0 : _a.call(globalCaches), parser: (_b = globalCaches.parser) === null || _b === void 0 ? void 0 : _b.call(globalCaches), canonicalStringify: (_c = globalCaches.canonicalStringify) === null || _c === void 0 ? void 0 : _c.call(globalCaches), links: linkInfo(this.link), queryManager: {
getDocumentInfo: this["queryManager"]["transformCache"].size,
documentTransforms: transformInfo(this["queryManager"].documentTransform),
} }, (_e = (_d = this.cache).getMemoryInternals) === null || _e === void 0 ? void 0 : _e.call(_d)),
};
}
function _getApolloCacheMemoryInternals() {
return {
cache: {
fragmentQueryDocuments: getWrapperInformation(this["getFragmentDoc"]),
},
};
}
function _getInMemoryCacheMemoryInternals() {
var fragments = this.config.fragments;
return __assign(__assign({}, _getApolloCacheMemoryInternals.apply(this)), { addTypenameDocumentTransform: transformInfo(this["addTypenameTransform"]), inMemoryCache: {
executeSelectionSet: getWrapperInformation(this["storeReader"]["executeSelectionSet"]),
executeSubSelectedArray: getWrapperInformation(this["storeReader"]["executeSubSelectedArray"]),
maybeBroadcastWatch: getWrapperInformation(this["maybeBroadcastWatch"]),
}, fragmentRegistry: {
findFragmentSpreads: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.findFragmentSpreads),
lookup: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.lookup),
transform: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.transform),
} });
}
function isWrapper(f) {
return !!f && "dirtyKey" in f;
}
function getWrapperInformation(f) {
return isWrapper(f) ? f.size : undefined;
}
function isDefined(value) {
return value != null;
}
function transformInfo(transform) {
return recurseTransformInfo(transform).map(function (cache) { return ({ cache: cache }); });
}
function recurseTransformInfo(transform) {
return transform ?
__spreadArray(__spreadArray([
getWrapperInformation(transform === null || transform === void 0 ? void 0 : transform["performWork"])
], recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["left"]), true), recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["right"]), true).filter(isDefined)
: [];
}
function linkInfo(link) {
var _a;
return link ?
__spreadArray(__spreadArray([
(_a = link === null || link === void 0 ? void 0 : link.getMemoryInternals) === null || _a === void 0 ? void 0 : _a.call(link)
], linkInfo(link === null || link === void 0 ? void 0 : link.left), true), linkInfo(link === null || link === void 0 ? void 0 : link.right), true).filter(isDefined)
: [];
}
//# sourceMappingURL=getMemoryInternals.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
export { AutoCleanedStrongCache, AutoCleanedWeakCache } from "./caches.js";
export type { CacheSizes } from "./sizes.js";
export { cacheSizes, defaultCacheSizes } from "./sizes.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,3 @@
export { AutoCleanedStrongCache, AutoCleanedWeakCache } from "./caches.js";
export { cacheSizes } from "./sizes.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utilities/caching/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAE3E,OAAO,EAAE,UAAU,EAAqB,MAAM,YAAY,CAAC","sourcesContent":["export { AutoCleanedStrongCache, AutoCleanedWeakCache } from \"./caches.js\";\nexport type { CacheSizes } from \"./sizes.js\";\nexport { cacheSizes, defaultCacheSizes } from \"./sizes.js\";\n"]}

View File

@@ -0,0 +1,311 @@
declare global {
interface Window {
[cacheSizeSymbol]?: Partial<CacheSizes>;
}
}
/**
* The cache sizes used by various Apollo Client caches.
*
* @remarks
* All configurable caches hold memoized values. If an item is
* cache-collected, it incurs only a small performance impact and
* doesn't cause data loss. A smaller cache size might save you memory.
*
* You should choose cache sizes appropriate for storing a reasonable
* number of values rather than every value. To prevent too much recalculation,
* choose cache sizes that are at least large enough to hold memoized values for
* all hooks/queries on the screen at any given time.
*/
export interface CacheSizes {
/**
* Cache size for the [`print`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/print.ts) function.
*
* It is called with transformed `DocumentNode`s.
*
* @defaultValue
* Defaults to `2000`.
*
* @remarks
* This method is called to transform a GraphQL query AST parsed by `gql`
* back into a GraphQL string.
*
* @privateRemarks
* This method is called from the `QueryManager` and various `ApolloLink`s,
* always with the "serverQuery", so the server-facing part of a transformed
* `DocumentNode`.
*/
print: number;
/**
* Cache size for the [`parser`](https://github.com/apollographql/apollo-client/blob/main/src/react/parser/index.ts) function.
*
* It is called with user-provided `DocumentNode`s.
*
* @defaultValue
* Defaults to `1000`.
*
* @remarks
* This method is called by HOCs and hooks.
*
* @privateRemarks
* This function is used directly in HOCs, and nowadays mainly accessed by
* calling `verifyDocumentType` from various hooks.
* It is called with a user-provided DocumentNode.
*/
parser: number;
/**
* Cache size for the cache of [`DocumentTransform`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/DocumentTransform.ts)
* instances with the `cache` option set to `true`.
*
* Can be called with user-defined or already-transformed `DocumentNode`s.
*
* @defaultValue
* Defaults to `2000`.
*
* @remarks
* The cache size here should be chosen with other `DocumentTransform`s in mind.
* For example, if there was a `DocumentTransform` that would take `x` `DocumentNode`s,
* and returned a differently-transformed `DocumentNode` depending if the app is
* online or offline, then we assume that the cache returns `2*x` documents.
* If that were concatenated with another `DocumentTransform` that would
* also duplicate the cache size, you'd need to account for `4*x` documents
* returned by the second transform.
*
* Due to an implementation detail of Apollo Client, if you use custom document
* transforms you should always add `n` (the "base" number of user-provided
* Documents) to the resulting cache size.
*
* If we assume that the user-provided transforms receive `n` documents and
* return `n` documents, the cache size should be `2*n`.
*
* If we assume that the chain of user-provided transforms receive `n` documents and
* return `4*n` documents, the cache size should be `5*n`.
*
* This size should also then be used in every other cache that mentions that
* it operates on a "transformed" `DocumentNode`.
*
* @privateRemarks
* Cache size for the `performWork` method of each [`DocumentTransform`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/DocumentTransform.ts).
*
* No user-provided DocumentNode will actually be "the last one", as we run the
* `defaultDocumentTransform` before *and* after the user-provided transforms.
* For that reason, we need the extra `n` here - `n` for "before transformation"
* plus the actual maximum cache size of the user-provided transform chain.
*
* This method is called from `transformDocument`, which is called from
* `QueryManager` with a user-provided DocumentNode.
* It is also called with already-transformed DocumentNodes, assuming the
* user provided additional transforms.
*
*/
"documentTransform.cache": number;
/**
* A cache inside of [`QueryManager`](https://github.com/apollographql/apollo-client/blob/main/src/core/QueryManager.ts).
*
* It is called with transformed `DocumentNode`s.
*
* @defaultValue
* Defaults to `2000`.
*
* @privateRemarks
* Cache size for the `transformCache` used in the `getDocumentInfo` method of `QueryManager`.
* Called throughout the `QueryManager` with transformed DocumentNodes.
*/
"queryManager.getDocumentInfo": number;
/**
* A cache inside of [`PersistedQueryLink`](https://github.com/apollographql/apollo-client/blob/main/src/link/persisted-queries/index.ts).
*
* It is called with transformed `DocumentNode`s.
*
* @defaultValue
* Defaults to `2000`.
*
* @remarks
* This cache is used to cache the hashes of persisted queries.
*
* @privateRemarks
* Cache size for the `hashesByQuery` cache in the `PersistedQueryLink`.
*/
"PersistedQueryLink.persistedQueryHashes": number;
/**
* Cache used by [`canonicalStringify`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/common/canonicalStringify.ts).
*
* @defaultValue
* Defaults to `1000`.
*
* @remarks
* This cache contains the sorted keys of objects that are stringified by
* `canonicalStringify`.
* It uses the stringified unsorted keys of objects as keys.
* The cache will not grow beyond the size of different object **shapes**
* encountered in an application, no matter how much actual data gets stringified.
*
* @privateRemarks
* Cache size for the `sortingMap` in `canonicalStringify`.
*/
canonicalStringify: number;
/**
* A cache inside of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).
*
* Can be called with user-defined or already-transformed `DocumentNode`s.
*
* @defaultValue
* Defaults to `2000`.
*
* @privateRemarks
*
* Cache size for the `transform` method of FragmentRegistry.
* This function is called as part of the `defaultDocumentTransform` which will be called with
* user-provided and already-transformed DocumentNodes.
*
*/
"fragmentRegistry.transform": number;
/**
* A cache inside of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).
*
* This function is called with fragment names in the form of a string.
*
* @defaultValue
* Defaults to `1000`.
*
* @remarks
* The size of this case should be chosen with the number of fragments in
* your application in mind.
*
* Note:
* This function is a dependency of `fragmentRegistry.transform`, so having too small of a cache size here
* might involuntarily invalidate values in the `transform` cache.
*
* @privateRemarks
* Cache size for the `lookup` method of FragmentRegistry.
*/
"fragmentRegistry.lookup": number;
/**
* Cache size for the `findFragmentSpreads` method of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).
*
* This function is called with transformed `DocumentNode`s, as well as recursively
* with every fragment spread referenced within that, or a fragment referenced by a
* fragment spread.
*
* @defaultValue
* Defaults to `4000`.
*
* @remarks
*
* Note: This function is a dependency of `fragmentRegistry.transform`, so having too small of cache size here
* might involuntarily invalidate values in the `transform` cache.
*/
"fragmentRegistry.findFragmentSpreads": number;
/**
* Cache size for the `getFragmentDoc` method of [`ApolloCache`](https://github.com/apollographql/apollo-client/blob/main/src/cache/core/cache.ts).
*
* This function is called with user-provided fragment definitions.
*
* @defaultValue
* Defaults to `1000`.
*
* @remarks
* This function is called from `readFragment` with user-provided fragment definitions.
*/
"cache.fragmentQueryDocuments": number;
/**
* Cache used in [`removeTypenameFromVariables`](https://github.com/apollographql/apollo-client/blob/main/src/link/remove-typename/removeTypenameFromVariables.ts).
*
* This function is called transformed `DocumentNode`s.
*
* @defaultValue
* Defaults to `2000`.
*
* @privateRemarks
* Cache size for the `getVariableDefinitions` function of `removeTypenameFromVariables`.
*/
"removeTypenameFromVariables.getVariableDefinitions": number;
/**
* Cache size for the `maybeBroadcastWatch` method on [`InMemoryCache`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/inMemoryCache.ts).
*
* Note: `maybeBroadcastWatch` will be set to the `resultCacheMaxSize` option and
* will fall back to this configuration value if the option is not set.
*
* @defaultValue
* Defaults to `5000`.
*
* @remarks
* This method is used for dependency tracking in the `InMemoryCache` and
* prevents from unnecessary re-renders.
* It is recommended to keep this value significantly higher than the number of
* possible subscribers you will have active at the same time in your application
* at any time.
*/
"inMemoryCache.maybeBroadcastWatch": number;
/**
* Cache size for the `executeSelectionSet` method on [`StoreReader`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/readFromStore.ts).
*
* Note:
* `executeSelectionSet` will be set to the `resultCacheMaxSize` option and
* will fall back to this configuration value if the option is not set.
*
* @defaultValue
* Defaults to `50000`.
*
* @remarks
* Every object that is read from the cache will be cached here, so it is
* recommended to set this to a high value.
*/
"inMemoryCache.executeSelectionSet": number;
/**
* Cache size for the `executeSubSelectedArray` method on [`StoreReader`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/readFromStore.ts).
*
* Note:
* `executeSubSelectedArray` will be set to the `resultCacheMaxSize` option and
* will fall back to this configuration value if the option is not set.
*
* @defaultValue
* Defaults to `10000`.
*
* @remarks
* Every array that is read from the cache will be cached here, so it is
* recommended to set this to a high value.
*/
"inMemoryCache.executeSubSelectedArray": number;
}
declare const cacheSizeSymbol: unique symbol;
/**
*
* The global cache size configuration for Apollo Client.
*
* @remarks
*
* You can directly modify this object, but any modification will
* only have an effect on caches that are created after the modification.
*
* So for global caches, such as `parser`, `canonicalStringify` and `print`,
* you might need to call `.reset` on them, which will essentially re-create them.
*
* Alternatively, you can set `globalThis[Symbol.for("apollo.cacheSize")]` before
* you load the Apollo Client package:
*
* @example
* ```ts
* globalThis[Symbol.for("apollo.cacheSize")] = {
* parser: 100
* } satisfies Partial<CacheSizes> // the `satisfies` is optional if using TypeScript
* ```
*/
export declare const cacheSizes: Partial<CacheSizes>;
export declare const enum defaultCacheSizes {
parser = 1000,
canonicalStringify = 1000,
print = 2000,
"documentTransform.cache" = 2000,
"queryManager.getDocumentInfo" = 2000,
"PersistedQueryLink.persistedQueryHashes" = 2000,
"fragmentRegistry.transform" = 2000,
"fragmentRegistry.lookup" = 1000,
"fragmentRegistry.findFragmentSpreads" = 4000,
"cache.fragmentQueryDocuments" = 1000,
"removeTypenameFromVariables.getVariableDefinitions" = 2000,
"inMemoryCache.maybeBroadcastWatch" = 5000,
"inMemoryCache.executeSelectionSet" = 50000,
"inMemoryCache.executeSubSelectedArray" = 10000
}
export {};
//# sourceMappingURL=sizes.d.ts.map

27
node_modules/@apollo/client/utilities/caching/sizes.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { __assign } from "tslib";
import { global } from "../globals/index.js";
var cacheSizeSymbol = Symbol.for("apollo.cacheSize");
/**
*
* The global cache size configuration for Apollo Client.
*
* @remarks
*
* You can directly modify this object, but any modification will
* only have an effect on caches that are created after the modification.
*
* So for global caches, such as `parser`, `canonicalStringify` and `print`,
* you might need to call `.reset` on them, which will essentially re-create them.
*
* Alternatively, you can set `globalThis[Symbol.for("apollo.cacheSize")]` before
* you load the Apollo Client package:
*
* @example
* ```ts
* globalThis[Symbol.for("apollo.cacheSize")] = {
* parser: 100
* } satisfies Partial<CacheSizes> // the `satisfies` is optional if using TypeScript
* ```
*/
export var cacheSizes = __assign({}, global[cacheSizeSymbol]);
//# sourceMappingURL=sizes.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export declare const isArray: (a: any) => a is any[] | readonly any[];
export declare function isNonEmptyArray<T>(value?: ArrayLike<T>): value is Array<T>;
//# sourceMappingURL=arrays.d.ts.map

View File

@@ -0,0 +1,6 @@
// A version of Array.isArray that works better with readonly arrays.
export var isArray = Array.isArray;
export function isNonEmptyArray(value) {
return Array.isArray(value) && value.length > 0;
}
//# sourceMappingURL=arrays.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"arrays.js","sourceRoot":"","sources":["../../../src/utilities/common/arrays.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,MAAM,CAAC,IAAM,OAAO,GAA4C,KAAK,CAAC,OAAO,CAAC;AAE9E,MAAM,UAAU,eAAe,CAAI,KAAoB;IACrD,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAClD,CAAC","sourcesContent":["// A version of Array.isArray that works better with readonly arrays.\nexport const isArray: (a: any) => a is any[] | readonly any[] = Array.isArray;\n\nexport function isNonEmptyArray<T>(value?: ArrayLike<T>): value is Array<T> {\n return Array.isArray(value) && value.length > 0;\n}\n"]}

View File

@@ -0,0 +1,7 @@
export declare const canUseWeakMap: boolean;
export declare const canUseWeakSet: boolean;
export declare const canUseSymbol: boolean;
export declare const canUseAsyncIteratorSymbol: false | typeof Symbol.asyncIterator;
export declare const canUseDOM: boolean;
export declare const canUseLayoutEffect: boolean;
//# sourceMappingURL=canUse.d.ts.map

26
node_modules/@apollo/client/utilities/common/canUse.js generated vendored Normal file
View File

@@ -0,0 +1,26 @@
import { maybe } from "../globals/index.js";
var isReactNative = maybe(function () { return navigator.product; }) == "ReactNative";
export var canUseWeakMap = typeof WeakMap === "function" &&
!(isReactNative && !global.HermesInternal);
export var canUseWeakSet = typeof WeakSet === "function";
export var canUseSymbol = typeof Symbol === "function" && typeof Symbol.for === "function";
export var canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;
export var canUseDOM = typeof maybe(function () { return window.document.createElement; }) === "function";
var usingJSDOM =
// Following advice found in this comment from @domenic (maintainer of jsdom):
// https://github.com/jsdom/jsdom/issues/1537#issuecomment-229405327
//
// Since we control the version of Jest and jsdom used when running Apollo
// Client tests, and that version is recent enought to include " jsdom/x.y.z"
// at the end of the user agent string, I believe this case is all we need to
// check. Testing for "Node.js" was recommended for backwards compatibility
// with older version of jsdom, but we don't have that problem.
maybe(function () { return navigator.userAgent.indexOf("jsdom") >= 0; }) || false;
// Our tests should all continue to pass if we remove this !usingJSDOM
// condition, thereby allowing useLayoutEffect when using jsdom. Unfortunately,
// if we allow useLayoutEffect, then useSyncExternalStore generates many
// warnings about useLayoutEffect doing nothing on the server. While these
// warnings are harmless, this !usingJSDOM condition seems to be the best way to
// prevent them (i.e. skipping useLayoutEffect when using jsdom).
export var canUseLayoutEffect = (canUseDOM || isReactNative) && !usingJSDOM;
//# sourceMappingURL=canUse.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"canUse.js","sourceRoot":"","sources":["../../../src/utilities/common/canUse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAE5C,IAAM,aAAa,GAAG,KAAK,CAAC,cAAM,OAAA,SAAS,CAAC,OAAO,EAAjB,CAAiB,CAAC,IAAI,aAAa,CAAC;AAEtE,MAAM,CAAC,IAAM,aAAa,GACxB,OAAO,OAAO,KAAK,UAAU;IAC7B,CAAC,CAAC,aAAa,IAAI,CAAE,MAAc,CAAC,cAAc,CAAC,CAAC;AAEtD,MAAM,CAAC,IAAM,aAAa,GAAG,OAAO,OAAO,KAAK,UAAU,CAAC;AAE3D,MAAM,CAAC,IAAM,YAAY,GACvB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,UAAU,CAAC;AAEnE,MAAM,CAAC,IAAM,yBAAyB,GAAG,YAAY,IAAI,MAAM,CAAC,aAAa,CAAC;AAE9E,MAAM,CAAC,IAAM,SAAS,GACpB,OAAO,KAAK,CAAC,cAAM,OAAA,MAAM,CAAC,QAAQ,CAAC,aAAa,EAA7B,CAA6B,CAAC,KAAK,UAAU,CAAC;AAEnE,IAAM,UAAU;AACd,8EAA8E;AAC9E,oEAAoE;AACpE,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,6EAA6E;AAC7E,2EAA2E;AAC3E,+DAA+D;AAC/D,KAAK,CAAC,cAAM,OAAA,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAzC,CAAyC,CAAC,IAAI,KAAK,CAAC;AAElE,sEAAsE;AACtE,+EAA+E;AAC/E,wEAAwE;AACxE,0EAA0E;AAC1E,gFAAgF;AAChF,iEAAiE;AACjE,MAAM,CAAC,IAAM,kBAAkB,GAAG,CAAC,SAAS,IAAI,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC","sourcesContent":["import { maybe } from \"../globals/index.js\";\n\nconst isReactNative = maybe(() => navigator.product) == \"ReactNative\";\n\nexport const canUseWeakMap =\n typeof WeakMap === \"function\" &&\n !(isReactNative && !(global as any).HermesInternal);\n\nexport const canUseWeakSet = typeof WeakSet === \"function\";\n\nexport const canUseSymbol =\n typeof Symbol === \"function\" && typeof Symbol.for === \"function\";\n\nexport const canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;\n\nexport const canUseDOM =\n typeof maybe(() => window.document.createElement) === \"function\";\n\nconst usingJSDOM: boolean =\n // Following advice found in this comment from @domenic (maintainer of jsdom):\n // https://github.com/jsdom/jsdom/issues/1537#issuecomment-229405327\n //\n // Since we control the version of Jest and jsdom used when running Apollo\n // Client tests, and that version is recent enought to include \" jsdom/x.y.z\"\n // at the end of the user agent string, I believe this case is all we need to\n // check. Testing for \"Node.js\" was recommended for backwards compatibility\n // with older version of jsdom, but we don't have that problem.\n maybe(() => navigator.userAgent.indexOf(\"jsdom\") >= 0) || false;\n\n// Our tests should all continue to pass if we remove this !usingJSDOM\n// condition, thereby allowing useLayoutEffect when using jsdom. Unfortunately,\n// if we allow useLayoutEffect, then useSyncExternalStore generates many\n// warnings about useLayoutEffect doing nothing on the server. While these\n// warnings are harmless, this !usingJSDOM condition seems to be the best way to\n// prevent them (i.e. skipping useLayoutEffect when using jsdom).\nexport const canUseLayoutEffect = (canUseDOM || isReactNative) && !usingJSDOM;\n"]}

View File

@@ -0,0 +1,21 @@
/**
* Like JSON.stringify, but with object keys always sorted in the same order.
*
* To achieve performant sorting, this function uses a Map from JSON-serialized
* arrays of keys (in any order) to sorted arrays of the same keys, with a
* single sorted array reference shared by all permutations of the keys.
*
* As a drawback, this function will add a little bit more memory for every
* object encountered that has different (more, less, a different order of) keys
* than in the past.
*
* In a typical application, this extra memory usage should not play a
* significant role, as `canonicalStringify` will be called for only a limited
* number of object shapes, and the cache will not grow beyond a certain point.
* But in some edge cases, this could be a problem, so we provide
* canonicalStringify.reset() as a way of clearing the cache.
* */
export declare const canonicalStringify: ((value: any) => string) & {
reset(): void;
};
//# sourceMappingURL=canonicalStringify.d.ts.map

View File

@@ -0,0 +1,84 @@
import { AutoCleanedStrongCache, cacheSizes, } from "../../utilities/caching/index.js";
import { registerGlobalCache } from "../caching/getMemoryInternals.js";
/**
* Like JSON.stringify, but with object keys always sorted in the same order.
*
* To achieve performant sorting, this function uses a Map from JSON-serialized
* arrays of keys (in any order) to sorted arrays of the same keys, with a
* single sorted array reference shared by all permutations of the keys.
*
* As a drawback, this function will add a little bit more memory for every
* object encountered that has different (more, less, a different order of) keys
* than in the past.
*
* In a typical application, this extra memory usage should not play a
* significant role, as `canonicalStringify` will be called for only a limited
* number of object shapes, and the cache will not grow beyond a certain point.
* But in some edge cases, this could be a problem, so we provide
* canonicalStringify.reset() as a way of clearing the cache.
* */
export var canonicalStringify = Object.assign(function canonicalStringify(value) {
return JSON.stringify(value, stableObjectReplacer);
}, {
reset: function () {
// Clearing the sortingMap will reclaim all cached memory, without
// affecting the logical results of canonicalStringify, but potentially
// sacrificing performance until the cache is refilled.
sortingMap = new AutoCleanedStrongCache(cacheSizes.canonicalStringify || 1000 /* defaultCacheSizes.canonicalStringify */);
},
});
if (globalThis.__DEV__ !== false) {
registerGlobalCache("canonicalStringify", function () { return sortingMap.size; });
}
// Values are JSON-serialized arrays of object keys (in any order), and values
// are sorted arrays of the same keys.
var sortingMap;
canonicalStringify.reset();
// The JSON.stringify function takes an optional second argument called a
// replacer function. This function is called for each key-value pair in the
// object being stringified, and its return value is used instead of the
// original value. If the replacer function returns a new value, that value is
// stringified as JSON instead of the original value of the property.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter
function stableObjectReplacer(key, value) {
if (value && typeof value === "object") {
var proto = Object.getPrototypeOf(value);
// We don't want to mess with objects that are not "plain" objects, which
// means their prototype is either Object.prototype or null. This check also
// prevents needlessly rearranging the indices of arrays.
if (proto === Object.prototype || proto === null) {
var keys = Object.keys(value);
// If keys is already sorted, let JSON.stringify serialize the original
// value instead of creating a new object with keys in the same order.
if (keys.every(everyKeyInOrder))
return value;
var unsortedKey = JSON.stringify(keys);
var sortedKeys = sortingMap.get(unsortedKey);
if (!sortedKeys) {
keys.sort();
var sortedKey = JSON.stringify(keys);
// Checking for sortedKey in the sortingMap allows us to share the same
// sorted array reference for all permutations of the same set of keys.
sortedKeys = sortingMap.get(sortedKey) || keys;
sortingMap.set(unsortedKey, sortedKeys);
sortingMap.set(sortedKey, sortedKeys);
}
var sortedObject_1 = Object.create(proto);
// Reassigning the keys in sorted order will cause JSON.stringify to
// serialize them in sorted order.
sortedKeys.forEach(function (key) {
sortedObject_1[key] = value[key];
});
return sortedObject_1;
}
}
return value;
}
// Since everything that happens in stableObjectReplacer benefits from being as
// efficient as possible, we use a static function as the callback for
// keys.every in order to test if the provided keys are already sorted without
// allocating extra memory for a callback.
function everyKeyInOrder(key, i, keys) {
return i === 0 || keys[i - 1] <= key;
}
//# sourceMappingURL=canonicalStringify.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
/**
* Deeply clones a value to create a new instance.
*/
export declare function cloneDeep<T>(value: T): T;
//# sourceMappingURL=cloneDeep.d.ts.map

View File

@@ -0,0 +1,38 @@
var toString = Object.prototype.toString;
/**
* Deeply clones a value to create a new instance.
*/
export function cloneDeep(value) {
return cloneDeepHelper(value);
}
function cloneDeepHelper(val, seen) {
switch (toString.call(val)) {
case "[object Array]": {
seen = seen || new Map();
if (seen.has(val))
return seen.get(val);
var copy_1 = val.slice(0);
seen.set(val, copy_1);
copy_1.forEach(function (child, i) {
copy_1[i] = cloneDeepHelper(child, seen);
});
return copy_1;
}
case "[object Object]": {
seen = seen || new Map();
if (seen.has(val))
return seen.get(val);
// High fidelity polyfills of Object.create and Object.getPrototypeOf are
// possible in all JS environments, so we will assume they exist/work.
var copy_2 = Object.create(Object.getPrototypeOf(val));
seen.set(val, copy_2);
Object.keys(val).forEach(function (key) {
copy_2[key] = cloneDeepHelper(val[key], seen);
});
return copy_2;
}
default:
return val;
}
}
//# sourceMappingURL=cloneDeep.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cloneDeep.js","sourceRoot":"","sources":["../../../src/utilities/common/cloneDeep.ts"],"names":[],"mappings":"AAAQ,IAAA,QAAQ,GAAK,MAAM,CAAC,SAAS,SAArB,CAAsB;AAEtC;;GAEG;AACH,MAAM,UAAU,SAAS,CAAI,KAAQ;IACnC,OAAO,eAAe,CAAC,KAAK,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,eAAe,CAAI,GAAM,EAAE,IAAoB;IACtD,QAAQ,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QAC3B,KAAK,gBAAgB,CAAC,CAAC,CAAC;YACtB,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,EAAE,CAAC;YACzB,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;gBAAE,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACxC,IAAM,MAAI,GAAe,GAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC9C,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,MAAI,CAAC,CAAC;YACpB,MAAI,CAAC,OAAO,CAAC,UAAU,KAAK,EAAE,CAAC;gBAC7B,MAAI,CAAC,CAAC,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACzC,CAAC,CAAC,CAAC;YACH,OAAO,MAAI,CAAC;QACd,CAAC;QAED,KAAK,iBAAiB,CAAC,CAAC,CAAC;YACvB,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,EAAE,CAAC;YACzB,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;gBAAE,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACxC,yEAAyE;YACzE,sEAAsE;YACtE,IAAM,MAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC;YACvD,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,MAAI,CAAC,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC,GAA8B,CAAC,CAAC,OAAO,CAAC,UAAC,GAAG;gBACtD,MAAI,CAAC,GAAG,CAAC,GAAG,eAAe,CAAE,GAAW,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC;YACvD,CAAC,CAAC,CAAC;YACH,OAAO,MAAI,CAAC;QACd,CAAC;QAED;YACE,OAAO,GAAG,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["const { toString } = Object.prototype;\n\n/**\n * Deeply clones a value to create a new instance.\n */\nexport function cloneDeep<T>(value: T): T {\n return cloneDeepHelper(value);\n}\n\nfunction cloneDeepHelper<T>(val: T, seen?: Map<any, any>): T {\n switch (toString.call(val)) {\n case \"[object Array]\": {\n seen = seen || new Map();\n if (seen.has(val)) return seen.get(val);\n const copy: T & any[] = (val as any).slice(0);\n seen.set(val, copy);\n copy.forEach(function (child, i) {\n copy[i] = cloneDeepHelper(child, seen);\n });\n return copy;\n }\n\n case \"[object Object]\": {\n seen = seen || new Map();\n if (seen.has(val)) return seen.get(val);\n // High fidelity polyfills of Object.create and Object.getPrototypeOf are\n // possible in all JS environments, so we will assume they exist/work.\n const copy = Object.create(Object.getPrototypeOf(val));\n seen.set(val, copy);\n Object.keys(val as T & Record<string, any>).forEach((key) => {\n copy[key] = cloneDeepHelper((val as any)[key], seen);\n });\n return copy;\n }\n\n default:\n return val;\n }\n}\n"]}

View File

@@ -0,0 +1,7 @@
import type { TupleToIntersection } from "./mergeDeep.js";
/**
* Merges the provided objects shallowly and removes
* all properties with an `undefined` value
*/
export declare function compact<TArgs extends any[]>(...objects: TArgs): TupleToIntersection<TArgs>;
//# sourceMappingURL=compact.d.ts.map

View File

@@ -0,0 +1,23 @@
/**
* Merges the provided objects shallowly and removes
* all properties with an `undefined` value
*/
export function compact() {
var objects = [];
for (var _i = 0; _i < arguments.length; _i++) {
objects[_i] = arguments[_i];
}
var result = Object.create(null);
objects.forEach(function (obj) {
if (!obj)
return;
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (value !== void 0) {
result[key] = value;
}
});
});
return result;
}
//# sourceMappingURL=compact.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compact.js","sourceRoot":"","sources":["../../../src/utilities/common/compact.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,UAAU,OAAO;IACrB,iBAAiB;SAAjB,UAAiB,EAAjB,qBAAiB,EAAjB,IAAiB;QAAjB,4BAAiB;;IAEjB,IAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAEnC,OAAO,CAAC,OAAO,CAAC,UAAC,GAAG;QAClB,IAAI,CAAC,GAAG;YAAE,OAAO;QACjB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,UAAC,GAAG;YAC3B,IAAM,KAAK,GAAI,GAAW,CAAC,GAAG,CAAC,CAAC;YAChC,IAAI,KAAK,KAAK,KAAK,CAAC,EAAE,CAAC;gBACrB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YACtB,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { TupleToIntersection } from \"./mergeDeep.js\";\n\n/**\n * Merges the provided objects shallowly and removes\n * all properties with an `undefined` value\n */\nexport function compact<TArgs extends any[]>(\n ...objects: TArgs\n): TupleToIntersection<TArgs> {\n const result = Object.create(null);\n\n objects.forEach((obj) => {\n if (!obj) return;\n Object.keys(obj).forEach((key) => {\n const value = (obj as any)[key];\n if (value !== void 0) {\n result[key] = value;\n }\n });\n });\n\n return result;\n}\n"]}

View File

@@ -0,0 +1,4 @@
import type { FetchResult } from "../../link/core/index.js";
export declare function graphQLResultHasError<T>(result: FetchResult<T>): boolean;
export declare function getGraphQLErrorsFromResult<T>(result: FetchResult<T>): import("graphql").GraphQLFormattedError[];
//# sourceMappingURL=errorHandling.d.ts.map

View File

@@ -0,0 +1,19 @@
import { isNonEmptyArray } from "./arrays.js";
import { isExecutionPatchIncrementalResult } from "./incrementalResult.js";
export function graphQLResultHasError(result) {
var errors = getGraphQLErrorsFromResult(result);
return isNonEmptyArray(errors);
}
export function getGraphQLErrorsFromResult(result) {
var graphQLErrors = isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
result.incremental.forEach(function (incrementalResult) {
if (incrementalResult.errors) {
graphQLErrors.push.apply(graphQLErrors, incrementalResult.errors);
}
});
}
return graphQLErrors;
}
//# sourceMappingURL=errorHandling.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"errorHandling.js","sourceRoot":"","sources":["../../../src/utilities/common/errorHandling.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,iCAAiC,EAAE,MAAM,wBAAwB,CAAC;AAE3E,MAAM,UAAU,qBAAqB,CAAI,MAAsB;IAC7D,IAAM,MAAM,GAAG,0BAA0B,CAAC,MAAM,CAAC,CAAC;IAClD,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,0BAA0B,CAAI,MAAsB;IAClE,IAAM,aAAa,GACjB,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAE/D,IACE,iCAAiC,CAAC,MAAM,CAAC;QACzC,eAAe,CAAC,MAAM,CAAC,WAAW,CAAC,EACnC,CAAC;QACD,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,UAAC,iBAAiB;YAC3C,IAAI,iBAAiB,CAAC,MAAM,EAAE,CAAC;gBAC7B,aAAa,CAAC,IAAI,OAAlB,aAAa,EAAS,iBAAiB,CAAC,MAAM,EAAE;YAClD,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import type { FetchResult } from \"../../link/core/index.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { isExecutionPatchIncrementalResult } from \"./incrementalResult.js\";\n\nexport function graphQLResultHasError<T>(result: FetchResult<T>): boolean {\n const errors = getGraphQLErrorsFromResult(result);\n return isNonEmptyArray(errors);\n}\n\nexport function getGraphQLErrorsFromResult<T>(result: FetchResult<T>) {\n const graphQLErrors =\n isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];\n\n if (\n isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)\n ) {\n result.incremental.forEach((incrementalResult) => {\n if (incrementalResult.errors) {\n graphQLErrors.push(...incrementalResult.errors);\n }\n });\n }\n return graphQLErrors;\n}\n"]}

View File

@@ -0,0 +1,7 @@
import type { ExecutionPatchIncrementalResult, ExecutionPatchInitialResult, ExecutionPatchResult, ApolloPayloadResult, FetchResult } from "../../link/core/index.js";
export declare function isExecutionPatchIncrementalResult<T>(value: FetchResult<T>): value is ExecutionPatchIncrementalResult;
export declare function isExecutionPatchInitialResult<T>(value: FetchResult<T>): value is ExecutionPatchInitialResult<T>;
export declare function isExecutionPatchResult<T>(value: FetchResult<T>): value is ExecutionPatchResult<T>;
export declare function isApolloPayloadResult(value: unknown): value is ApolloPayloadResult;
export declare function mergeIncrementalData<TData extends object>(prevResult: TData, result: ExecutionPatchResult<TData>): TData;
//# sourceMappingURL=incrementalResult.d.ts.map

View File

@@ -0,0 +1,39 @@
import { isNonNullObject } from "./objects.js";
import { isNonEmptyArray } from "./arrays.js";
import { DeepMerger } from "./mergeDeep.js";
export function isExecutionPatchIncrementalResult(value) {
return "incremental" in value;
}
export function isExecutionPatchInitialResult(value) {
return "hasNext" in value && "data" in value;
}
export function isExecutionPatchResult(value) {
return (isExecutionPatchIncrementalResult(value) ||
isExecutionPatchInitialResult(value));
}
// This function detects an Apollo payload result before it is transformed
// into a FetchResult via HttpLink; it cannot detect an ApolloPayloadResult
// once it leaves the link chain.
export function isApolloPayloadResult(value) {
return isNonNullObject(value) && "payload" in value;
}
export function mergeIncrementalData(prevResult, result) {
var mergedData = prevResult;
var merger = new DeepMerger();
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
result.incremental.forEach(function (_a) {
var data = _a.data, path = _a.path;
for (var i = path.length - 1; i >= 0; --i) {
var key = path[i];
var isNumericKey = !isNaN(+key);
var parent_1 = isNumericKey ? [] : {};
parent_1[key] = data;
data = parent_1;
}
mergedData = merger.merge(mergedData, data);
});
}
return mergedData;
}
//# sourceMappingURL=incrementalResult.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"incrementalResult.js","sourceRoot":"","sources":["../../../src/utilities/common/incrementalResult.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,MAAM,UAAU,iCAAiC,CAC/C,KAAqB;IAErB,OAAO,aAAa,IAAI,KAAK,CAAC;AAChC,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,KAAqB;IAErB,OAAO,SAAS,IAAI,KAAK,IAAI,MAAM,IAAI,KAAK,CAAC;AAC/C,CAAC;AAED,MAAM,UAAU,sBAAsB,CACpC,KAAqB;IAErB,OAAO,CACL,iCAAiC,CAAC,KAAK,CAAC;QACxC,6BAA6B,CAAC,KAAK,CAAC,CACrC,CAAC;AACJ,CAAC;AAED,0EAA0E;AAC1E,2EAA2E;AAC3E,iCAAiC;AACjC,MAAM,UAAU,qBAAqB,CACnC,KAAc;IAEd,OAAO,eAAe,CAAC,KAAK,CAAC,IAAI,SAAS,IAAI,KAAK,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,oBAAoB,CAClC,UAAiB,EACjB,MAAmC;IAEnC,IAAI,UAAU,GAAG,UAAU,CAAC;IAC5B,IAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;IAChC,IACE,iCAAiC,CAAC,MAAM,CAAC;QACzC,eAAe,CAAC,MAAM,CAAC,WAAW,CAAC,EACnC,CAAC;QACD,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,UAAC,EAAc;gBAAZ,IAAI,UAAA,EAAE,IAAI,UAAA;YACtC,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;gBAC1C,IAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;gBACpB,IAAM,YAAY,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC;gBAClC,IAAM,QAAM,GAAiC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACpE,QAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;gBACnB,IAAI,GAAG,QAAqB,CAAC;YAC/B,CAAC;YACD,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,UAAmB,CAAC;AAC7B,CAAC","sourcesContent":["import type {\n ExecutionPatchIncrementalResult,\n ExecutionPatchInitialResult,\n ExecutionPatchResult,\n ApolloPayloadResult,\n FetchResult,\n} from \"../../link/core/index.js\";\nimport { isNonNullObject } from \"./objects.js\";\nimport { isNonEmptyArray } from \"./arrays.js\";\nimport { DeepMerger } from \"./mergeDeep.js\";\n\nexport function isExecutionPatchIncrementalResult<T>(\n value: FetchResult<T>\n): value is ExecutionPatchIncrementalResult {\n return \"incremental\" in value;\n}\n\nexport function isExecutionPatchInitialResult<T>(\n value: FetchResult<T>\n): value is ExecutionPatchInitialResult<T> {\n return \"hasNext\" in value && \"data\" in value;\n}\n\nexport function isExecutionPatchResult<T>(\n value: FetchResult<T>\n): value is ExecutionPatchResult<T> {\n return (\n isExecutionPatchIncrementalResult(value) ||\n isExecutionPatchInitialResult(value)\n );\n}\n\n// This function detects an Apollo payload result before it is transformed\n// into a FetchResult via HttpLink; it cannot detect an ApolloPayloadResult\n// once it leaves the link chain.\nexport function isApolloPayloadResult(\n value: unknown\n): value is ApolloPayloadResult {\n return isNonNullObject(value) && \"payload\" in value;\n}\n\nexport function mergeIncrementalData<TData extends object>(\n prevResult: TData,\n result: ExecutionPatchResult<TData>\n) {\n let mergedData = prevResult;\n const merger = new DeepMerger();\n if (\n isExecutionPatchIncrementalResult(result) &&\n isNonEmptyArray(result.incremental)\n ) {\n result.incremental.forEach(({ data, path }) => {\n for (let i = path.length - 1; i >= 0; --i) {\n const key = path[i];\n const isNumericKey = !isNaN(+key);\n const parent: Record<string | number, any> = isNumericKey ? [] : {};\n parent[key] = data;\n data = parent as typeof data;\n }\n mergedData = merger.merge(mergedData, data);\n });\n }\n return mergedData as TData;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare function makeUniqueId(prefix: string): string;
//# sourceMappingURL=makeUniqueId.d.ts.map

View File

@@ -0,0 +1,9 @@
var prefixCounts = new Map();
// These IDs won't be globally unique, but they will be unique within this
// process, thanks to the counter, and unguessable thanks to the random suffix.
export function makeUniqueId(prefix) {
var count = prefixCounts.get(prefix) || 1;
prefixCounts.set(prefix, count + 1);
return "".concat(prefix, ":").concat(count, ":").concat(Math.random().toString(36).slice(2));
}
//# sourceMappingURL=makeUniqueId.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"makeUniqueId.js","sourceRoot":"","sources":["../../../src/utilities/common/makeUniqueId.ts"],"names":[],"mappings":"AAAA,IAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE/C,0EAA0E;AAC1E,+EAA+E;AAC/E,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,IAAM,KAAK,GAAG,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC5C,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IACpC,OAAO,UAAG,MAAM,cAAI,KAAK,cAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,CAAC;AACrE,CAAC","sourcesContent":["const prefixCounts = new Map<string, number>();\n\n// These IDs won't be globally unique, but they will be unique within this\n// process, thanks to the counter, and unguessable thanks to the random suffix.\nexport function makeUniqueId(prefix: string) {\n const count = prefixCounts.get(prefix) || 1;\n prefixCounts.set(prefix, count + 1);\n return `${prefix}:${count}:${Math.random().toString(36).slice(2)}`;\n}\n"]}

View File

@@ -0,0 +1,3 @@
export declare function deepFreeze(value: any): any;
export declare function maybeDeepFreeze<T>(obj: T): T;
//# sourceMappingURL=maybeDeepFreeze.d.ts.map

View File

@@ -0,0 +1,36 @@
import { isNonNullObject } from "./objects.js";
export function deepFreeze(value) {
var workSet = new Set([value]);
workSet.forEach(function (obj) {
if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {
Object.getOwnPropertyNames(obj).forEach(function (name) {
if (isNonNullObject(obj[name]))
workSet.add(obj[name]);
});
}
});
return value;
}
function shallowFreeze(obj) {
if (globalThis.__DEV__ !== false && !Object.isFrozen(obj)) {
try {
Object.freeze(obj);
}
catch (e) {
// Some types like Uint8Array and Node.js's Buffer cannot be frozen, but
// they all throw a TypeError when you try, so we re-throw any exceptions
// that are not TypeErrors, since that would be unexpected.
if (e instanceof TypeError)
return null;
throw e;
}
}
return obj;
}
export function maybeDeepFreeze(obj) {
if (globalThis.__DEV__ !== false) {
deepFreeze(obj);
}
return obj;
}
//# sourceMappingURL=maybeDeepFreeze.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"maybeDeepFreeze.js","sourceRoot":"","sources":["../../../src/utilities/common/maybeDeepFreeze.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,UAAU,UAAU,CAAC,KAAU;IACnC,IAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IACjC,OAAO,CAAC,OAAO,CAAC,UAAC,GAAG;QAClB,IAAI,eAAe,CAAC,GAAG,CAAC,IAAI,aAAa,CAAC,GAAG,CAAC,KAAK,GAAG,EAAE,CAAC;YACvD,MAAM,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,UAAC,IAAI;gBAC3C,IAAI,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;oBAAE,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;YACzD,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,aAAa,CAAmB,GAAM;IAC7C,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrC,IAAI,CAAC;YACH,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,wEAAwE;YACxE,yEAAyE;YACzE,2DAA2D;YAC3D,IAAI,CAAC,YAAY,SAAS;gBAAE,OAAO,IAAI,CAAC;YACxC,MAAM,CAAC,CAAC;QACV,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,UAAU,eAAe,CAAI,GAAM;IACvC,IAAI,OAAO,EAAE,CAAC;QACZ,UAAU,CAAC,GAAG,CAAC,CAAC;IAClB,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { isNonNullObject } from \"./objects.js\";\n\nexport function deepFreeze(value: any) {\n const workSet = new Set([value]);\n workSet.forEach((obj) => {\n if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {\n Object.getOwnPropertyNames(obj).forEach((name) => {\n if (isNonNullObject(obj[name])) workSet.add(obj[name]);\n });\n }\n });\n return value;\n}\n\nfunction shallowFreeze<T extends object>(obj: T): T | null {\n if (__DEV__ && !Object.isFrozen(obj)) {\n try {\n Object.freeze(obj);\n } catch (e) {\n // Some types like Uint8Array and Node.js's Buffer cannot be frozen, but\n // they all throw a TypeError when you try, so we re-throw any exceptions\n // that are not TypeErrors, since that would be unexpected.\n if (e instanceof TypeError) return null;\n throw e;\n }\n }\n return obj;\n}\n\nexport function maybeDeepFreeze<T>(obj: T): T {\n if (__DEV__) {\n deepFreeze(obj);\n }\n return obj;\n}\n"]}

View File

@@ -0,0 +1,14 @@
import { isNonNullObject } from "./objects.js";
export type TupleToIntersection<T extends any[]> = T extends [infer A] ? A : T extends [infer A, infer B] ? A & B : T extends [infer A, infer B, infer C] ? A & B & C : T extends [infer A, infer B, infer C, infer D] ? A & B & C & D : T extends [infer A, infer B, infer C, infer D, infer E] ? A & B & C & D & E : T extends (infer U)[] ? U : any;
export declare function mergeDeep<T extends any[]>(...sources: T): TupleToIntersection<T>;
export declare function mergeDeepArray<T>(sources: T[]): T;
export type ReconcilerFunction<TContextArgs extends any[]> = (this: DeepMerger<TContextArgs>, target: Record<string | number, any>, source: Record<string | number, any>, property: string | number, ...context: TContextArgs) => any;
export declare class DeepMerger<TContextArgs extends any[]> {
private reconciler;
constructor(reconciler?: ReconcilerFunction<TContextArgs>);
merge(target: any, source: any, ...context: TContextArgs): any;
isObject: typeof isNonNullObject;
private pastCopies;
shallowCopyForMerge<T>(value: T): T;
}
//# sourceMappingURL=mergeDeep.d.ts.map

View File

@@ -0,0 +1,89 @@
import { __assign, __spreadArray } from "tslib";
import { isNonNullObject } from "./objects.js";
var hasOwnProperty = Object.prototype.hasOwnProperty;
export function mergeDeep() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
return mergeDeepArray(sources);
}
// In almost any situation where you could succeed in getting the
// TypeScript compiler to infer a tuple type for the sources array, you
// could just use mergeDeep instead of mergeDeepArray, so instead of
// trying to convert T[] to an intersection type we just infer the array
// element type, which works perfectly when the sources array has a
// consistent element type.
export function mergeDeepArray(sources) {
var target = sources[0] || {};
var count = sources.length;
if (count > 1) {
var merger = new DeepMerger();
for (var i = 1; i < count; ++i) {
target = merger.merge(target, sources[i]);
}
}
return target;
}
var defaultReconciler = function (target, source, property) {
return this.merge(target[property], source[property]);
};
var DeepMerger = /** @class */ (function () {
function DeepMerger(reconciler) {
if (reconciler === void 0) { reconciler = defaultReconciler; }
this.reconciler = reconciler;
this.isObject = isNonNullObject;
this.pastCopies = new Set();
}
DeepMerger.prototype.merge = function (target, source) {
var _this = this;
var context = [];
for (var _i = 2; _i < arguments.length; _i++) {
context[_i - 2] = arguments[_i];
}
if (isNonNullObject(source) && isNonNullObject(target)) {
Object.keys(source).forEach(function (sourceKey) {
if (hasOwnProperty.call(target, sourceKey)) {
var targetValue = target[sourceKey];
if (source[sourceKey] !== targetValue) {
var result = _this.reconciler.apply(_this, __spreadArray([target,
source,
sourceKey], context, false));
// A well-implemented reconciler may return targetValue to indicate
// the merge changed nothing about the structure of the target.
if (result !== targetValue) {
target = _this.shallowCopyForMerge(target);
target[sourceKey] = result;
}
}
}
else {
// If there is no collision, the target can safely share memory with
// the source, and the recursion can terminate here.
target = _this.shallowCopyForMerge(target);
target[sourceKey] = source[sourceKey];
}
});
return target;
}
// If source (or target) is not an object, let source replace target.
return source;
};
DeepMerger.prototype.shallowCopyForMerge = function (value) {
if (isNonNullObject(value)) {
if (!this.pastCopies.has(value)) {
if (Array.isArray(value)) {
value = value.slice(0);
}
else {
value = __assign({ __proto__: Object.getPrototypeOf(value) }, value);
}
this.pastCopies.add(value);
}
}
return value;
};
return DeepMerger;
}());
export { DeepMerger };
//# sourceMappingURL=mergeDeep.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
import type { QueryOptions, WatchQueryOptions, MutationOptions, OperationVariables } from "../../core/index.js";
type OptionsUnion<TData, TVariables extends OperationVariables, TContext> = WatchQueryOptions<TVariables, TData> | QueryOptions<TVariables, TData> | MutationOptions<TData, TVariables, TContext, any>;
export declare function mergeOptions<TDefaultOptions extends Partial<OptionsUnion<any, any, any>>, TOptions extends TDefaultOptions>(defaults: TDefaultOptions | Partial<TDefaultOptions> | undefined, options: TOptions | Partial<TOptions>): TOptions & TDefaultOptions;
export {};
//# sourceMappingURL=mergeOptions.d.ts.map

View File

@@ -0,0 +1,8 @@
import { __assign } from "tslib";
import { compact } from "./compact.js";
export function mergeOptions(defaults, options) {
return compact(defaults, options, options.variables && {
variables: compact(__assign(__assign({}, (defaults && defaults.variables)), options.variables)),
});
}
//# sourceMappingURL=mergeOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"mergeOptions.js","sourceRoot":"","sources":["../../../src/utilities/common/mergeOptions.ts"],"names":[],"mappings":";AAOA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAOvC,MAAM,UAAU,YAAY,CAI1B,QAAgE,EAChE,OAAqC;IAErC,OAAO,OAAO,CACZ,QAAQ,EACR,OAAO,EACP,OAAO,CAAC,SAAS,IAAI;QACnB,SAAS,EAAE,OAAO,uBACb,CAAC,QAAQ,IAAI,QAAQ,CAAC,SAAS,CAAC,GAChC,OAAO,CAAC,SAAS,EACpB;KACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n QueryOptions,\n WatchQueryOptions,\n MutationOptions,\n OperationVariables,\n} from \"../../core/index.js\";\n\nimport { compact } from \"./compact.js\";\n\ntype OptionsUnion<TData, TVariables extends OperationVariables, TContext> =\n | WatchQueryOptions<TVariables, TData>\n | QueryOptions<TVariables, TData>\n | MutationOptions<TData, TVariables, TContext, any>;\n\nexport function mergeOptions<\n TDefaultOptions extends Partial<OptionsUnion<any, any, any>>,\n TOptions extends TDefaultOptions,\n>(\n defaults: TDefaultOptions | Partial<TDefaultOptions> | undefined,\n options: TOptions | Partial<TOptions>\n): TOptions & TDefaultOptions {\n return compact(\n defaults,\n options,\n options.variables && {\n variables: compact({\n ...(defaults && defaults.variables),\n ...options.variables,\n }),\n }\n );\n}\n"]}

View File

@@ -0,0 +1,3 @@
export declare function isNonNullObject(obj: any): obj is Record<string | number, any>;
export declare function isPlainObject(obj: any): obj is Record<string | number, any>;
//# sourceMappingURL=objects.d.ts.map

View File

@@ -0,0 +1,10 @@
export function isNonNullObject(obj) {
return obj !== null && typeof obj === "object";
}
export function isPlainObject(obj) {
return (obj !== null &&
typeof obj === "object" &&
(Object.getPrototypeOf(obj) === Object.prototype ||
Object.getPrototypeOf(obj) === null));
}
//# sourceMappingURL=objects.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"objects.js","sourceRoot":"","sources":["../../../src/utilities/common/objects.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,eAAe,CAAC,GAAQ;IACtC,OAAO,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,CAAC;AACjD,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,GAAQ;IACpC,OAAO,CACL,GAAG,KAAK,IAAI;QACZ,OAAO,GAAG,KAAK,QAAQ;QACvB,CAAC,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC,SAAS;YAC9C,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,CACvC,CAAC;AACJ,CAAC","sourcesContent":["export function isNonNullObject(obj: any): obj is Record<string | number, any> {\n return obj !== null && typeof obj === \"object\";\n}\n\nexport function isPlainObject(obj: any): obj is Record<string | number, any> {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n (Object.getPrototypeOf(obj) === Object.prototype ||\n Object.getPrototypeOf(obj) === null)\n );\n}\n"]}

View File

@@ -0,0 +1,3 @@
import type { DeepOmit } from "../types/DeepOmit.js";
export declare function omitDeep<T, K extends string>(value: T, key: K): DeepOmit<T, K>;
//# sourceMappingURL=omitDeep.d.ts.map

View File

@@ -0,0 +1,41 @@
import { isPlainObject } from "./objects.js";
export function omitDeep(value, key) {
return __omitDeep(value, key);
}
function __omitDeep(value, key, known) {
if (known === void 0) { known = new Map(); }
if (known.has(value)) {
return known.get(value);
}
var modified = false;
if (Array.isArray(value)) {
var array_1 = [];
known.set(value, array_1);
value.forEach(function (value, index) {
var result = __omitDeep(value, key, known);
modified || (modified = result !== value);
array_1[index] = result;
});
if (modified) {
return array_1;
}
}
else if (isPlainObject(value)) {
var obj_1 = Object.create(Object.getPrototypeOf(value));
known.set(value, obj_1);
Object.keys(value).forEach(function (k) {
if (k === key) {
modified = true;
return;
}
var result = __omitDeep(value[k], key, known);
modified || (modified = result !== value[k]);
obj_1[k] = result;
});
if (modified) {
return obj_1;
}
}
return value;
}
//# sourceMappingURL=omitDeep.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"omitDeep.js","sourceRoot":"","sources":["../../../src/utilities/common/omitDeep.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,UAAU,QAAQ,CAAsB,KAAQ,EAAE,GAAM;IAC5D,OAAO,UAAU,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,UAAU,CACjB,KAAQ,EACR,GAAM,EACN,KAA2B;IAA3B,sBAAA,EAAA,YAAY,GAAG,EAAY;IAE3B,IAAI,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC1B,CAAC;IAED,IAAI,QAAQ,GAAG,KAAK,CAAC;IAErB,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,IAAM,OAAK,GAAU,EAAE,CAAC;QACxB,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,OAAK,CAAC,CAAC;QAExB,KAAK,CAAC,OAAO,CAAC,UAAC,KAAK,EAAE,KAAK;YACzB,IAAM,MAAM,GAAG,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;YAC7C,QAAQ,KAAR,QAAQ,GAAK,MAAM,KAAK,KAAK,EAAC;YAE9B,OAAK,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC;QACxB,CAAC,CAAC,CAAC;QAEH,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,OAAuB,CAAC;QACjC,CAAC;IACH,CAAC;SAAM,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;QAChC,IAAM,KAAG,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC;QACxD,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,KAAG,CAAC,CAAC;QAEtB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,UAAC,CAAC;YAC3B,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;gBACd,QAAQ,GAAG,IAAI,CAAC;gBAChB,OAAO;YACT,CAAC;YAED,IAAM,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;YAChD,QAAQ,KAAR,QAAQ,GAAK,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,EAAC;YAEjC,KAAG,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC;QAClB,CAAC,CAAC,CAAC;QAEH,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,KAAG,CAAC;QACb,CAAC;IACH,CAAC;IAED,OAAO,KAAuB,CAAC;AACjC,CAAC","sourcesContent":["import type { DeepOmit } from \"../types/DeepOmit.js\";\nimport { isPlainObject } from \"./objects.js\";\n\nexport function omitDeep<T, K extends string>(value: T, key: K) {\n return __omitDeep(value, key);\n}\n\nfunction __omitDeep<T, K extends string>(\n value: T,\n key: K,\n known = new Map<any, any>()\n): DeepOmit<T, K> {\n if (known.has(value)) {\n return known.get(value);\n }\n\n let modified = false;\n\n if (Array.isArray(value)) {\n const array: any[] = [];\n known.set(value, array);\n\n value.forEach((value, index) => {\n const result = __omitDeep(value, key, known);\n modified ||= result !== value;\n\n array[index] = result;\n });\n\n if (modified) {\n return array as DeepOmit<T, K>;\n }\n } else if (isPlainObject(value)) {\n const obj = Object.create(Object.getPrototypeOf(value));\n known.set(value, obj);\n\n Object.keys(value).forEach((k) => {\n if (k === key) {\n modified = true;\n return;\n }\n\n const result = __omitDeep(value[k], key, known);\n modified ||= result !== value[k];\n\n obj[k] = result;\n });\n\n if (modified) {\n return obj;\n }\n }\n\n return value as DeepOmit<T, K>;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare function stringifyForDisplay(value: any, space?: number): string;
//# sourceMappingURL=stringifyForDisplay.d.ts.map

View File

@@ -0,0 +1,11 @@
import { makeUniqueId } from "./makeUniqueId.js";
export function stringifyForDisplay(value, space) {
if (space === void 0) { space = 0; }
var undefId = makeUniqueId("stringifyForDisplay");
return JSON.stringify(value, function (key, value) {
return value === void 0 ? undefId : value;
}, space)
.split(JSON.stringify(undefId))
.join("<undefined>");
}
//# sourceMappingURL=stringifyForDisplay.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"stringifyForDisplay.js","sourceRoot":"","sources":["../../../src/utilities/common/stringifyForDisplay.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,MAAM,UAAU,mBAAmB,CAAC,KAAU,EAAE,KAAS;IAAT,sBAAA,EAAA,SAAS;IACvD,IAAM,OAAO,GAAG,YAAY,CAAC,qBAAqB,CAAC,CAAC;IACpD,OAAO,IAAI,CAAC,SAAS,CACnB,KAAK,EACL,UAAC,GAAG,EAAE,KAAK;QACT,OAAO,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC;IAC5C,CAAC,EACD,KAAK,CACN;SACE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;SAC9B,IAAI,CAAC,aAAa,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import { makeUniqueId } from \"./makeUniqueId.js\";\n\nexport function stringifyForDisplay(value: any, space = 0): string {\n const undefId = makeUniqueId(\"stringifyForDisplay\");\n return JSON.stringify(\n value,\n (key, value) => {\n return value === void 0 ? undefId : value;\n },\n space\n )\n .split(JSON.stringify(undefId))\n .join(\"<undefined>\");\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare function stripTypename<T>(value: T): import("../index.js").DeepOmit<T, "__typename">;
//# sourceMappingURL=stripTypename.d.ts.map

View File

@@ -0,0 +1,5 @@
import { omitDeep } from "./omitDeep.js";
export function stripTypename(value) {
return omitDeep(value, "__typename");
}
//# sourceMappingURL=stripTypename.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"stripTypename.js","sourceRoot":"","sources":["../../../src/utilities/common/stripTypename.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,MAAM,UAAU,aAAa,CAAI,KAAQ;IACvC,OAAO,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import { omitDeep } from \"./omitDeep.js\";\n\nexport function stripTypename<T>(value: T) {\n return omitDeep(value, \"__typename\");\n}\n"]}

View File

@@ -0,0 +1,8 @@
declare global {
interface Window {
__DEV__?: boolean;
}
}
declare const _default: typeof globalThis & Window;
export default _default;
//# sourceMappingURL=global.d.ts.map

View File

@@ -0,0 +1,14 @@
import { maybe } from "./maybe.js";
export default (maybe(function () { return globalThis; }) ||
maybe(function () { return window; }) ||
maybe(function () { return self; }) ||
maybe(function () { return global; }) || // We don't expect the Function constructor ever to be invoked at runtime, as
// long as at least one of globalThis, window, self, or global is defined, so
// we are under no obligation to make it easy for static analysis tools to
// detect syntactic usage of the Function constructor. If you think you can
// improve your static analysis to detect this obfuscation, think again. This
// is an arms race you cannot win, at least not in JavaScript.
maybe(function () {
return maybe.constructor("return this")();
}));
//# sourceMappingURL=global.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"global.js","sourceRoot":"","sources":["../../../src/utilities/globals/global.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AASnC,eAAe,CAAC,KAAK,CAAC,cAAM,OAAA,UAAU,EAAV,CAAU,CAAC;IACrC,KAAK,CAAC,cAAM,OAAA,MAAM,EAAN,CAAM,CAAC;IACnB,KAAK,CAAC,cAAM,OAAA,IAAI,EAAJ,CAAI,CAAC;IACjB,KAAK,CAAC,cAAM,OAAA,MAAM,EAAN,CAAM,CAAC;IACnB,6EAA6E;IAC7E,6EAA6E;IAC7E,0EAA0E;IAC1E,2EAA2E;IAC3E,6EAA6E;IAC7E,8DAA8D;IAC9D,KAAK,CAAC;QACJ,OAAO,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC;IAC5C,CAAC,CAAC,CAA+B,CAAC","sourcesContent":["import { maybe } from \"./maybe.js\";\n\ndeclare global {\n const __DEV__: boolean; // will be removed in `dist` by the `postprocessDist` script\n interface Window {\n __DEV__?: boolean;\n }\n}\n\nexport default (maybe(() => globalThis) ||\n maybe(() => window) ||\n maybe(() => self) ||\n maybe(() => global) ||\n // We don't expect the Function constructor ever to be invoked at runtime, as\n // long as at least one of globalThis, window, self, or global is defined, so\n // we are under no obligation to make it easy for static analysis tools to\n // detect syntactic usage of the Function constructor. If you think you can\n // improve your static analysis to detect this obfuscation, think again. This\n // is an arms race you cannot win, at least not in JavaScript.\n maybe(function () {\n return maybe.constructor(\"return this\")();\n })) as typeof globalThis & Window;\n"]}

View File

@@ -0,0 +1,119 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tsInvariant = require('ts-invariant');
var version = "3.13.8";
function maybe(thunk) {
try {
return thunk();
}
catch (_a) { }
}
var global$1 = (maybe(function () { return globalThis; }) ||
maybe(function () { return window; }) ||
maybe(function () { return self; }) ||
maybe(function () { return global; }) ||
maybe(function () {
return maybe.constructor("return this")();
}));
var prefixCounts = new Map();
function makeUniqueId(prefix) {
var count = prefixCounts.get(prefix) || 1;
prefixCounts.set(prefix, count + 1);
return "".concat(prefix, ":").concat(count, ":").concat(Math.random().toString(36).slice(2));
}
function stringifyForDisplay(value, space) {
if (space === void 0) { space = 0; }
var undefId = makeUniqueId("stringifyForDisplay");
return JSON.stringify(value, function (key, value) {
return value === void 0 ? undefId : value;
}, space)
.split(JSON.stringify(undefId))
.join("<undefined>");
}
function wrap(fn) {
return function (message) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (typeof message === "number") {
var arg0 = message;
message = getHandledErrorMsg(arg0);
if (!message) {
message = getFallbackErrorMsg(arg0, args);
args = [];
}
}
fn.apply(void 0, [message].concat(args));
};
}
var invariant = Object.assign(function invariant(condition, message) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
if (!condition) {
tsInvariant.invariant(condition, getHandledErrorMsg(message, args) || getFallbackErrorMsg(message, args));
}
}, {
debug: wrap(tsInvariant.invariant.debug),
log: wrap(tsInvariant.invariant.log),
warn: wrap(tsInvariant.invariant.warn),
error: wrap(tsInvariant.invariant.error),
});
function newInvariantError(message) {
var optionalParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
optionalParams[_i - 1] = arguments[_i];
}
return new tsInvariant.InvariantError(getHandledErrorMsg(message, optionalParams) ||
getFallbackErrorMsg(message, optionalParams));
}
var ApolloErrorMessageHandler = Symbol.for("ApolloErrorMessageHandler_" + version);
function stringify(arg) {
if (typeof arg == "string") {
return arg;
}
try {
return stringifyForDisplay(arg, 2).slice(0, 1000);
}
catch (_a) {
return "<non-serializable>";
}
}
function getHandledErrorMsg(message, messageArgs) {
if (messageArgs === void 0) { messageArgs = []; }
if (!message)
return;
return (global$1[ApolloErrorMessageHandler] &&
global$1[ApolloErrorMessageHandler](message, messageArgs.map(stringify)));
}
function getFallbackErrorMsg(message, messageArgs) {
if (messageArgs === void 0) { messageArgs = []; }
if (!message)
return;
return "An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#".concat(encodeURIComponent(JSON.stringify({
version: version,
message: message,
args: messageArgs.map(stringify),
})));
}
var DEV = globalThis.__DEV__ !== false;
exports.InvariantError = tsInvariant.InvariantError;
exports.DEV = DEV;
exports.__DEV__ = DEV;
exports.global = global$1;
exports.invariant = invariant;
exports.maybe = maybe;
exports.newInvariantError = newInvariantError;
//# sourceMappingURL=globals.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,119 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tsInvariant = require('ts-invariant');
var version = "3.13.8";
function maybe(thunk) {
try {
return thunk();
}
catch (_a) { }
}
var global$1 = (maybe(function () { return globalThis; }) ||
maybe(function () { return window; }) ||
maybe(function () { return self; }) ||
maybe(function () { return global; }) ||
maybe(function () {
return maybe.constructor("return this")();
}));
var prefixCounts = new Map();
function makeUniqueId(prefix) {
var count = prefixCounts.get(prefix) || 1;
prefixCounts.set(prefix, count + 1);
return "".concat(prefix, ":").concat(count, ":").concat(Math.random().toString(36).slice(2));
}
function stringifyForDisplay(value, space) {
if (space === void 0) { space = 0; }
var undefId = makeUniqueId("stringifyForDisplay");
return JSON.stringify(value, function (key, value) {
return value === void 0 ? undefId : value;
}, space)
.split(JSON.stringify(undefId))
.join("<undefined>");
}
function wrap(fn) {
return function (message) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (typeof message === "number") {
var arg0 = message;
message = getHandledErrorMsg(arg0);
if (!message) {
message = getFallbackErrorMsg(arg0, args);
args = [];
}
}
fn.apply(void 0, [message].concat(args));
};
}
var invariant = Object.assign(function invariant(condition, message) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
if (!condition) {
tsInvariant.invariant(condition, getHandledErrorMsg(message, args) || getFallbackErrorMsg(message, args));
}
}, {
debug: wrap(tsInvariant.invariant.debug),
log: wrap(tsInvariant.invariant.log),
warn: wrap(tsInvariant.invariant.warn),
error: wrap(tsInvariant.invariant.error),
});
function newInvariantError(message) {
var optionalParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
optionalParams[_i - 1] = arguments[_i];
}
return new tsInvariant.InvariantError(getHandledErrorMsg(message, optionalParams) ||
getFallbackErrorMsg(message, optionalParams));
}
var ApolloErrorMessageHandler = Symbol.for("ApolloErrorMessageHandler_" + version);
function stringify(arg) {
if (typeof arg == "string") {
return arg;
}
try {
return stringifyForDisplay(arg, 2).slice(0, 1000);
}
catch (_a) {
return "<non-serializable>";
}
}
function getHandledErrorMsg(message, messageArgs) {
if (messageArgs === void 0) { messageArgs = []; }
if (!message)
return;
return (global$1[ApolloErrorMessageHandler] &&
global$1[ApolloErrorMessageHandler](message, messageArgs.map(stringify)));
}
function getFallbackErrorMsg(message, messageArgs) {
if (messageArgs === void 0) { messageArgs = []; }
if (!message)
return;
return "An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#".concat(encodeURIComponent(JSON.stringify({
version: version,
message: message,
args: messageArgs.map(stringify),
})));
}
var DEV = globalThis.__DEV__ !== false;
exports.InvariantError = tsInvariant.InvariantError;
exports.DEV = DEV;
exports.__DEV__ = DEV;
exports.global = global$1;
exports.invariant = invariant;
exports.maybe = maybe;
exports.newInvariantError = newInvariantError;
//# sourceMappingURL=globals.cjs.map

View File

@@ -0,0 +1 @@
export * from "./index.d.ts";

View File

@@ -0,0 +1,11 @@
import { invariant, newInvariantError, InvariantError } from "./invariantWrappers.js";
export { maybe } from "./maybe.js";
export { default as global } from "./global.js";
export { invariant, newInvariantError, InvariantError };
/**
* @deprecated we do not use this internally anymore,
* it is just exported for backwards compatibility
*/
export declare const DEV: boolean;
export { DEV as __DEV__ };
//# sourceMappingURL=index.d.ts.map

14
node_modules/@apollo/client/utilities/globals/index.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { invariant, newInvariantError, InvariantError, } from "./invariantWrappers.js";
export { maybe } from "./maybe.js";
export { default as global } from "./global.js";
export { invariant, newInvariantError, InvariantError };
/**
* @deprecated we do not use this internally anymore,
* it is just exported for backwards compatibility
*/
// this file is extempt from automatic `__DEV__` replacement
// so we have to write it out here
// @ts-ignore
export var DEV = globalThis.__DEV__ !== false;
export { DEV as __DEV__ };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utilities/globals/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,cAAc,GACf,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,cAAc,EAAE,CAAC;AAExD;;;GAGG;AACH,4DAA4D;AAC5D,kCAAkC;AAClC,aAAa;AACb,MAAM,CAAC,IAAM,GAAG,GAAG,UAAU,CAAC,OAAO,KAAK,KAAK,CAAC;AAChD,OAAO,EAAE,GAAG,IAAI,OAAO,EAAE,CAAC","sourcesContent":["import {\n invariant,\n newInvariantError,\n InvariantError,\n} from \"./invariantWrappers.js\";\n\nexport { maybe } from \"./maybe.js\";\nexport { default as global } from \"./global.js\";\nexport { invariant, newInvariantError, InvariantError };\n\n/**\n * @deprecated we do not use this internally anymore,\n * it is just exported for backwards compatibility\n */\n// this file is extempt from automatic `__DEV__` replacement\n// so we have to write it out here\n// @ts-ignore\nexport const DEV = globalThis.__DEV__ !== false;\nexport { DEV as __DEV__ };\n"]}

View File

@@ -0,0 +1,64 @@
import { InvariantError } from "ts-invariant";
import type { ErrorCodes } from "../../invariantErrorCodes.js";
type LogFunction = {
/**
* Logs a `$level` message if the user used `ts-invariant`'s `setVerbosity` to set
* a verbosity level of `$level` or lower. (defaults to `"log"`).
*
* The user will either be presented with a link to the documentation for the message,
* or they can use the `loadDevMessages` to add the message strings to the bundle.
* The documentation will display the message without argument substitution.
* Instead, the arguments will be printed on the console after the link.
*
* `message` can only be a string, a concatenation of strings, or a ternary statement
* that results in a string. This will be enforced on build, where the message will
* be replaced with a message number.
*
* String substitutions like %s, %o, %d or %f are supported.
*/
(message?: any, ...optionalParams: unknown[]): void;
};
type WrappedInvariant = {
/**
* Throws and InvariantError with the given message if the condition is false.
*
* `message` can only be a string, a concatenation of strings, or a ternary statement
* that results in a string. This will be enforced on build, where the message will
* be replaced with a message number.
*
* The user will either be presented with a link to the documentation for the message,
* or they can use the `loadErrorMessages` to add the message strings to the bundle.
* The documentation will display the message with the arguments substituted.
*
* String substitutions with %s are supported and will also return
* pretty-stringified objects.
* Excess `optionalParams` will be swallowed.
*/
(condition: any, message?: string | number, ...optionalParams: unknown[]): asserts condition;
debug: LogFunction;
log: LogFunction;
warn: LogFunction;
error: LogFunction;
};
declare const invariant: WrappedInvariant;
/**
* Returns an InvariantError.
*
* `message` can only be a string, a concatenation of strings, or a ternary statement
* that results in a string. This will be enforced on build, where the message will
* be replaced with a message number.
* String substitutions with %s are supported and will also return
* pretty-stringified objects.
* Excess `optionalParams` will be swallowed.
*/
declare function newInvariantError(message?: string | number, ...optionalParams: unknown[]): InvariantError;
declare const ApolloErrorMessageHandler: unique symbol;
declare global {
interface Window {
[ApolloErrorMessageHandler]?: {
(message: string | number, args: string[]): string | undefined;
} & ErrorCodes;
}
}
export { invariant, InvariantError, newInvariantError, ApolloErrorMessageHandler, };
//# sourceMappingURL=invariantWrappers.d.ts.map

View File

@@ -0,0 +1,84 @@
import { invariant as originalInvariant, InvariantError } from "ts-invariant";
import { version } from "../../version.js";
import global from "./global.js";
import { stringifyForDisplay } from "../common/stringifyForDisplay.js";
function wrap(fn) {
return function (message) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (typeof message === "number") {
var arg0 = message;
message = getHandledErrorMsg(arg0);
if (!message) {
message = getFallbackErrorMsg(arg0, args);
args = [];
}
}
fn.apply(void 0, [message].concat(args));
};
}
var invariant = Object.assign(function invariant(condition, message) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
if (!condition) {
originalInvariant(condition, getHandledErrorMsg(message, args) || getFallbackErrorMsg(message, args));
}
}, {
debug: wrap(originalInvariant.debug),
log: wrap(originalInvariant.log),
warn: wrap(originalInvariant.warn),
error: wrap(originalInvariant.error),
});
/**
* Returns an InvariantError.
*
* `message` can only be a string, a concatenation of strings, or a ternary statement
* that results in a string. This will be enforced on build, where the message will
* be replaced with a message number.
* String substitutions with %s are supported and will also return
* pretty-stringified objects.
* Excess `optionalParams` will be swallowed.
*/
function newInvariantError(message) {
var optionalParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
optionalParams[_i - 1] = arguments[_i];
}
return new InvariantError(getHandledErrorMsg(message, optionalParams) ||
getFallbackErrorMsg(message, optionalParams));
}
var ApolloErrorMessageHandler = Symbol.for("ApolloErrorMessageHandler_" + version);
function stringify(arg) {
if (typeof arg == "string") {
return arg;
}
try {
return stringifyForDisplay(arg, 2).slice(0, 1000);
}
catch (_a) {
return "<non-serializable>";
}
}
function getHandledErrorMsg(message, messageArgs) {
if (messageArgs === void 0) { messageArgs = []; }
if (!message)
return;
return (global[ApolloErrorMessageHandler] &&
global[ApolloErrorMessageHandler](message, messageArgs.map(stringify)));
}
function getFallbackErrorMsg(message, messageArgs) {
if (messageArgs === void 0) { messageArgs = []; }
if (!message)
return;
return "An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#".concat(encodeURIComponent(JSON.stringify({
version: version,
message: message,
args: messageArgs.map(stringify),
})));
}
export { invariant, InvariantError, newInvariantError, ApolloErrorMessageHandler, };
//# sourceMappingURL=invariantWrappers.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export declare function maybe<T>(thunk: () => T): T | undefined;
//# sourceMappingURL=maybe.d.ts.map

View File

@@ -0,0 +1,7 @@
export function maybe(thunk) {
try {
return thunk();
}
catch (_a) { }
}
//# sourceMappingURL=maybe.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"maybe.js","sourceRoot":"","sources":["../../../src/utilities/globals/maybe.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,KAAK,CAAI,KAAc;IACrC,IAAI,CAAC;QACH,OAAO,KAAK,EAAE,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC,CAAA,CAAC;AACZ,CAAC","sourcesContent":["export function maybe<T>(thunk: () => T): T | undefined {\n try {\n return thunk();\n } catch {}\n}\n"]}

View File

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

View File

@@ -0,0 +1,50 @@
import type { DocumentNode } from "graphql";
export type DocumentTransformCacheKey = ReadonlyArray<unknown>;
type TransformFn = (document: DocumentNode) => DocumentNode;
interface DocumentTransformOptions {
/**
* Determines whether to cache the transformed GraphQL document. Caching can speed up repeated calls to the document transform for the same input document. Set to `false` to completely disable caching for the document transform. When disabled, this option takes precedence over the [`getCacheKey`](#getcachekey) option.
*
* The default value is `true`.
*/
cache?: boolean;
/**
* Defines a custom cache key for a GraphQL document that will determine whether to re-run the document transform when given the same input GraphQL document. Returns an array that defines the cache key. Return `undefined` to disable caching for that GraphQL document.
*
* > **Note:** The items in the array may be any type, but also need to be referentially stable to guarantee a stable cache key.
*
* The default implementation of this function returns the `document` as the cache key.
*/
getCacheKey?: (document: DocumentNode) => DocumentTransformCacheKey | undefined;
}
export declare class DocumentTransform {
private readonly transform;
private cached;
private readonly resultCache;
private getCacheKey;
static identity(): DocumentTransform;
static split(predicate: (document: DocumentNode) => boolean, left: DocumentTransform, right?: DocumentTransform): DocumentTransform & {
left: DocumentTransform;
right: DocumentTransform;
};
constructor(transform: TransformFn, options?: DocumentTransformOptions);
/**
* Resets the internal cache of this transform, if it has one.
*/
resetCache(): void;
private performWork;
transformDocument(document: DocumentNode): DocumentNode;
concat(otherTransform: DocumentTransform): DocumentTransform;
/**
* @internal
* Used to iterate through all transforms that are concatenations or `split` links.
*/
readonly left?: DocumentTransform;
/**
* @internal
* Used to iterate through all transforms that are concatenations or `split` links.
*/
readonly right?: DocumentTransform;
}
export {};
//# sourceMappingURL=DocumentTransform.d.ts.map

View File

@@ -0,0 +1,94 @@
import { Trie } from "@wry/trie";
import { canUseWeakMap, canUseWeakSet } from "../common/canUse.js";
import { checkDocument } from "./getFromAST.js";
import { invariant } from "../globals/index.js";
import { WeakCache } from "@wry/caches";
import { wrap } from "optimism";
import { cacheSizes } from "../caching/index.js";
function identity(document) {
return document;
}
var DocumentTransform = /** @class */ (function () {
function DocumentTransform(transform, options) {
if (options === void 0) { options = Object.create(null); }
this.resultCache = canUseWeakSet ? new WeakSet() : new Set();
this.transform = transform;
if (options.getCacheKey) {
// Override default `getCacheKey` function, which returns [document].
this.getCacheKey = options.getCacheKey;
}
this.cached = options.cache !== false;
this.resetCache();
}
// This default implementation of getCacheKey can be overridden by providing
// options.getCacheKey to the DocumentTransform constructor. In general, a
// getCacheKey function may either return an array of keys (often including
// the document) to be used as a cache key, or undefined to indicate the
// transform for this document should not be cached.
DocumentTransform.prototype.getCacheKey = function (document) {
return [document];
};
DocumentTransform.identity = function () {
// No need to cache this transform since it just returns the document
// unchanged. This should save a bit of memory that would otherwise be
// needed to populate the `documentCache` of this transform.
return new DocumentTransform(identity, { cache: false });
};
DocumentTransform.split = function (predicate, left, right) {
if (right === void 0) { right = DocumentTransform.identity(); }
return Object.assign(new DocumentTransform(function (document) {
var documentTransform = predicate(document) ? left : right;
return documentTransform.transformDocument(document);
},
// Reasonably assume both `left` and `right` transforms handle their own caching
{ cache: false }), { left: left, right: right });
};
/**
* Resets the internal cache of this transform, if it has one.
*/
DocumentTransform.prototype.resetCache = function () {
var _this = this;
if (this.cached) {
var stableCacheKeys_1 = new Trie(canUseWeakMap);
this.performWork = wrap(DocumentTransform.prototype.performWork.bind(this), {
makeCacheKey: function (document) {
var cacheKeys = _this.getCacheKey(document);
if (cacheKeys) {
invariant(Array.isArray(cacheKeys), 77);
return stableCacheKeys_1.lookupArray(cacheKeys);
}
},
max: cacheSizes["documentTransform.cache"],
cache: (WeakCache),
});
}
};
DocumentTransform.prototype.performWork = function (document) {
checkDocument(document);
return this.transform(document);
};
DocumentTransform.prototype.transformDocument = function (document) {
// If a user passes an already transformed result back to this function,
// immediately return it.
if (this.resultCache.has(document)) {
return document;
}
var transformedDocument = this.performWork(document);
this.resultCache.add(transformedDocument);
return transformedDocument;
};
DocumentTransform.prototype.concat = function (otherTransform) {
var _this = this;
return Object.assign(new DocumentTransform(function (document) {
return otherTransform.transformDocument(_this.transformDocument(document));
},
// Reasonably assume both transforms handle their own caching
{ cache: false }), {
left: this,
right: otherTransform,
});
};
return DocumentTransform;
}());
export { DocumentTransform };
//# sourceMappingURL=DocumentTransform.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,20 @@
import type { SelectionNode, DirectiveNode, DocumentNode, ArgumentNode, ASTNode, FragmentSpreadNode } from "graphql";
export type DirectiveInfo = {
[fieldName: string]: {
[argName: string]: any;
};
};
export declare function shouldInclude({ directives }: SelectionNode, variables?: Record<string, any>): boolean;
export declare function getDirectiveNames(root: ASTNode): string[];
export declare const hasAnyDirectives: (names: string[], root: ASTNode) => boolean;
export declare const hasAllDirectives: (names: string[], root: ASTNode) => boolean;
export declare function hasDirectives(names: string[], root: ASTNode, all?: boolean): boolean;
export declare function hasClientExports(document: DocumentNode): boolean;
export type InclusionDirectives = Array<{
directive: DirectiveNode;
ifArgument: ArgumentNode;
}>;
export declare function getInclusionDirectives(directives: ReadonlyArray<DirectiveNode>): InclusionDirectives;
/** @internal */
export declare function getFragmentMaskMode(fragment: FragmentSpreadNode): "mask" | "migrate" | "unmask";
//# sourceMappingURL=directives.d.ts.map

View File

@@ -0,0 +1,112 @@
import { invariant } from "../globals/index.js";
import { visit, BREAK, Kind } from "graphql";
export function shouldInclude(_a, variables) {
var directives = _a.directives;
if (!directives || !directives.length) {
return true;
}
return getInclusionDirectives(directives).every(function (_a) {
var directive = _a.directive, ifArgument = _a.ifArgument;
var evaledValue = false;
if (ifArgument.value.kind === "Variable") {
evaledValue =
variables && variables[ifArgument.value.name.value];
invariant(evaledValue !== void 0, 78, directive.name.value);
}
else {
evaledValue = ifArgument.value.value;
}
return directive.name.value === "skip" ? !evaledValue : evaledValue;
});
}
export function getDirectiveNames(root) {
var names = [];
visit(root, {
Directive: function (node) {
names.push(node.name.value);
},
});
return names;
}
export var hasAnyDirectives = function (names, root) {
return hasDirectives(names, root, false);
};
export var hasAllDirectives = function (names, root) {
return hasDirectives(names, root, true);
};
export function hasDirectives(names, root, all) {
var nameSet = new Set(names);
var uniqueCount = nameSet.size;
visit(root, {
Directive: function (node) {
if (nameSet.delete(node.name.value) && (!all || !nameSet.size)) {
return BREAK;
}
},
});
// If we found all the names, nameSet will be empty. If we only care about
// finding some of them, the < condition is sufficient.
return all ? !nameSet.size : nameSet.size < uniqueCount;
}
export function hasClientExports(document) {
return document && hasDirectives(["client", "export"], document, true);
}
function isInclusionDirective(_a) {
var value = _a.name.value;
return value === "skip" || value === "include";
}
export function getInclusionDirectives(directives) {
var result = [];
if (directives && directives.length) {
directives.forEach(function (directive) {
if (!isInclusionDirective(directive))
return;
var directiveArguments = directive.arguments;
var directiveName = directive.name.value;
invariant(directiveArguments && directiveArguments.length === 1, 79, directiveName);
var ifArgument = directiveArguments[0];
invariant(ifArgument.name && ifArgument.name.value === "if", 80, directiveName);
var ifValue = ifArgument.value;
// means it has to be a variable value if this is a valid @skip or @include directive
invariant(ifValue &&
(ifValue.kind === "Variable" || ifValue.kind === "BooleanValue"), 81, directiveName);
result.push({ directive: directive, ifArgument: ifArgument });
});
}
return result;
}
/** @internal */
export function getFragmentMaskMode(fragment) {
var _a, _b;
var directive = (_a = fragment.directives) === null || _a === void 0 ? void 0 : _a.find(function (_a) {
var name = _a.name;
return name.value === "unmask";
});
if (!directive) {
return "mask";
}
var modeArg = (_b = directive.arguments) === null || _b === void 0 ? void 0 : _b.find(function (_a) {
var name = _a.name;
return name.value === "mode";
});
if (globalThis.__DEV__ !== false) {
if (modeArg) {
if (modeArg.value.kind === Kind.VARIABLE) {
globalThis.__DEV__ !== false && invariant.warn(82);
}
else if (modeArg.value.kind !== Kind.STRING) {
globalThis.__DEV__ !== false && invariant.warn(83);
}
else if (modeArg.value.value !== "migrate") {
globalThis.__DEV__ !== false && invariant.warn(84, modeArg.value.value);
}
}
}
if (modeArg &&
"value" in modeArg.value &&
modeArg.value.value === "migrate") {
return "migrate";
}
return "unmask";
}
//# sourceMappingURL=directives.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,35 @@
import type { DocumentNode, FragmentDefinitionNode, InlineFragmentNode, SelectionNode } from "graphql";
/**
* Returns a query document which adds a single query operation that only
* spreads the target fragment inside of it.
*
* So for example a document of:
*
* ```graphql
* fragment foo on Foo { a b c }
* ```
*
* Turns into:
*
* ```graphql
* { ...foo }
*
* fragment foo on Foo { a b c }
* ```
*
* The target fragment will either be the only fragment in the document, or a
* fragment specified by the provided `fragmentName`. If there is more than one
* fragment, but a `fragmentName` was not defined then an error will be thrown.
*/
export declare function getFragmentQueryDocument(document: DocumentNode, fragmentName?: string): DocumentNode;
/**
* This is an interface that describes a map from fragment names to fragment definitions.
*/
export interface FragmentMap {
[fragmentName: string]: FragmentDefinitionNode;
}
export type FragmentMapFunction = (fragmentName: string) => FragmentDefinitionNode | null;
export declare function createFragmentMap(fragments?: FragmentDefinitionNode[]): FragmentMap;
export declare function getFragmentFromSelection(selection: SelectionNode, fragmentMap?: FragmentMap | FragmentMapFunction): InlineFragmentNode | FragmentDefinitionNode | null;
export declare function isFullyUnmaskedOperation(document: DocumentNode): boolean;
//# sourceMappingURL=fragments.d.ts.map

View File

@@ -0,0 +1,118 @@
import { __assign, __spreadArray } from "tslib";
import { invariant, newInvariantError } from "../globals/index.js";
import { BREAK, visit } from "graphql";
/**
* Returns a query document which adds a single query operation that only
* spreads the target fragment inside of it.
*
* So for example a document of:
*
* ```graphql
* fragment foo on Foo { a b c }
* ```
*
* Turns into:
*
* ```graphql
* { ...foo }
*
* fragment foo on Foo { a b c }
* ```
*
* The target fragment will either be the only fragment in the document, or a
* fragment specified by the provided `fragmentName`. If there is more than one
* fragment, but a `fragmentName` was not defined then an error will be thrown.
*/
export function getFragmentQueryDocument(document, fragmentName) {
var actualFragmentName = fragmentName;
// Build an array of all our fragment definitions that will be used for
// validations. We also do some validations on the other definitions in the
// document while building this list.
var fragments = [];
document.definitions.forEach(function (definition) {
// Throw an error if we encounter an operation definition because we will
// define our own operation definition later on.
if (definition.kind === "OperationDefinition") {
throw newInvariantError(
85,
definition.operation,
definition.name ? " named '".concat(definition.name.value, "'") : ""
);
}
// Add our definition to the fragments array if it is a fragment
// definition.
if (definition.kind === "FragmentDefinition") {
fragments.push(definition);
}
});
// If the user did not give us a fragment name then let us try to get a
// name from a single fragment in the definition.
if (typeof actualFragmentName === "undefined") {
invariant(fragments.length === 1, 86, fragments.length);
actualFragmentName = fragments[0].name.value;
}
// Generate a query document with an operation that simply spreads the
// fragment inside of it.
var query = __assign(__assign({}, document), { definitions: __spreadArray([
{
kind: "OperationDefinition",
// OperationTypeNode is an enum
operation: "query",
selectionSet: {
kind: "SelectionSet",
selections: [
{
kind: "FragmentSpread",
name: {
kind: "Name",
value: actualFragmentName,
},
},
],
},
}
], document.definitions, true) });
return query;
}
// Utility function that takes a list of fragment definitions and makes a hash out of them
// that maps the name of the fragment to the fragment definition.
export function createFragmentMap(fragments) {
if (fragments === void 0) { fragments = []; }
var symTable = {};
fragments.forEach(function (fragment) {
symTable[fragment.name.value] = fragment;
});
return symTable;
}
export function getFragmentFromSelection(selection, fragmentMap) {
switch (selection.kind) {
case "InlineFragment":
return selection;
case "FragmentSpread": {
var fragmentName = selection.name.value;
if (typeof fragmentMap === "function") {
return fragmentMap(fragmentName);
}
var fragment = fragmentMap && fragmentMap[fragmentName];
invariant(fragment, 87, fragmentName);
return fragment || null;
}
default:
return null;
}
}
export function isFullyUnmaskedOperation(document) {
var isUnmasked = true;
visit(document, {
FragmentSpread: function (node) {
isUnmasked =
!!node.directives &&
node.directives.some(function (directive) { return directive.name.value === "unmask"; });
if (!isUnmasked) {
return BREAK;
}
},
});
return isUnmasked;
}
//# sourceMappingURL=fragments.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import type { DocumentNode, OperationDefinitionNode, FragmentDefinitionNode } from "graphql";
export declare function checkDocument(doc: DocumentNode): DocumentNode;
export declare function getOperationDefinition(doc: DocumentNode): OperationDefinitionNode | undefined;
export declare function getOperationName(doc: DocumentNode): string | null;
export declare function getFragmentDefinitions(doc: DocumentNode): FragmentDefinitionNode[];
export declare function getQueryDefinition(doc: DocumentNode): OperationDefinitionNode;
export declare function getFragmentDefinition(doc: DocumentNode): FragmentDefinitionNode;
/**
* Returns the first operation definition found in this document.
* If no operation definition is found, the first fragment definition will be returned.
* If no definitions are found, an error will be thrown.
*/
export declare function getMainDefinition(queryDoc: DocumentNode): OperationDefinitionNode | FragmentDefinitionNode;
export declare function getDefaultValues(definition: OperationDefinitionNode | undefined): Record<string, any>;
//# sourceMappingURL=getFromAST.d.ts.map

View File

@@ -0,0 +1,89 @@
import { invariant, newInvariantError } from "../globals/index.js";
import { valueToObjectRepresentation } from "./storeUtils.js";
// Checks the document for errors and throws an exception if there is an error.
export function checkDocument(doc) {
invariant(doc && doc.kind === "Document", 88);
var operations = doc.definitions
.filter(function (d) { return d.kind !== "FragmentDefinition"; })
.map(function (definition) {
if (definition.kind !== "OperationDefinition") {
throw newInvariantError(89, definition.kind);
}
return definition;
});
invariant(operations.length <= 1, 90, operations.length);
return doc;
}
export function getOperationDefinition(doc) {
checkDocument(doc);
return doc.definitions.filter(function (definition) {
return definition.kind === "OperationDefinition";
})[0];
}
export function getOperationName(doc) {
return (doc.definitions
.filter(function (definition) {
return definition.kind === "OperationDefinition" && !!definition.name;
})
.map(function (x) { return x.name.value; })[0] || null);
}
// Returns the FragmentDefinitions from a particular document as an array
export function getFragmentDefinitions(doc) {
return doc.definitions.filter(function (definition) {
return definition.kind === "FragmentDefinition";
});
}
export function getQueryDefinition(doc) {
var queryDef = getOperationDefinition(doc);
invariant(queryDef && queryDef.operation === "query", 91);
return queryDef;
}
export function getFragmentDefinition(doc) {
invariant(doc.kind === "Document", 92);
invariant(doc.definitions.length <= 1, 93);
var fragmentDef = doc.definitions[0];
invariant(fragmentDef.kind === "FragmentDefinition", 94);
return fragmentDef;
}
/**
* Returns the first operation definition found in this document.
* If no operation definition is found, the first fragment definition will be returned.
* If no definitions are found, an error will be thrown.
*/
export function getMainDefinition(queryDoc) {
checkDocument(queryDoc);
var fragmentDefinition;
for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {
var definition = _a[_i];
if (definition.kind === "OperationDefinition") {
var operation = definition.operation;
if (operation === "query" ||
operation === "mutation" ||
operation === "subscription") {
return definition;
}
}
if (definition.kind === "FragmentDefinition" && !fragmentDefinition) {
// we do this because we want to allow multiple fragment definitions
// to precede an operation definition.
fragmentDefinition = definition;
}
}
if (fragmentDefinition) {
return fragmentDefinition;
}
throw newInvariantError(95);
}
export function getDefaultValues(definition) {
var defaultValues = Object.create(null);
var defs = definition && definition.variableDefinitions;
if (defs && defs.length) {
defs.forEach(function (def) {
if (def.defaultValue) {
valueToObjectRepresentation(defaultValues, def.variable.name, def.defaultValue);
}
});
}
return defaultValues;
}
//# sourceMappingURL=getFromAST.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
import type { DocumentNode } from "../../core/index.js";
export declare function isMutationOperation(document: DocumentNode): boolean;
export declare function isQueryOperation(document: DocumentNode): boolean;
export declare function isSubscriptionOperation(document: DocumentNode): boolean;
//# sourceMappingURL=operations.d.ts.map

View File

@@ -0,0 +1,15 @@
import { getOperationDefinition } from "./getFromAST.js";
function isOperation(document, operation) {
var _a;
return ((_a = getOperationDefinition(document)) === null || _a === void 0 ? void 0 : _a.operation) === operation;
}
export function isMutationOperation(document) {
return isOperation(document, "mutation");
}
export function isQueryOperation(document) {
return isOperation(document, "query");
}
export function isSubscriptionOperation(document) {
return isOperation(document, "subscription");
}
//# sourceMappingURL=operations.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"operations.js","sourceRoot":"","sources":["../../../src/utilities/graphql/operations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,SAAS,WAAW,CAClB,QAAsB,EACtB,SAAgD;;IAEhD,OAAO,CAAA,MAAA,sBAAsB,CAAC,QAAQ,CAAC,0CAAE,SAAS,MAAK,SAAS,CAAC;AACnE,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,QAAsB;IACxD,OAAO,WAAW,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,QAAsB;IACrD,OAAO,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,QAAsB;IAC5D,OAAO,WAAW,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type { DocumentNode } from \"../../core/index.js\";\nimport { getOperationDefinition } from \"./getFromAST.js\";\n\nfunction isOperation(\n document: DocumentNode,\n operation: \"query\" | \"mutation\" | \"subscription\"\n) {\n return getOperationDefinition(document)?.operation === operation;\n}\n\nexport function isMutationOperation(document: DocumentNode) {\n return isOperation(document, \"mutation\");\n}\n\nexport function isQueryOperation(document: DocumentNode) {\n return isOperation(document, \"query\");\n}\n\nexport function isSubscriptionOperation(document: DocumentNode) {\n return isOperation(document, \"subscription\");\n}\n"]}

View File

@@ -0,0 +1,5 @@
import type { ASTNode } from "graphql";
export declare const print: ((ast: ASTNode) => string) & {
reset(): void;
};
//# sourceMappingURL=print.d.ts.map

21
node_modules/@apollo/client/utilities/graphql/print.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import { print as origPrint } from "graphql";
import { AutoCleanedWeakCache, cacheSizes, } from "../caching/index.js";
import { registerGlobalCache } from "../caching/getMemoryInternals.js";
var printCache;
export var print = Object.assign(function (ast) {
var result = printCache.get(ast);
if (!result) {
result = origPrint(ast);
printCache.set(ast, result);
}
return result;
}, {
reset: function () {
printCache = new AutoCleanedWeakCache(cacheSizes.print || 2000 /* defaultCacheSizes.print */);
},
});
print.reset();
if (globalThis.__DEV__ !== false) {
registerGlobalCache("print", function () { return (printCache ? printCache.size : 0); });
}
//# sourceMappingURL=print.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"print.js","sourceRoot":"","sources":["../../../src/utilities/graphql/print.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EACL,oBAAoB,EACpB,UAAU,GAEX,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAEvE,IAAI,UAAkD,CAAC;AACvD,MAAM,CAAC,IAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAChC,UAAC,GAAY;IACX,IAAI,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAEjC,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;QACxB,UAAU,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC,EACD;IACE,KAAK;QACH,UAAU,GAAG,IAAI,oBAAoB,CACnC,UAAU,CAAC,KAAK,sCAA2B,CAC5C,CAAC;IACJ,CAAC;CACF,CACF,CAAC;AACF,KAAK,CAAC,KAAK,EAAE,CAAC;AAEd,IAAI,OAAO,EAAE,CAAC;IACZ,mBAAmB,CAAC,OAAO,EAAE,cAAM,OAAA,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAlC,CAAkC,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import type { ASTNode } from \"graphql\";\nimport { print as origPrint } from \"graphql\";\nimport {\n AutoCleanedWeakCache,\n cacheSizes,\n defaultCacheSizes,\n} from \"../caching/index.js\";\nimport { registerGlobalCache } from \"../caching/getMemoryInternals.js\";\n\nlet printCache!: AutoCleanedWeakCache<ASTNode, string>;\nexport const print = Object.assign(\n (ast: ASTNode) => {\n let result = printCache.get(ast);\n\n if (!result) {\n result = origPrint(ast);\n printCache.set(ast, result);\n }\n return result;\n },\n {\n reset() {\n printCache = new AutoCleanedWeakCache<ASTNode, string>(\n cacheSizes.print || defaultCacheSizes.print\n );\n },\n }\n);\nprint.reset();\n\nif (__DEV__) {\n registerGlobalCache(\"print\", () => (printCache ? printCache.size : 0));\n}\n"]}

View File

@@ -0,0 +1,51 @@
import type { DirectiveNode, FieldNode, VariableNode, InlineFragmentNode, ValueNode, SelectionNode, NameNode, SelectionSetNode, DocumentNode } from "graphql";
import type { FragmentMap } from "./fragments.js";
export interface Reference {
readonly __ref: string;
}
export declare function makeReference(id: string): Reference;
export declare function isReference(obj: any): obj is Reference;
export type StoreValue = number | string | string[] | Reference | Reference[] | null | undefined | void | Object;
export interface StoreObject {
__typename?: string;
[storeFieldName: string]: StoreValue;
}
/**
* Workaround for a TypeScript quirk:
* types per default have an implicit index signature that makes them
* assignable to `StoreObject`.
* interfaces do not have that implicit index signature, so they cannot
* be assigned to `StoreObject`.
* This type just maps over a type or interface that is passed in,
* implicitly adding the index signature.
* That way, the result can be assigned to `StoreObject`.
*
* This is important if some user-defined interface is used e.g.
* in cache.modify, where the `toReference` method expects a
* `StoreObject` as input.
*/
export type AsStoreObject<T extends {
__typename?: string;
}> = {
[K in keyof T]: T[K];
};
export declare function isDocumentNode(value: any): value is DocumentNode;
export declare function valueToObjectRepresentation(argObj: any, name: NameNode, value: ValueNode, variables?: Object): void;
export declare function storeKeyNameFromField(field: FieldNode, variables?: Object): string;
export type Directives = {
[directiveName: string]: {
[argName: string]: any;
};
};
declare let storeKeyNameStringify: (value: any) => string;
export declare const getStoreKeyName: ((fieldName: string, args?: Record<string, any> | null, directives?: Directives) => string) & {
setStringify(s: typeof storeKeyNameStringify): (value: any) => string;
};
export declare function argumentsObjectFromField(field: FieldNode | DirectiveNode, variables?: Record<string, any>): Object | null;
export declare function resultKeyNameFromField(field: FieldNode): string;
export declare function getTypenameFromResult(result: Record<string, any>, selectionSet: SelectionSetNode, fragmentMap?: FragmentMap): string | undefined;
export declare function isField(selection: SelectionNode): selection is FieldNode;
export declare function isInlineFragment(selection: SelectionNode): selection is InlineFragmentNode;
export type VariableValue = (node: VariableNode) => any;
export {};
//# sourceMappingURL=storeUtils.d.ts.map

View File

@@ -0,0 +1,213 @@
import { newInvariantError } from "../globals/index.js";
import { isNonNullObject } from "../common/objects.js";
import { getFragmentFromSelection } from "./fragments.js";
import { canonicalStringify } from "../common/canonicalStringify.js";
export function makeReference(id) {
return { __ref: String(id) };
}
export function isReference(obj) {
return Boolean(obj && typeof obj === "object" && typeof obj.__ref === "string");
}
export function isDocumentNode(value) {
return (isNonNullObject(value) &&
value.kind === "Document" &&
Array.isArray(value.definitions));
}
function isStringValue(value) {
return value.kind === "StringValue";
}
function isBooleanValue(value) {
return value.kind === "BooleanValue";
}
function isIntValue(value) {
return value.kind === "IntValue";
}
function isFloatValue(value) {
return value.kind === "FloatValue";
}
function isVariable(value) {
return value.kind === "Variable";
}
function isObjectValue(value) {
return value.kind === "ObjectValue";
}
function isListValue(value) {
return value.kind === "ListValue";
}
function isEnumValue(value) {
return value.kind === "EnumValue";
}
function isNullValue(value) {
return value.kind === "NullValue";
}
export function valueToObjectRepresentation(argObj, name, value, variables) {
if (isIntValue(value) || isFloatValue(value)) {
argObj[name.value] = Number(value.value);
}
else if (isBooleanValue(value) || isStringValue(value)) {
argObj[name.value] = value.value;
}
else if (isObjectValue(value)) {
var nestedArgObj_1 = {};
value.fields.map(function (obj) {
return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables);
});
argObj[name.value] = nestedArgObj_1;
}
else if (isVariable(value)) {
var variableValue = (variables || {})[value.name.value];
argObj[name.value] = variableValue;
}
else if (isListValue(value)) {
argObj[name.value] = value.values.map(function (listValue) {
var nestedArgArrayObj = {};
valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
return nestedArgArrayObj[name.value];
});
}
else if (isEnumValue(value)) {
argObj[name.value] = value.value;
}
else if (isNullValue(value)) {
argObj[name.value] = null;
}
else {
throw newInvariantError(96, name.value, value.kind);
}
}
export function storeKeyNameFromField(field, variables) {
var directivesObj = null;
if (field.directives) {
directivesObj = {};
field.directives.forEach(function (directive) {
directivesObj[directive.name.value] = {};
if (directive.arguments) {
directive.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables);
});
}
});
}
var argObj = null;
if (field.arguments && field.arguments.length) {
argObj = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj, name, value, variables);
});
}
return getStoreKeyName(field.name.value, argObj, directivesObj);
}
var KNOWN_DIRECTIVES = [
"connection",
"include",
"skip",
"client",
"rest",
"export",
"nonreactive",
];
// Default stable JSON.stringify implementation used by getStoreKeyName. Can be
// updated/replaced with something better by calling
// getStoreKeyName.setStringify(newStringifyFunction).
var storeKeyNameStringify = canonicalStringify;
export var getStoreKeyName = Object.assign(function (fieldName, args, directives) {
if (args &&
directives &&
directives["connection"] &&
directives["connection"]["key"]) {
if (directives["connection"]["filter"] &&
directives["connection"]["filter"].length > 0) {
var filterKeys = directives["connection"]["filter"] ?
directives["connection"]["filter"]
: [];
filterKeys.sort();
var filteredArgs_1 = {};
filterKeys.forEach(function (key) {
filteredArgs_1[key] = args[key];
});
return "".concat(directives["connection"]["key"], "(").concat(storeKeyNameStringify(filteredArgs_1), ")");
}
else {
return directives["connection"]["key"];
}
}
var completeFieldName = fieldName;
if (args) {
// We can't use `JSON.stringify` here since it's non-deterministic,
// and can lead to different store key names being created even though
// the `args` object used during creation has the same properties/values.
var stringifiedArgs = storeKeyNameStringify(args);
completeFieldName += "(".concat(stringifiedArgs, ")");
}
if (directives) {
Object.keys(directives).forEach(function (key) {
if (KNOWN_DIRECTIVES.indexOf(key) !== -1)
return;
if (directives[key] && Object.keys(directives[key]).length) {
completeFieldName += "@".concat(key, "(").concat(storeKeyNameStringify(directives[key]), ")");
}
else {
completeFieldName += "@".concat(key);
}
});
}
return completeFieldName;
}, {
setStringify: function (s) {
var previous = storeKeyNameStringify;
storeKeyNameStringify = s;
return previous;
},
});
export function argumentsObjectFromField(field, variables) {
if (field.arguments && field.arguments.length) {
var argObj_1 = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj_1, name, value, variables);
});
return argObj_1;
}
return null;
}
export function resultKeyNameFromField(field) {
return field.alias ? field.alias.value : field.name.value;
}
export function getTypenameFromResult(result, selectionSet, fragmentMap) {
var fragments;
for (var _i = 0, _a = selectionSet.selections; _i < _a.length; _i++) {
var selection = _a[_i];
if (isField(selection)) {
if (selection.name.value === "__typename") {
return result[resultKeyNameFromField(selection)];
}
}
else if (fragments) {
fragments.push(selection);
}
else {
fragments = [selection];
}
}
if (typeof result.__typename === "string") {
return result.__typename;
}
if (fragments) {
for (var _b = 0, fragments_1 = fragments; _b < fragments_1.length; _b++) {
var selection = fragments_1[_b];
var typename = getTypenameFromResult(result, getFragmentFromSelection(selection, fragmentMap).selectionSet, fragmentMap);
if (typeof typename === "string") {
return typename;
}
}
}
}
export function isField(selection) {
return selection.kind === "Field";
}
export function isInlineFragment(selection) {
return selection.kind === "InlineFragment";
}
//# sourceMappingURL=storeUtils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,28 @@
import type { DocumentNode, FieldNode, DirectiveNode, FragmentDefinitionNode, ArgumentNode, FragmentSpreadNode, VariableDefinitionNode, ASTNode } from "graphql";
export type RemoveNodeConfig<N> = {
name?: string;
test?: (node: N) => boolean;
remove?: boolean;
};
export type GetNodeConfig<N> = {
name?: string;
test?: (node: N) => boolean;
};
export type RemoveDirectiveConfig = RemoveNodeConfig<DirectiveNode>;
export type GetDirectiveConfig = GetNodeConfig<DirectiveNode>;
export type RemoveArgumentsConfig = RemoveNodeConfig<ArgumentNode>;
export type GetFragmentSpreadConfig = GetNodeConfig<FragmentSpreadNode>;
export type RemoveFragmentSpreadConfig = RemoveNodeConfig<FragmentSpreadNode>;
export type RemoveFragmentDefinitionConfig = RemoveNodeConfig<FragmentDefinitionNode>;
export type RemoveVariableDefinitionConfig = RemoveNodeConfig<VariableDefinitionNode>;
export declare function removeDirectivesFromDocument(directives: RemoveDirectiveConfig[], doc: DocumentNode): DocumentNode | null;
export declare const addTypenameToDocument: (<TNode extends ASTNode>(doc: TNode) => TNode) & {
added(field: FieldNode): boolean;
};
export declare function removeConnectionDirectiveFromDocument(doc: DocumentNode): DocumentNode | null;
export declare function removeArgumentsFromDocument(config: RemoveArgumentsConfig[], doc: DocumentNode): DocumentNode | null;
export declare function removeFragmentSpreadFromDocument(config: RemoveFragmentSpreadConfig[], doc: DocumentNode): DocumentNode | null;
export declare function buildQueryFromSelectionSet(document: DocumentNode): DocumentNode;
export declare function removeClientSetsFromDocument(document: DocumentNode): DocumentNode | null;
export declare function addNonReactiveToNamedFragments(document: DocumentNode): DocumentNode;
//# sourceMappingURL=transform.d.ts.map

View File

@@ -0,0 +1,501 @@
import { __assign, __spreadArray } from "tslib";
import { invariant } from "../globals/index.js";
import { visit, Kind } from "graphql";
import { checkDocument, getOperationDefinition, getFragmentDefinition, getFragmentDefinitions, getMainDefinition, } from "./getFromAST.js";
import { isField } from "./storeUtils.js";
import { createFragmentMap } from "./fragments.js";
import { isArray, isNonEmptyArray } from "../common/arrays.js";
var TYPENAME_FIELD = {
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: "__typename",
},
};
function isEmpty(op, fragmentMap) {
return (!op ||
op.selectionSet.selections.every(function (selection) {
return selection.kind === Kind.FRAGMENT_SPREAD &&
isEmpty(fragmentMap[selection.name.value], fragmentMap);
}));
}
function nullIfDocIsEmpty(doc) {
return (isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))) ?
null
: doc;
}
function getDirectiveMatcher(configs) {
var names = new Map();
var tests = new Map();
configs.forEach(function (directive) {
if (directive) {
if (directive.name) {
names.set(directive.name, directive);
}
else if (directive.test) {
tests.set(directive.test, directive);
}
}
});
return function (directive) {
var config = names.get(directive.name.value);
if (!config && tests.size) {
tests.forEach(function (testConfig, test) {
if (test(directive)) {
config = testConfig;
}
});
}
return config;
};
}
function makeInUseGetterFunction(defaultKey) {
var map = new Map();
return function inUseGetterFunction(key) {
if (key === void 0) { key = defaultKey; }
var inUse = map.get(key);
if (!inUse) {
map.set(key, (inUse = {
// Variable and fragment spread names used directly within this
// operation or fragment definition, as identified by key. These sets
// will be populated during the first traversal of the document in
// removeDirectivesFromDocument below.
variables: new Set(),
fragmentSpreads: new Set(),
}));
}
return inUse;
};
}
export function removeDirectivesFromDocument(directives, doc) {
checkDocument(doc);
// Passing empty strings to makeInUseGetterFunction means we handle anonymous
// operations as if their names were "". Anonymous fragment definitions are
// not supposed to be possible, but the same default naming strategy seems
// appropriate for that case as well.
var getInUseByOperationName = makeInUseGetterFunction("");
var getInUseByFragmentName = makeInUseGetterFunction("");
var getInUse = function (ancestors) {
for (var p = 0, ancestor = void 0; p < ancestors.length && (ancestor = ancestors[p]); ++p) {
if (isArray(ancestor))
continue;
if (ancestor.kind === Kind.OPERATION_DEFINITION) {
// If an operation is anonymous, we use the empty string as its key.
return getInUseByOperationName(ancestor.name && ancestor.name.value);
}
if (ancestor.kind === Kind.FRAGMENT_DEFINITION) {
return getInUseByFragmentName(ancestor.name.value);
}
}
globalThis.__DEV__ !== false && invariant.error(97);
return null;
};
var operationCount = 0;
for (var i = doc.definitions.length - 1; i >= 0; --i) {
if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {
++operationCount;
}
}
var directiveMatcher = getDirectiveMatcher(directives);
var shouldRemoveField = function (nodeDirectives) {
return isNonEmptyArray(nodeDirectives) &&
nodeDirectives
.map(directiveMatcher)
.some(function (config) { return config && config.remove; });
};
var originalFragmentDefsByPath = new Map();
// Any time the first traversal of the document below makes a change like
// removing a fragment (by returning null), this variable should be set to
// true. Once it becomes true, it should never be set to false again. If this
// variable remains false throughout the traversal, then we can return the
// original doc immediately without any modifications.
var firstVisitMadeChanges = false;
var fieldOrInlineFragmentVisitor = {
enter: function (node) {
if (shouldRemoveField(node.directives)) {
firstVisitMadeChanges = true;
return null;
}
},
};
var docWithoutDirectiveSubtrees = visit(doc, {
// These two AST node types share the same implementation, defined above.
Field: fieldOrInlineFragmentVisitor,
InlineFragment: fieldOrInlineFragmentVisitor,
VariableDefinition: {
enter: function () {
// VariableDefinition nodes do not count as variables in use, though
// they do contain Variable nodes that might be visited below. To avoid
// counting variable declarations as usages, we skip visiting the
// contents of this VariableDefinition node by returning false.
return false;
},
},
Variable: {
enter: function (node, _key, _parent, _path, ancestors) {
var inUse = getInUse(ancestors);
if (inUse) {
inUse.variables.add(node.name.value);
}
},
},
FragmentSpread: {
enter: function (node, _key, _parent, _path, ancestors) {
if (shouldRemoveField(node.directives)) {
firstVisitMadeChanges = true;
return null;
}
var inUse = getInUse(ancestors);
if (inUse) {
inUse.fragmentSpreads.add(node.name.value);
}
// We might like to remove this FragmentSpread by returning null here if
// the corresponding FragmentDefinition node is also going to be removed
// by the logic below, but we can't control the relative order of those
// events, so we have to postpone the removal of dangling FragmentSpread
// nodes until after the current visit of the document has finished.
},
},
FragmentDefinition: {
enter: function (node, _key, _parent, path) {
originalFragmentDefsByPath.set(JSON.stringify(path), node);
},
leave: function (node, _key, _parent, path) {
var originalNode = originalFragmentDefsByPath.get(JSON.stringify(path));
if (node === originalNode) {
// If the FragmentNode received by this leave function is identical to
// the one received by the corresponding enter function (above), then
// the visitor must not have made any changes within this
// FragmentDefinition node. This fragment definition may still be
// removed if there are no ...spread references to it, but it won't be
// removed just because it has only a __typename field.
return node;
}
if (
// This logic applies only if the document contains one or more
// operations, since removing all fragments from a document containing
// only fragments makes the document useless.
operationCount > 0 &&
node.selectionSet.selections.every(function (selection) {
return selection.kind === Kind.FIELD &&
selection.name.value === "__typename";
})) {
// This is a somewhat opinionated choice: if a FragmentDefinition ends
// up having no fields other than __typename, we remove the whole
// fragment definition, and later prune ...spread references to it.
getInUseByFragmentName(node.name.value).removed = true;
firstVisitMadeChanges = true;
return null;
}
},
},
Directive: {
leave: function (node) {
// If a matching directive is found, remove the directive itself. Note
// that this does not remove the target (field, argument, etc) of the
// directive, but only the directive itself.
if (directiveMatcher(node)) {
firstVisitMadeChanges = true;
return null;
}
},
},
});
if (!firstVisitMadeChanges) {
// If our first pass did not change anything about the document, then there
// is no cleanup we need to do, and we can return the original doc.
return doc;
}
// Utility for making sure inUse.transitiveVars is recursively populated.
// Because this logic assumes inUse.fragmentSpreads has been completely
// populated and inUse.removed has been set if appropriate,
// populateTransitiveVars must be called after that information has been
// collected by the first traversal of the document.
var populateTransitiveVars = function (inUse) {
if (!inUse.transitiveVars) {
inUse.transitiveVars = new Set(inUse.variables);
if (!inUse.removed) {
inUse.fragmentSpreads.forEach(function (childFragmentName) {
populateTransitiveVars(getInUseByFragmentName(childFragmentName)).transitiveVars.forEach(function (varName) {
inUse.transitiveVars.add(varName);
});
});
}
}
return inUse;
};
// Since we've been keeping track of fragment spreads used by particular
// operations and fragment definitions, we now need to compute the set of all
// spreads used (transitively) by any operations in the document.
var allFragmentNamesUsed = new Set();
docWithoutDirectiveSubtrees.definitions.forEach(function (def) {
if (def.kind === Kind.OPERATION_DEFINITION) {
populateTransitiveVars(getInUseByOperationName(def.name && def.name.value)).fragmentSpreads.forEach(function (childFragmentName) {
allFragmentNamesUsed.add(childFragmentName);
});
}
else if (def.kind === Kind.FRAGMENT_DEFINITION &&
// If there are no operations in the document, then all fragment
// definitions count as usages of their own fragment names. This heuristic
// prevents accidentally removing all fragment definitions from the
// document just because it contains no operations that use the fragments.
operationCount === 0 &&
!getInUseByFragmentName(def.name.value).removed) {
allFragmentNamesUsed.add(def.name.value);
}
});
// Now that we have added all fragment spreads used by operations to the
// allFragmentNamesUsed set, we can complete the set by transitively adding
// all fragment spreads used by those fragments, and so on.
allFragmentNamesUsed.forEach(function (fragmentName) {
// Once all the childFragmentName strings added here have been seen already,
// the top-level allFragmentNamesUsed.forEach loop will terminate.
populateTransitiveVars(getInUseByFragmentName(fragmentName)).fragmentSpreads.forEach(function (childFragmentName) {
allFragmentNamesUsed.add(childFragmentName);
});
});
var fragmentWillBeRemoved = function (fragmentName) {
return !!(
// A fragment definition will be removed if there are no spreads that refer
// to it, or the fragment was explicitly removed because it had no fields
// other than __typename.
(!allFragmentNamesUsed.has(fragmentName) ||
getInUseByFragmentName(fragmentName).removed));
};
var enterVisitor = {
enter: function (node) {
if (fragmentWillBeRemoved(node.name.value)) {
return null;
}
},
};
return nullIfDocIsEmpty(visit(docWithoutDirectiveSubtrees, {
// If the fragment is going to be removed, then leaving any dangling
// FragmentSpread nodes with the same name would be a mistake.
FragmentSpread: enterVisitor,
// This is where the fragment definition is actually removed.
FragmentDefinition: enterVisitor,
OperationDefinition: {
leave: function (node) {
// Upon leaving each operation in the depth-first AST traversal, prune
// any variables that are declared by the operation but unused within.
if (node.variableDefinitions) {
var usedVariableNames_1 = populateTransitiveVars(
// If an operation is anonymous, we use the empty string as its key.
getInUseByOperationName(node.name && node.name.value)).transitiveVars;
// According to the GraphQL spec, all variables declared by an
// operation must either be used by that operation or used by some
// fragment included transitively into that operation:
// https://spec.graphql.org/draft/#sec-All-Variables-Used
//
// To stay on the right side of this validation rule, if/when we
// remove the last $var references from an operation or its fragments,
// we must also remove the corresponding $var declaration from the
// enclosing operation. This pruning applies only to operations and
// not fragment definitions, at the moment. Fragments may be able to
// declare variables eventually, but today they can only consume them.
if (usedVariableNames_1.size < node.variableDefinitions.length) {
return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions.filter(function (varDef) {
return usedVariableNames_1.has(varDef.variable.name.value);
}) });
}
}
},
},
}));
}
export var addTypenameToDocument = Object.assign(function (doc) {
return visit(doc, {
SelectionSet: {
enter: function (node, _key, parent) {
// Don't add __typename to OperationDefinitions.
if (parent &&
parent.kind ===
Kind.OPERATION_DEFINITION) {
return;
}
// No changes if no selections.
var selections = node.selections;
if (!selections) {
return;
}
// If selections already have a __typename, or are part of an
// introspection query, do nothing.
var skip = selections.some(function (selection) {
return (isField(selection) &&
(selection.name.value === "__typename" ||
selection.name.value.lastIndexOf("__", 0) === 0));
});
if (skip) {
return;
}
// If this SelectionSet is @export-ed as an input variable, it should
// not have a __typename field (see issue #4691).
var field = parent;
if (isField(field) &&
field.directives &&
field.directives.some(function (d) { return d.name.value === "export"; })) {
return;
}
// Create and return a new SelectionSet with a __typename Field.
return __assign(__assign({}, node), { selections: __spreadArray(__spreadArray([], selections, true), [TYPENAME_FIELD], false) });
},
},
});
}, {
added: function (field) {
return field === TYPENAME_FIELD;
},
});
var connectionRemoveConfig = {
test: function (directive) {
var willRemove = directive.name.value === "connection";
if (willRemove) {
if (!directive.arguments ||
!directive.arguments.some(function (arg) { return arg.name.value === "key"; })) {
globalThis.__DEV__ !== false && invariant.warn(98);
}
}
return willRemove;
},
};
export function removeConnectionDirectiveFromDocument(doc) {
return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));
}
function hasDirectivesInSelectionSet(directives, selectionSet, nestedCheck) {
if (nestedCheck === void 0) { nestedCheck = true; }
return (!!selectionSet &&
selectionSet.selections &&
selectionSet.selections.some(function (selection) {
return hasDirectivesInSelection(directives, selection, nestedCheck);
}));
}
function hasDirectivesInSelection(directives, selection, nestedCheck) {
if (nestedCheck === void 0) { nestedCheck = true; }
if (!isField(selection)) {
return true;
}
if (!selection.directives) {
return false;
}
return (selection.directives.some(getDirectiveMatcher(directives)) ||
(nestedCheck &&
hasDirectivesInSelectionSet(directives, selection.selectionSet, nestedCheck)));
}
function getArgumentMatcher(config) {
return function argumentMatcher(argument) {
return config.some(function (aConfig) {
return argument.value &&
argument.value.kind === Kind.VARIABLE &&
argument.value.name &&
(aConfig.name === argument.value.name.value ||
(aConfig.test && aConfig.test(argument)));
});
};
}
export function removeArgumentsFromDocument(config, doc) {
var argMatcher = getArgumentMatcher(config);
return nullIfDocIsEmpty(visit(doc, {
OperationDefinition: {
enter: function (node) {
return __assign(__assign({}, node), {
// Remove matching top level variables definitions.
variableDefinitions: node.variableDefinitions ?
node.variableDefinitions.filter(function (varDef) {
return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });
})
: [] });
},
},
Field: {
enter: function (node) {
// If `remove` is set to true for an argument, and an argument match
// is found for a field, remove the field as well.
var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });
if (shouldRemoveField) {
var argMatchCount_1 = 0;
if (node.arguments) {
node.arguments.forEach(function (arg) {
if (argMatcher(arg)) {
argMatchCount_1 += 1;
}
});
}
if (argMatchCount_1 === 1) {
return null;
}
}
},
},
Argument: {
enter: function (node) {
// Remove all matching arguments.
if (argMatcher(node)) {
return null;
}
},
},
}));
}
export function removeFragmentSpreadFromDocument(config, doc) {
function enter(node) {
if (config.some(function (def) { return def.name === node.name.value; })) {
return null;
}
}
return nullIfDocIsEmpty(visit(doc, {
FragmentSpread: { enter: enter },
FragmentDefinition: { enter: enter },
}));
}
// If the incoming document is a query, return it as is. Otherwise, build a
// new document containing a query operation based on the selection set
// of the previous main operation.
export function buildQueryFromSelectionSet(document) {
var definition = getMainDefinition(document);
var definitionOperation = definition.operation;
if (definitionOperation === "query") {
// Already a query, so return the existing document.
return document;
}
// Build a new query using the selection set of the main operation.
var modifiedDoc = visit(document, {
OperationDefinition: {
enter: function (node) {
return __assign(__assign({}, node), { operation: "query" });
},
},
});
return modifiedDoc;
}
// Remove fields / selection sets that include an @client directive.
export function removeClientSetsFromDocument(document) {
checkDocument(document);
var modifiedDoc = removeDirectivesFromDocument([
{
test: function (directive) { return directive.name.value === "client"; },
remove: true,
},
], document);
return modifiedDoc;
}
export function addNonReactiveToNamedFragments(document) {
checkDocument(document);
return visit(document, {
FragmentSpread: function (node) {
var _a;
// Do not add `@nonreactive` if the fragment is marked with `@unmask`
// since we want to react to changes in this fragment.
if ((_a = node.directives) === null || _a === void 0 ? void 0 : _a.some(function (directive) { return directive.name.value === "unmask"; })) {
return;
}
return __assign(__assign({}, node), { directives: __spreadArray(__spreadArray([], (node.directives || []), true), [
{
kind: Kind.DIRECTIVE,
name: { kind: Kind.NAME, value: "nonreactive" },
},
], false) });
},
});
}
//# sourceMappingURL=transform.js.map

File diff suppressed because one or more lines are too long

51
node_modules/@apollo/client/utilities/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,51 @@
export { DEV, maybe } from "./globals/index.js";
export type { DirectiveInfo, InclusionDirectives, } from "./graphql/directives.js";
export { shouldInclude, hasDirectives, hasAnyDirectives, hasAllDirectives, hasClientExports, getDirectiveNames, getInclusionDirectives, getFragmentMaskMode, } from "./graphql/directives.js";
export type { DocumentTransformCacheKey } from "./graphql/DocumentTransform.js";
export { DocumentTransform } from "./graphql/DocumentTransform.js";
export type { FragmentMap, FragmentMapFunction } from "./graphql/fragments.js";
export { createFragmentMap, getFragmentQueryDocument, getFragmentFromSelection, isFullyUnmaskedOperation, } from "./graphql/fragments.js";
export { checkDocument, getOperationDefinition, getOperationName, getFragmentDefinitions, getQueryDefinition, getFragmentDefinition, getMainDefinition, getDefaultValues, } from "./graphql/getFromAST.js";
export { print } from "./graphql/print.js";
export type { StoreObject, AsStoreObject, Reference, StoreValue, Directives, VariableValue, } from "./graphql/storeUtils.js";
export { makeReference, isDocumentNode, isReference, isField, isInlineFragment, valueToObjectRepresentation, storeKeyNameFromField, argumentsObjectFromField, resultKeyNameFromField, getStoreKeyName, getTypenameFromResult, } from "./graphql/storeUtils.js";
export type { RemoveNodeConfig, GetNodeConfig, RemoveDirectiveConfig, GetDirectiveConfig, RemoveArgumentsConfig, GetFragmentSpreadConfig, RemoveFragmentSpreadConfig, RemoveFragmentDefinitionConfig, RemoveVariableDefinitionConfig, } from "./graphql/transform.js";
export { addTypenameToDocument, addNonReactiveToNamedFragments, buildQueryFromSelectionSet, removeDirectivesFromDocument, removeConnectionDirectiveFromDocument, removeArgumentsFromDocument, removeFragmentSpreadFromDocument, removeClientSetsFromDocument, } from "./graphql/transform.js";
export { isMutationOperation, isQueryOperation, isSubscriptionOperation, } from "./graphql/operations.js";
export { concatPagination, offsetLimitPagination, relayStylePagination, } from "./policies/pagination.js";
export type { Observer, ObservableSubscription, } from "./observables/Observable.js";
export { Observable } from "./observables/Observable.js";
export type { PromiseWithState } from "./promises/decoration.js";
export { isStatefulPromise, createFulfilledPromise, createRejectedPromise, wrapPromiseWithState, } from "./promises/decoration.js";
export { preventUnhandledRejection } from "./promises/preventUnhandledRejection.js";
export * from "./common/mergeDeep.js";
export * from "./common/cloneDeep.js";
export { maybeDeepFreeze } from "./common/maybeDeepFreeze.js";
export * from "./observables/iteration.js";
export * from "./observables/asyncMap.js";
export * from "./observables/Concast.js";
export * from "./observables/subclassing.js";
export * from "./common/arrays.js";
export * from "./common/objects.js";
export * from "./common/errorHandling.js";
export * from "./common/canUse.js";
export * from "./common/compact.js";
export * from "./common/makeUniqueId.js";
export * from "./common/stringifyForDisplay.js";
export * from "./common/mergeOptions.js";
export * from "./common/incrementalResult.js";
export { canonicalStringify } from "./common/canonicalStringify.js";
export { omitDeep } from "./common/omitDeep.js";
export { stripTypename } from "./common/stripTypename.js";
export type * from "./types/IsStrictlyAny.js";
export type { DeepOmit } from "./types/DeepOmit.js";
export type { DeepPartial } from "./types/DeepPartial.js";
export type { OnlyRequiredProperties } from "./types/OnlyRequiredProperties.js";
export type { Prettify } from "./types/Prettify.js";
export type { Primitive } from "./types/Primitive.js";
export type { UnionToIntersection } from "./types/UnionToIntersection.js";
export type { NoInfer } from "./types/NoInfer.js";
export type { RemoveIndexSignature } from "./types/RemoveIndexSignature.js";
export { AutoCleanedStrongCache, AutoCleanedWeakCache, cacheSizes, defaultCacheSizes, } from "./caching/index.js";
export type { CacheSizes } from "./caching/index.js";
//# sourceMappingURL=index.d.ts.map

34
node_modules/@apollo/client/utilities/index.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
export { DEV, maybe } from "./globals/index.js";
export { shouldInclude, hasDirectives, hasAnyDirectives, hasAllDirectives, hasClientExports, getDirectiveNames, getInclusionDirectives, getFragmentMaskMode, } from "./graphql/directives.js";
export { DocumentTransform } from "./graphql/DocumentTransform.js";
export { createFragmentMap, getFragmentQueryDocument, getFragmentFromSelection, isFullyUnmaskedOperation, } from "./graphql/fragments.js";
export { checkDocument, getOperationDefinition, getOperationName, getFragmentDefinitions, getQueryDefinition, getFragmentDefinition, getMainDefinition, getDefaultValues, } from "./graphql/getFromAST.js";
export { print } from "./graphql/print.js";
export { makeReference, isDocumentNode, isReference, isField, isInlineFragment, valueToObjectRepresentation, storeKeyNameFromField, argumentsObjectFromField, resultKeyNameFromField, getStoreKeyName, getTypenameFromResult, } from "./graphql/storeUtils.js";
export { addTypenameToDocument, addNonReactiveToNamedFragments, buildQueryFromSelectionSet, removeDirectivesFromDocument, removeConnectionDirectiveFromDocument, removeArgumentsFromDocument, removeFragmentSpreadFromDocument, removeClientSetsFromDocument, } from "./graphql/transform.js";
export { isMutationOperation, isQueryOperation, isSubscriptionOperation, } from "./graphql/operations.js";
export { concatPagination, offsetLimitPagination, relayStylePagination, } from "./policies/pagination.js";
export { Observable } from "./observables/Observable.js";
export { isStatefulPromise, createFulfilledPromise, createRejectedPromise, wrapPromiseWithState, } from "./promises/decoration.js";
export { preventUnhandledRejection } from "./promises/preventUnhandledRejection.js";
export * from "./common/mergeDeep.js";
export * from "./common/cloneDeep.js";
export { maybeDeepFreeze } from "./common/maybeDeepFreeze.js";
export * from "./observables/iteration.js";
export * from "./observables/asyncMap.js";
export * from "./observables/Concast.js";
export * from "./observables/subclassing.js";
export * from "./common/arrays.js";
export * from "./common/objects.js";
export * from "./common/errorHandling.js";
export * from "./common/canUse.js";
export * from "./common/compact.js";
export * from "./common/makeUniqueId.js";
export * from "./common/stringifyForDisplay.js";
export * from "./common/mergeOptions.js";
export * from "./common/incrementalResult.js";
export { canonicalStringify } from "./common/canonicalStringify.js";
export { omitDeep } from "./common/omitDeep.js";
export { stripTypename } from "./common/stripTypename.js";
export { AutoCleanedStrongCache, AutoCleanedWeakCache, cacheSizes, } from "./caching/index.js";
//# sourceMappingURL=index.js.map

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