Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@apollo/client-react-streaming

Package Overview
Dependencies
Maintainers
1
Versions
35
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@apollo/client-react-streaming - npm Package Compare versions

Comparing version 0.10.1 to 0.11.0

dist/index.cc.cjs

192

dist/combined.d.ts
import * as _apollo_client_index_js from '@apollo/client/index.js';
import { ApolloClient as ApolloClient$1, ApolloLink, Operation, NextLink, FetchResult, InMemoryCache as InMemoryCache$1, Observable as Observable$1, WatchQueryOptions, ApolloClientOptions, OperationVariables } from '@apollo/client/index.js';
import { WatchQueryOptions, QueryRef, ApolloClient as ApolloClient$1, OperationVariables, ApolloLink, Operation, NextLink, FetchResult, InMemoryCache as InMemoryCache$1, InMemoryCacheConfig, Observable as Observable$1, NormalizedCacheObject, DocumentNode, ApolloClientOptions } from '@apollo/client/index.js';
import React, { ReactNode } from 'react';
import { QueryOptions } from '@apollo/client';
import { Observable } from '@apollo/client/utilities/index.js';
import React from 'react';
type TransportedOptions = {
query: string;
} & Omit<WatchQueryOptions, "query">;
/**
* > This export is only available in React Server Components
* A `TransportedQueryRef` is an opaque object accessible via renderProp within `PreloadQuery`.
*
* Ensures that you can always access the same instance of ApolloClient
* during RSC for an ongoing request, while always returning
* a new instance for different requests.
* A child client component reading the `TransportedQueryRef` via useReadQuery will suspend until the promise resolves.
*
* @example
* ```ts
* export const { getClient } = registerApolloClient(() => {
* return new ApolloClient({
* cache: new InMemoryCache(),
* link: new HttpLink({
* uri: "http://example.com/api/graphql",
* }),
* });
* });
* ```
*
* @public
*/
declare function registerApolloClient(makeClient: () => Promise<ApolloClient$1<any>>): {
getClient: () => Promise<ApolloClient$1<any>>;
interface TransportedQueryRef<TData = unknown, TVariables = unknown> extends QueryRef<TData, TVariables> {
/**
* Only available in React Server Components.
* Will be `undefined` after being passed to Client Components.
*
* Returns a promise that resolves back to the `TransportedQueryRef` that can be awaited in RSC to suspend a subtree until the originating query has been loaded.
*/
toPromise?: () => Promise<TransportedQueryRef>;
}
type RestrictedPreloadOptions = {
fetchPolicy?: "cache-first";
returnPartialData?: false;
nextFetchPolicy?: undefined;
pollInterval?: undefined;
};
type PreloadQueryOptions<TVariables, TData> = QueryOptions<TVariables, TData> & RestrictedPreloadOptions;
/**
* > This export is only available in React Server Components
*
* Ensures that you can always access the same instance of ApolloClient

@@ -37,3 +45,3 @@ * during RSC for an ongoing request, while always returning

* ```ts
* export const { getClient } = registerApolloClient(() => {
* export const { getClient, query, PreloadQuery } = registerApolloClient(() => {
* return new ApolloClient({

@@ -50,5 +58,49 @@ * cache: new InMemoryCache(),

*/
declare function registerApolloClient(makeClient: () => ApolloClient$1<any>): {
getClient: () => ApolloClient$1<any>;
declare function registerApolloClient<ApolloClientOrPromise extends Promise<ApolloClient$1<any>> | ApolloClient$1<any>>(makeClient: () => ApolloClientOrPromise): {
getClient: () => ApolloClientOrPromise;
query: Awaited<ApolloClientOrPromise>["query"];
/**
* Preloads data in React Server Components to be hydrated
* in Client Components.
*
* ### Example with `queryRef`
* `ClientChild` would call `useReadQuery` with the `queryRef`, the `Suspense` boundary is optional:
* ```jsx
* <PreloadQuery
* query={QUERY}
* variables={{
* foo: 1
* }}
* >
* {(queryRef) => (
* <Suspense fallback={<>loading</>}>
* <ClientChild queryRef={queryRef} />
* </Suspense>
* )}
* </PreloadQuery>
* ```
*
* ### Example for `useSuspenseQuery`
* `ClientChild` would call the same query with `useSuspenseQuery`, the `Suspense` boundary is optional:
* ```jsx
* <PreloadQuery
* query={QUERY}
* variables={{
* foo: 1
* }}
* >
* <Suspense fallback={<>loading</>}>
* <ClientChild />
* </Suspense>
* </PreloadQuery>
* ```
*/
PreloadQuery: PreloadQueryComponent;
};
interface PreloadQueryProps<TData, TVariables> extends PreloadQueryOptions<TVariables, TData> {
children: ReactNode | ((queryRef: TransportedQueryRef<NoInfer<TData>, NoInfer<TVariables>>) => ReactNode);
}
interface PreloadQueryComponent {
<TData, TVariables extends OperationVariables>(props: PreloadQueryProps<TData, TVariables>): React.ReactNode;
}

@@ -203,2 +255,4 @@ interface AccumulateMultipartResponsesConfig {

declare const sourceSymbol: unique symbol;
/**

@@ -212,2 +266,12 @@ * A version of `InMemoryCache` to be used with streaming SSR.

declare class InMemoryCache extends InMemoryCache$1 {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static readonly info: {
pkg: string;
};
[sourceSymbol]: string;
constructor(config?: InMemoryCacheConfig | undefined);
}

@@ -278,3 +342,3 @@

type: "started";
options: WatchQueryOptions;
options: TransportedOptions;
id: TransportIdentifier;

@@ -292,2 +356,5 @@ } | {

};
type ProgressEvent = Exclude<QueryEvent, {
type: "started";
}>;

@@ -299,3 +366,6 @@ type SimulatedQueryInfo = {

};
declare class ApolloClientBase<TCacheShape> extends ApolloClient$1<TCacheShape> {
interface WrappedApolloClientOptions extends Omit<ApolloClientOptions<NormalizedCacheObject>, "cache"> {
cache: InMemoryCache;
}
declare class ApolloClientBase extends ApolloClient$1<NormalizedCacheObject> {
/**

@@ -308,9 +378,31 @@ * Information about the current package and it's export names, for use in error messages.

pkg: string;
client: string;
cache: string;
};
constructor(options: ApolloClientOptions<TCacheShape>);
[sourceSymbol]: string;
constructor(options: WrappedApolloClientOptions);
}
declare class ApolloClientSSRImpl<TCacheShape> extends ApolloClientBase<TCacheShape> {
constructor(options: ApolloClientOptions<TCacheShape>);
declare class ApolloClientClientBaseImpl extends ApolloClientBase {
constructor(options: WrappedApolloClientOptions);
private simulatedStreamingQueries;
private transportedQueryOptions;
protected identifyUniqueQuery(options: {
query: DocumentNode;
variables?: unknown;
}): {
cacheKey: string;
cacheKeyArr: string[];
};
onQueryStarted({ options, id }: Extract<QueryEvent, {
type: "started";
}>): void;
onQueryProgress: (event: ProgressEvent) => void;
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries: () => void;
rerunSimulatedQuery: (queryInfo: SimulatedQueryInfo) => void;
}
declare class ApolloClientSSRImpl extends ApolloClientClientBaseImpl {
private forwardedQueries;
watchQueryQueue: {

@@ -335,25 +427,11 @@ push: (value: {

watchQuery<T = any, TVariables extends OperationVariables = OperationVariables>(options: WatchQueryOptions<TVariables, T>): _apollo_client_index_js.ObservableQuery<T, TVariables>;
}
declare class ApolloClientBrowserImpl<TCacheShape> extends ApolloClientBase<TCacheShape> {
constructor(options: ApolloClientOptions<TCacheShape>);
private simulatedStreamingQueries;
private transportedQueryOptions;
private identifyUniqueQuery;
onQueryStarted: ({ options, id, }: Extract<QueryEvent, {
onQueryStarted(event: Extract<QueryEvent, {
type: "started";
}>) => void;
onQueryProgress: (event: Exclude<QueryEvent, {
type: "started";
}>) => void;
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries: () => void;
rerunSimulatedQuery: (queryInfo: SimulatedQueryInfo) => void;
}>): void;
}
declare class ApolloClientBrowserImpl extends ApolloClientClientBaseImpl {
}
declare const ApolloClient_base: typeof ApolloClientBase;
/**
* A version of `ApolloClient` to be used with streaming SSR.
* A version of `ApolloClient` to be used with streaming SSR or in React Server Components.
*

@@ -364,13 +442,13 @@ * For more documentation, please see {@link https://www.apollographql.com/docs/react/api/core/ApolloClient | the Apollo Client API documentation}.

*/
declare class ApolloClient<TCacheShape> extends ApolloClient_base<TCacheShape> implements Partial<ApolloClientBrowserImpl<TCacheShape>>, Partial<ApolloClientSSRImpl<TCacheShape>> {
declare class ApolloClient<Ignored = NormalizedCacheObject> extends ApolloClient_base implements Partial<ApolloClientBrowserImpl>, Partial<ApolloClientSSRImpl> {
/** @internal */
onQueryStarted?: ApolloClientBrowserImpl<TCacheShape>["onQueryStarted"];
onQueryStarted?: ApolloClientBrowserImpl["onQueryStarted"];
/** @internal */
onQueryProgress?: ApolloClientBrowserImpl<TCacheShape>["onQueryProgress"];
onQueryProgress?: ApolloClientBrowserImpl["onQueryProgress"];
/** @internal */
rerunSimulatedQueries?: ApolloClientBrowserImpl<TCacheShape>["rerunSimulatedQueries"];
rerunSimulatedQueries?: ApolloClientBrowserImpl["rerunSimulatedQueries"];
/** @internal */
rerunSimulatedQuery?: ApolloClientBrowserImpl<TCacheShape>["rerunSimulatedQuery"];
rerunSimulatedQuery?: ApolloClientBrowserImpl["rerunSimulatedQuery"];
/** @internal */
watchQueryQueue?: ApolloClientSSRImpl<TCacheShape>["watchQueryQueue"];
watchQueryQueue?: ApolloClientSSRImpl["watchQueryQueue"];
}

@@ -415,4 +493,2 @@

pkg: string;
client: string;
cache: string;
};

@@ -432,2 +508,2 @@ }

export { ApolloClient, DataTransportContext, type DataTransportProviderImplementation, AccumulateMultipartResponsesLink as DebounceMultipartResponsesLink, InMemoryCache, type QueryEvent, RemoveMultipartDirectivesLink, SSRMultipartLink, WrapApolloProvider, type WrappedApolloProvider, registerApolloClient, resetApolloSingletons };
export { ApolloClient, DataTransportContext, type DataTransportProviderImplementation, AccumulateMultipartResponsesLink as DebounceMultipartResponsesLink, InMemoryCache, type QueryEvent, RemoveMultipartDirectivesLink, SSRMultipartLink, type TransportedQueryRef, WrapApolloProvider, type WrappedApolloProvider, registerApolloClient, resetApolloSingletons };
import * as _apollo_client_index_js from '@apollo/client/index.js';
import { ApolloLink, Operation, NextLink, FetchResult, InMemoryCache as InMemoryCache$1, Observable as Observable$1, WatchQueryOptions, ApolloClientOptions, OperationVariables, ApolloClient as ApolloClient$1 } from '@apollo/client/index.js';
import { ApolloLink, Operation, NextLink, FetchResult, InMemoryCache as InMemoryCache$1, InMemoryCacheConfig, WatchQueryOptions, Observable as Observable$1, NormalizedCacheObject, OperationVariables, ApolloClient as ApolloClient$1, DocumentNode, ApolloClientOptions, QueryRef } from '@apollo/client/index.js';
import { Observable } from '@apollo/client/utilities/index.js';

@@ -154,2 +154,4 @@ import React from 'react';

declare const sourceSymbol: unique symbol;
/**

@@ -163,4 +165,18 @@ * A version of `InMemoryCache` to be used with streaming SSR.

declare class InMemoryCache extends InMemoryCache$1 {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static readonly info: {
pkg: string;
};
[sourceSymbol]: string;
constructor(config?: InMemoryCacheConfig | undefined);
}
type TransportedOptions = {
query: string;
} & Omit<WatchQueryOptions, "query">;
interface DataTransportAbstraction {

@@ -229,3 +245,3 @@ /**

type: "started";
options: WatchQueryOptions;
options: TransportedOptions;
id: TransportIdentifier;

@@ -243,2 +259,5 @@ } | {

};
type ProgressEvent = Exclude<QueryEvent, {
type: "started";
}>;

@@ -250,3 +269,6 @@ type SimulatedQueryInfo = {

};
declare class ApolloClientBase<TCacheShape> extends ApolloClient$1<TCacheShape> {
interface WrappedApolloClientOptions extends Omit<ApolloClientOptions<NormalizedCacheObject>, "cache"> {
cache: InMemoryCache;
}
declare class ApolloClientBase extends ApolloClient$1<NormalizedCacheObject> {
/**

@@ -259,9 +281,31 @@ * Information about the current package and it's export names, for use in error messages.

pkg: string;
client: string;
cache: string;
};
constructor(options: ApolloClientOptions<TCacheShape>);
[sourceSymbol]: string;
constructor(options: WrappedApolloClientOptions);
}
declare class ApolloClientSSRImpl<TCacheShape> extends ApolloClientBase<TCacheShape> {
constructor(options: ApolloClientOptions<TCacheShape>);
declare class ApolloClientClientBaseImpl extends ApolloClientBase {
constructor(options: WrappedApolloClientOptions);
private simulatedStreamingQueries;
private transportedQueryOptions;
protected identifyUniqueQuery(options: {
query: DocumentNode;
variables?: unknown;
}): {
cacheKey: string;
cacheKeyArr: string[];
};
onQueryStarted({ options, id }: Extract<QueryEvent, {
type: "started";
}>): void;
onQueryProgress: (event: ProgressEvent) => void;
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries: () => void;
rerunSimulatedQuery: (queryInfo: SimulatedQueryInfo) => void;
}
declare class ApolloClientSSRImpl extends ApolloClientClientBaseImpl {
private forwardedQueries;
watchQueryQueue: {

@@ -286,25 +330,11 @@ push: (value: {

watchQuery<T = any, TVariables extends OperationVariables = OperationVariables>(options: WatchQueryOptions<TVariables, T>): _apollo_client_index_js.ObservableQuery<T, TVariables>;
}
declare class ApolloClientBrowserImpl<TCacheShape> extends ApolloClientBase<TCacheShape> {
constructor(options: ApolloClientOptions<TCacheShape>);
private simulatedStreamingQueries;
private transportedQueryOptions;
private identifyUniqueQuery;
onQueryStarted: ({ options, id, }: Extract<QueryEvent, {
onQueryStarted(event: Extract<QueryEvent, {
type: "started";
}>) => void;
onQueryProgress: (event: Exclude<QueryEvent, {
type: "started";
}>) => void;
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries: () => void;
rerunSimulatedQuery: (queryInfo: SimulatedQueryInfo) => void;
}>): void;
}
declare class ApolloClientBrowserImpl extends ApolloClientClientBaseImpl {
}
declare const ApolloClient_base: typeof ApolloClientBase;
/**
* A version of `ApolloClient` to be used with streaming SSR.
* A version of `ApolloClient` to be used with streaming SSR or in React Server Components.
*

@@ -315,13 +345,13 @@ * For more documentation, please see {@link https://www.apollographql.com/docs/react/api/core/ApolloClient | the Apollo Client API documentation}.

*/
declare class ApolloClient<TCacheShape> extends ApolloClient_base<TCacheShape> implements Partial<ApolloClientBrowserImpl<TCacheShape>>, Partial<ApolloClientSSRImpl<TCacheShape>> {
declare class ApolloClient<Ignored = NormalizedCacheObject> extends ApolloClient_base implements Partial<ApolloClientBrowserImpl>, Partial<ApolloClientSSRImpl> {
/** @internal */
onQueryStarted?: ApolloClientBrowserImpl<TCacheShape>["onQueryStarted"];
onQueryStarted?: ApolloClientBrowserImpl["onQueryStarted"];
/** @internal */
onQueryProgress?: ApolloClientBrowserImpl<TCacheShape>["onQueryProgress"];
onQueryProgress?: ApolloClientBrowserImpl["onQueryProgress"];
/** @internal */
rerunSimulatedQueries?: ApolloClientBrowserImpl<TCacheShape>["rerunSimulatedQueries"];
rerunSimulatedQueries?: ApolloClientBrowserImpl["rerunSimulatedQueries"];
/** @internal */
rerunSimulatedQuery?: ApolloClientBrowserImpl<TCacheShape>["rerunSimulatedQuery"];
rerunSimulatedQuery?: ApolloClientBrowserImpl["rerunSimulatedQuery"];
/** @internal */
watchQueryQueue?: ApolloClientSSRImpl<TCacheShape>["watchQueryQueue"];
watchQueryQueue?: ApolloClientSSRImpl["watchQueryQueue"];
}

@@ -366,4 +396,2 @@

pkg: string;
client: string;
cache: string;
};

@@ -383,2 +411,19 @@ }

export { ApolloClient, DataTransportContext, type DataTransportProviderImplementation, AccumulateMultipartResponsesLink as DebounceMultipartResponsesLink, InMemoryCache, type QueryEvent, RemoveMultipartDirectivesLink, SSRMultipartLink, WrapApolloProvider, type WrappedApolloProvider, resetApolloSingletons };
/**
* A `TransportedQueryRef` is an opaque object accessible via renderProp within `PreloadQuery`.
*
* A child client component reading the `TransportedQueryRef` via useReadQuery will suspend until the promise resolves.
*
* @public
*/
interface TransportedQueryRef<TData = unknown, TVariables = unknown> extends QueryRef<TData, TVariables> {
/**
* Only available in React Server Components.
* Will be `undefined` after being passed to Client Components.
*
* Returns a promise that resolves back to the `TransportedQueryRef` that can be awaited in RSC to suspend a subtree until the originating query has been loaded.
*/
toPromise?: () => Promise<TransportedQueryRef>;
}
export { ApolloClient, DataTransportContext, type DataTransportProviderImplementation, AccumulateMultipartResponsesLink as DebounceMultipartResponsesLink, InMemoryCache, type QueryEvent, RemoveMultipartDirectivesLink, SSRMultipartLink, type TransportedQueryRef, WrapApolloProvider, type WrappedApolloProvider, resetApolloSingletons };

@@ -1,6 +0,7 @@

import { ApolloLink, InMemoryCache as InMemoryCache$1, ApolloProvider, Observable as Observable$1, ApolloClient as ApolloClient$1 } from '@apollo/client/index.js';
import { ApolloLink, InMemoryCache as InMemoryCache$1, ApolloProvider, Observable as Observable$1, gql, ApolloClient as ApolloClient$1, useApolloClient } from '@apollo/client/index.js';
import { hasDirectives, Observable, removeDirectivesFromDocument, mergeIncrementalData, print } from '@apollo/client/utilities/index.js';
import { canonicalStringify } from '@apollo/client/cache/index.js';
import { invariant } from 'ts-invariant';
import React, { createContext, useRef, useContext, useSyncExternalStore } from 'react';
import React, { createContext, useRef, useContext, useSyncExternalStore, useEffect } from 'react';
import { assertWrappedQueryRef, unwrapQueryRef, getSuspenseCache, wrapQueryRef } from '@apollo/client/react/internal/index.js';

@@ -142,3 +143,23 @@ // src/AccumulateMultipartResponsesLink.ts

};
// src/bundleInfo.ts
var bundle = {
pkg: "@apollo/client-react-streaming"
};
var sourceSymbol = Symbol.for("apollo.source_package");
// src/DataTransportAbstraction/WrappedInMemoryCache.tsx
var InMemoryCache = class extends InMemoryCache$1 {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static info = bundle;
[sourceSymbol];
constructor(config) {
super(config);
const info = this.constructor.info;
this[sourceSymbol] = `${info.pkg}:InMemoryCache`;
}
};

@@ -166,2 +187,57 @@ var DataTransportContext = /* @__PURE__ */ createContext(null);

}
function deserializeOptions(options) {
return {
...options,
// `gql` memoizes results, but based on the input string.
// We parse-stringify-parse here to ensure that our minified query
// has the best chance of being the referential same query as the one used in
// client-side code.
query: gql(print(gql(options.query)))
};
}
function reviveTransportedQueryRef(queryRef, client) {
const hydratedOptions = deserializeOptions(queryRef.options);
const cacheKey = [
hydratedOptions.query,
canonicalStringify(hydratedOptions.variables),
queryRef.queryKey
];
if (queryRef.__transportedQueryRef === true) {
queryRef.__transportedQueryRef = wrapQueryRef(
getSuspenseCache(client).getQueryRef(
cacheKey,
() => client.watchQuery(hydratedOptions)
)
);
}
return [queryRef.__transportedQueryRef, cacheKey];
}
function isTransportedQueryRef(queryRef) {
return "__transportedQueryRef" in queryRef;
}
function useWrapTransportedQueryRef(queryRef) {
const client = useApolloClient();
let cacheKey;
let isTransported;
if (isTransported = isTransportedQueryRef(queryRef)) {
[queryRef, cacheKey] = reviveTransportedQueryRef(queryRef, client);
}
assertWrappedQueryRef(queryRef);
const unwrapped = unwrapQueryRef(queryRef);
useEffect(() => {
if (!isTransported)
return;
if (cacheKey) {
if (unwrapped.disposed) {
getSuspenseCache(client).add(cacheKey, unwrapped);
}
}
});
useEffect(() => {
if (isTransported) {
return unwrapped.softRetain();
}
}, [isTransported, unwrapped]);
return queryRef;
}

@@ -183,3 +259,13 @@ // src/DataTransportAbstraction/hooks.ts

useReadQuery(orig_useReadQuery) {
return wrap(orig_useReadQuery, ["data", "networkStatus"]);
return wrap(
(queryRef) => {
return orig_useReadQuery(useWrapTransportedQueryRef(queryRef));
},
["data", "networkStatus"]
);
},
useQueryRefHandlers(orig_useQueryRefHandlers) {
return wrap((queryRef) => {
return orig_useQueryRefHandlers(useWrapTransportedQueryRef(queryRef));
}, []);
}

@@ -190,2 +276,5 @@ };

const result = useFn(...args);
if (transportKeys.length == 0) {
return result;
}
const transported = {};

@@ -199,8 +288,10 @@ for (const key of transportKeys) {

// src/bundleInfo.ts
var bundle = {
pkg: "@apollo/client-react-streaming",
client: "ApolloClient",
cache: "InMemoryCache"
};
// src/assertInstance.ts
function assertInstance(value, info, name) {
if (value[sourceSymbol] !== `${info.pkg}:${name}`) {
throw new Error(
`When using \`${name}\` in streaming SSR, you must use the \`${name}\` export provided by \`"${info.pkg}"\`.`
);
}
}

@@ -219,2 +310,3 @@ // src/DataTransportAbstraction/WrappedApolloClient.tsx

static info = bundle;
[sourceSymbol];
constructor(options) {

@@ -224,12 +316,15 @@ super(

);
if (!(this.cache instanceof InMemoryCache)) {
throw new Error(
`When using \`InMemoryCache\` in streaming SSR, you must use the \`${this.constructor.info.cache}\` export provided by \`"${this.constructor.info.pkg}"\`.`
);
}
const info = this.constructor.info;
this[sourceSymbol] = `${info.pkg}:ApolloClient`;
assertInstance(
this.cache,
info,
"InMemoryCache"
);
}
};
var ApolloClientBrowserImpl = class extends ApolloClientBase {
var ApolloClientClientBaseImpl = class extends ApolloClientBase {
constructor(options) {
super(options);
this.onQueryStarted = this.onQueryStarted.bind(this);
getQueryManager(this)[wrappers] = hookWrappers;

@@ -249,16 +344,15 @@ }

const canonicalVariables = canonicalStringify(options.variables || {});
const cacheKey = [print(serverQuery), canonicalVariables].toString();
return { query: serverQuery, cacheKey, varJson: canonicalVariables };
const cacheKeyArr = [print(serverQuery), canonicalVariables];
const cacheKey = JSON.stringify(cacheKeyArr);
return {
cacheKey,
cacheKeyArr
};
}
onQueryStarted = ({
options,
id
}) => {
const { query, varJson, cacheKey } = this.identifyUniqueQuery(options);
this.transportedQueryOptions.set(id, options);
if (!query)
return;
const printedServerQuery = print(query);
onQueryStarted({ options, id }) {
const hydratedOptions = deserializeOptions(options);
const { cacheKey, cacheKeyArr } = this.identifyUniqueQuery(hydratedOptions);
this.transportedQueryOptions.set(id, hydratedOptions);
const queryManager = getQueryManager(this);
if (!queryManager["inFlightLinkObservables"].peek(printedServerQuery, varJson)?.observable) {
if (!queryManager["inFlightLinkObservables"].peekArray(cacheKeyArr)?.observable) {
let simulatedStreamingQuery, fetchCancelFn;

@@ -268,6 +362,3 @@ const cleanup = () => {

queryManager["fetchCancelFns"].delete(cacheKey);
queryManager["inFlightLinkObservables"].remove(
printedServerQuery,
varJson
);
queryManager["inFlightLinkObservables"].removeArray(cacheKeyArr);
if (this.simulatedStreamingQueries.get(id) === simulatedStreamingQuery)

@@ -279,6 +370,10 @@ this.simulatedStreamingQueries.delete(id);

id,
simulatedStreamingQuery = { resolve, reject, options }
simulatedStreamingQuery = {
resolve,
reject,
options: hydratedOptions
}
);
});
promise.finally(cleanup);
promise.then(cleanup, cleanup);
const observable = new Observable$1((observer) => {

@@ -292,5 +387,4 @@ promise.then((result) => {

});
queryManager["inFlightLinkObservables"].lookup(
printedServerQuery,
varJson
queryManager["inFlightLinkObservables"].lookupArray(
cacheKeyArr
).observable = observable;

@@ -308,3 +402,3 @@ queryManager["fetchCancelFns"].set(

}
};
}
onQueryProgress = (event) => {

@@ -327,7 +421,9 @@ const queryInfo = this.simulatedStreamingQueries.get(event.id);

this.simulatedStreamingQueries.delete(event.id);
invariant.debug(
"query failed on server, rerunning in browser:",
queryInfo.options
);
this.rerunSimulatedQuery(queryInfo);
{
invariant.debug(
"Query failed on server, rerunning in browser:",
queryInfo.options
);
this.rerunSimulatedQuery(queryInfo);
}
}

@@ -367,2 +463,4 @@ this.transportedQueryOptions.delete(event.id);

};
var ApolloClientBrowserImpl = class extends ApolloClientClientBaseImpl {
};
var ApolloClientImplementation = ApolloClientBrowserImpl ;

@@ -387,9 +485,11 @@ var ApolloClient = class extends ApolloClientImplementation {

}) => {
const clientRef = useRef();
{
clientRef.current = window[ApolloClientSingleton] ??= makeClient();
}
if (!(clientRef.current instanceof ApolloClient)) {
throw new Error(
`When using \`ApolloClient\` in streaming SSR, you must use the \`${WrappedApolloProvider3.info.client}\` export provided by \`"${WrappedApolloProvider3.info.pkg}"\`.`
const clientRef = useRef(void 0);
if (!clientRef.current) {
{
clientRef.current = window[ApolloClientSingleton] ??= makeClient();
}
assertInstance(
clientRef.current,
WrappedApolloProvider3.info,
"ApolloClient"
);

@@ -396,0 +496,0 @@ }

import * as _apollo_client_index_js from '@apollo/client/index.js';
import { ApolloClient as ApolloClient$1, ApolloLink, Operation, NextLink, FetchResult, InMemoryCache as InMemoryCache$1, WatchQueryOptions, ApolloClientOptions, Observable as Observable$1, OperationVariables } from '@apollo/client/index.js';
import { WatchQueryOptions, QueryRef, ApolloClient as ApolloClient$1, OperationVariables, ApolloLink, Operation, NextLink, FetchResult, InMemoryCache as InMemoryCache$1, InMemoryCacheConfig, NormalizedCacheObject, Observable as Observable$1, DocumentNode, ApolloClientOptions } from '@apollo/client/index.js';
import React, { ReactNode } from 'react';
import { QueryOptions } from '@apollo/client';
import { Observable } from '@apollo/client/utilities/index.js';
type TransportedOptions = {
query: string;
} & Omit<WatchQueryOptions, "query">;
/**
* > This export is only available in React Server Components
* A `TransportedQueryRef` is an opaque object accessible via renderProp within `PreloadQuery`.
*
* Ensures that you can always access the same instance of ApolloClient
* during RSC for an ongoing request, while always returning
* a new instance for different requests.
* A child client component reading the `TransportedQueryRef` via useReadQuery will suspend until the promise resolves.
*
* @example
* ```ts
* export const { getClient } = registerApolloClient(() => {
* return new ApolloClient({
* cache: new InMemoryCache(),
* link: new HttpLink({
* uri: "http://example.com/api/graphql",
* }),
* });
* });
* ```
*
* @public
*/
declare function registerApolloClient(makeClient: () => Promise<ApolloClient$1<any>>): {
getClient: () => Promise<ApolloClient$1<any>>;
interface TransportedQueryRef<TData = unknown, TVariables = unknown> extends QueryRef<TData, TVariables> {
/**
* Only available in React Server Components.
* Will be `undefined` after being passed to Client Components.
*
* Returns a promise that resolves back to the `TransportedQueryRef` that can be awaited in RSC to suspend a subtree until the originating query has been loaded.
*/
toPromise?: () => Promise<TransportedQueryRef>;
}
type RestrictedPreloadOptions = {
fetchPolicy?: "cache-first";
returnPartialData?: false;
nextFetchPolicy?: undefined;
pollInterval?: undefined;
};
type PreloadQueryOptions<TVariables, TData> = QueryOptions<TVariables, TData> & RestrictedPreloadOptions;
/**
* > This export is only available in React Server Components
*
* Ensures that you can always access the same instance of ApolloClient

@@ -36,3 +45,3 @@ * during RSC for an ongoing request, while always returning

* ```ts
* export const { getClient } = registerApolloClient(() => {
* export const { getClient, query, PreloadQuery } = registerApolloClient(() => {
* return new ApolloClient({

@@ -49,5 +58,49 @@ * cache: new InMemoryCache(),

*/
declare function registerApolloClient(makeClient: () => ApolloClient$1<any>): {
getClient: () => ApolloClient$1<any>;
declare function registerApolloClient<ApolloClientOrPromise extends Promise<ApolloClient$1<any>> | ApolloClient$1<any>>(makeClient: () => ApolloClientOrPromise): {
getClient: () => ApolloClientOrPromise;
query: Awaited<ApolloClientOrPromise>["query"];
/**
* Preloads data in React Server Components to be hydrated
* in Client Components.
*
* ### Example with `queryRef`
* `ClientChild` would call `useReadQuery` with the `queryRef`, the `Suspense` boundary is optional:
* ```jsx
* <PreloadQuery
* query={QUERY}
* variables={{
* foo: 1
* }}
* >
* {(queryRef) => (
* <Suspense fallback={<>loading</>}>
* <ClientChild queryRef={queryRef} />
* </Suspense>
* )}
* </PreloadQuery>
* ```
*
* ### Example for `useSuspenseQuery`
* `ClientChild` would call the same query with `useSuspenseQuery`, the `Suspense` boundary is optional:
* ```jsx
* <PreloadQuery
* query={QUERY}
* variables={{
* foo: 1
* }}
* >
* <Suspense fallback={<>loading</>}>
* <ClientChild />
* </Suspense>
* </PreloadQuery>
* ```
*/
PreloadQuery: PreloadQueryComponent;
};
interface PreloadQueryProps<TData, TVariables> extends PreloadQueryOptions<TVariables, TData> {
children: ReactNode | ((queryRef: TransportedQueryRef<NoInfer<TData>, NoInfer<TVariables>>) => ReactNode);
}
interface PreloadQueryComponent {
<TData, TVariables extends OperationVariables>(props: PreloadQueryProps<TData, TVariables>): React.ReactNode;
}

@@ -202,2 +255,4 @@ interface AccumulateMultipartResponsesConfig {

declare const sourceSymbol: unique symbol;
/**

@@ -211,2 +266,12 @@ * A version of `InMemoryCache` to be used with streaming SSR.

declare class InMemoryCache extends InMemoryCache$1 {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static readonly info: {
pkg: string;
};
[sourceSymbol]: string;
constructor(config?: InMemoryCacheConfig | undefined);
}

@@ -227,3 +292,3 @@

type: "started";
options: WatchQueryOptions;
options: TransportedOptions;
id: TransportIdentifier;

@@ -241,2 +306,5 @@ } | {

};
type ProgressEvent = Exclude<QueryEvent, {
type: "started";
}>;

@@ -248,3 +316,6 @@ type SimulatedQueryInfo = {

};
declare class ApolloClientBase<TCacheShape> extends ApolloClient$1<TCacheShape> {
interface WrappedApolloClientOptions extends Omit<ApolloClientOptions<NormalizedCacheObject>, "cache"> {
cache: InMemoryCache;
}
declare class ApolloClientBase extends ApolloClient$1<NormalizedCacheObject> {
/**

@@ -257,9 +328,31 @@ * Information about the current package and it's export names, for use in error messages.

pkg: string;
client: string;
cache: string;
};
constructor(options: ApolloClientOptions<TCacheShape>);
[sourceSymbol]: string;
constructor(options: WrappedApolloClientOptions);
}
declare class ApolloClientSSRImpl<TCacheShape> extends ApolloClientBase<TCacheShape> {
constructor(options: ApolloClientOptions<TCacheShape>);
declare class ApolloClientClientBaseImpl extends ApolloClientBase {
constructor(options: WrappedApolloClientOptions);
private simulatedStreamingQueries;
private transportedQueryOptions;
protected identifyUniqueQuery(options: {
query: DocumentNode;
variables?: unknown;
}): {
cacheKey: string;
cacheKeyArr: string[];
};
onQueryStarted({ options, id }: Extract<QueryEvent, {
type: "started";
}>): void;
onQueryProgress: (event: ProgressEvent) => void;
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries: () => void;
rerunSimulatedQuery: (queryInfo: SimulatedQueryInfo) => void;
}
declare class ApolloClientSSRImpl extends ApolloClientClientBaseImpl {
private forwardedQueries;
watchQueryQueue: {

@@ -284,25 +377,11 @@ push: (value: {

watchQuery<T = any, TVariables extends OperationVariables = OperationVariables>(options: WatchQueryOptions<TVariables, T>): _apollo_client_index_js.ObservableQuery<T, TVariables>;
}
declare class ApolloClientBrowserImpl<TCacheShape> extends ApolloClientBase<TCacheShape> {
constructor(options: ApolloClientOptions<TCacheShape>);
private simulatedStreamingQueries;
private transportedQueryOptions;
private identifyUniqueQuery;
onQueryStarted: ({ options, id, }: Extract<QueryEvent, {
onQueryStarted(event: Extract<QueryEvent, {
type: "started";
}>) => void;
onQueryProgress: (event: Exclude<QueryEvent, {
type: "started";
}>) => void;
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries: () => void;
rerunSimulatedQuery: (queryInfo: SimulatedQueryInfo) => void;
}>): void;
}
declare class ApolloClientBrowserImpl extends ApolloClientClientBaseImpl {
}
declare const ApolloClient_base: typeof ApolloClientBase;
/**
* A version of `ApolloClient` to be used with streaming SSR.
* A version of `ApolloClient` to be used with streaming SSR or in React Server Components.
*

@@ -313,13 +392,13 @@ * For more documentation, please see {@link https://www.apollographql.com/docs/react/api/core/ApolloClient | the Apollo Client API documentation}.

*/
declare class ApolloClient<TCacheShape> extends ApolloClient_base<TCacheShape> implements Partial<ApolloClientBrowserImpl<TCacheShape>>, Partial<ApolloClientSSRImpl<TCacheShape>> {
declare class ApolloClient<Ignored = NormalizedCacheObject> extends ApolloClient_base implements Partial<ApolloClientBrowserImpl>, Partial<ApolloClientSSRImpl> {
/** @internal */
onQueryStarted?: ApolloClientBrowserImpl<TCacheShape>["onQueryStarted"];
onQueryStarted?: ApolloClientBrowserImpl["onQueryStarted"];
/** @internal */
onQueryProgress?: ApolloClientBrowserImpl<TCacheShape>["onQueryProgress"];
onQueryProgress?: ApolloClientBrowserImpl["onQueryProgress"];
/** @internal */
rerunSimulatedQueries?: ApolloClientBrowserImpl<TCacheShape>["rerunSimulatedQueries"];
rerunSimulatedQueries?: ApolloClientBrowserImpl["rerunSimulatedQueries"];
/** @internal */
rerunSimulatedQuery?: ApolloClientBrowserImpl<TCacheShape>["rerunSimulatedQuery"];
rerunSimulatedQuery?: ApolloClientBrowserImpl["rerunSimulatedQuery"];
/** @internal */
watchQueryQueue?: ApolloClientSSRImpl<TCacheShape>["watchQueryQueue"];
watchQueryQueue?: ApolloClientSSRImpl["watchQueryQueue"];
}

@@ -335,2 +414,2 @@

export { ApolloClient, AccumulateMultipartResponsesLink as DebounceMultipartResponsesLink, InMemoryCache, RemoveMultipartDirectivesLink, SSRMultipartLink, registerApolloClient };
export { ApolloClient, AccumulateMultipartResponsesLink as DebounceMultipartResponsesLink, InMemoryCache, RemoveMultipartDirectivesLink, SSRMultipartLink, type TransportedQueryRef, registerApolloClient };

@@ -1,9 +0,1244 @@

import { cache } from 'react';
import React, { cache } from 'react';
import { SimulatePreloadedQuery } from './index.cc.js';
import { ApolloLink, InMemoryCache as InMemoryCache$1, ApolloClient as ApolloClient$1 } from '@apollo/client/index.js';
import { hasDirectives, Observable, removeDirectivesFromDocument, mergeIncrementalData } from '@apollo/client/utilities/index.js';
import { hasDirectives, Observable, removeDirectivesFromDocument, mergeIncrementalData, print } from '@apollo/client/utilities/index.js';
// src/registerApolloClient.tsx
// ../../node_modules/graphql/jsutils/devAssert.mjs
function devAssert(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(message);
}
}
// ../../node_modules/graphql/jsutils/isObjectLike.mjs
function isObjectLike(value) {
return typeof value == "object" && value !== null;
}
// ../../node_modules/graphql/jsutils/invariant.mjs
function invariant(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(
message != null ? message : "Unexpected invariant triggered."
);
}
}
// ../../node_modules/graphql/language/location.mjs
var LineRegExp = /\r\n|[\n\r]/g;
function getLocation(source, position) {
let lastLineStart = 0;
let line = 1;
for (const match of source.body.matchAll(LineRegExp)) {
typeof match.index === "number" || invariant(false);
if (match.index >= position) {
break;
}
lastLineStart = match.index + match[0].length;
line += 1;
}
return {
line,
column: position + 1 - lastLineStart
};
}
// ../../node_modules/graphql/language/printLocation.mjs
function printLocation(location) {
return printSourceLocation(
location.source,
getLocation(location.source, location.start)
);
}
function printSourceLocation(source, sourceLocation) {
const firstLineColumnOffset = source.locationOffset.column - 1;
const body = "".padStart(firstLineColumnOffset) + source.body;
const lineIndex = sourceLocation.line - 1;
const lineOffset = source.locationOffset.line - 1;
const lineNum = sourceLocation.line + lineOffset;
const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
const columnNum = sourceLocation.column + columnOffset;
const locationStr = `${source.name}:${lineNum}:${columnNum}
`;
const lines = body.split(/\r\n|[\n\r]/g);
const locationLine = lines[lineIndex];
if (locationLine.length > 120) {
const subLineIndex = Math.floor(columnNum / 80);
const subLineColumnNum = columnNum % 80;
const subLines = [];
for (let i = 0; i < locationLine.length; i += 80) {
subLines.push(locationLine.slice(i, i + 80));
}
return locationStr + printPrefixedLines([
[`${lineNum} |`, subLines[0]],
...subLines.slice(1, subLineIndex + 1).map((subLine) => ["|", subLine]),
["|", "^".padStart(subLineColumnNum)],
["|", subLines[subLineIndex + 1]]
]);
}
return locationStr + printPrefixedLines([
// Lines specified like this: ["prefix", "string"],
[`${lineNum - 1} |`, lines[lineIndex - 1]],
[`${lineNum} |`, locationLine],
["|", "^".padStart(columnNum)],
[`${lineNum + 1} |`, lines[lineIndex + 1]]
]);
}
function printPrefixedLines(lines) {
const existingLines = lines.filter(([_, line]) => line !== void 0);
const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));
return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? " " + line : "")).join("\n");
}
// ../../node_modules/graphql/error/GraphQLError.mjs
function toNormalizedOptions(args) {
const firstArg = args[0];
if (firstArg == null || "kind" in firstArg || "length" in firstArg) {
return {
nodes: firstArg,
source: args[1],
positions: args[2],
path: args[3],
originalError: args[4],
extensions: args[5]
};
}
return firstArg;
}
var GraphQLError = class _GraphQLError extends Error {
/**
* An array of `{ line, column }` locations within the source GraphQL document
* which correspond to this error.
*
* Errors during validation often contain multiple locations, for example to
* point out two things with the same name. Errors during execution include a
* single location, the field which produced the error.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array describing the JSON-path into the execution response which
* corresponds to this error. Only included for errors during execution.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array of GraphQL AST Nodes corresponding to this error.
*/
/**
* The source GraphQL document for the first location of this error.
*
* Note that if this Error represents more than one node, the source may not
* represent nodes after the first node.
*/
/**
* An array of character offsets within the source GraphQL document
* which correspond to this error.
*/
/**
* The original error thrown from a field resolver during execution.
*/
/**
* Extension fields to add to the formatted error.
*/
/**
* @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
*/
constructor(message, ...rawArgs) {
var _this$nodes, _nodeLocations$, _ref;
const { nodes, source, positions, path, originalError, extensions } = toNormalizedOptions(rawArgs);
super(message);
this.name = "GraphQLError";
this.path = path !== null && path !== void 0 ? path : void 0;
this.originalError = originalError !== null && originalError !== void 0 ? originalError : void 0;
this.nodes = undefinedIfEmpty(
Array.isArray(nodes) ? nodes : nodes ? [nodes] : void 0
);
const nodeLocations = undefinedIfEmpty(
(_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map((node) => node.loc).filter((loc) => loc != null)
);
this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source;
this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => loc.start);
this.locations = positions && source ? positions.map((pos) => getLocation(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => getLocation(loc.source, loc.start));
const originalExtensions = isObjectLike(
originalError === null || originalError === void 0 ? void 0 : originalError.extensions
) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : void 0;
this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : /* @__PURE__ */ Object.create(null);
Object.defineProperties(this, {
message: {
writable: true,
enumerable: true
},
name: {
enumerable: false
},
nodes: {
enumerable: false
},
source: {
enumerable: false
},
positions: {
enumerable: false
},
originalError: {
enumerable: false
}
});
if (originalError !== null && originalError !== void 0 && originalError.stack) {
Object.defineProperty(this, "stack", {
value: originalError.stack,
writable: true,
configurable: true
});
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, _GraphQLError);
} else {
Object.defineProperty(this, "stack", {
value: Error().stack,
writable: true,
configurable: true
});
}
}
get [Symbol.toStringTag]() {
return "GraphQLError";
}
toString() {
let output = this.message;
if (this.nodes) {
for (const node of this.nodes) {
if (node.loc) {
output += "\n\n" + printLocation(node.loc);
}
}
} else if (this.source && this.locations) {
for (const location of this.locations) {
output += "\n\n" + printSourceLocation(this.source, location);
}
}
return output;
}
toJSON() {
const formattedError = {
message: this.message
};
if (this.locations != null) {
formattedError.locations = this.locations;
}
if (this.path != null) {
formattedError.path = this.path;
}
if (this.extensions != null && Object.keys(this.extensions).length > 0) {
formattedError.extensions = this.extensions;
}
return formattedError;
}
};
function undefinedIfEmpty(array) {
return array === void 0 || array.length === 0 ? void 0 : array;
}
// ../../node_modules/graphql/error/syntaxError.mjs
function syntaxError(source, position, description) {
return new GraphQLError(`Syntax Error: ${description}`, {
source,
positions: [position]
});
}
// ../../node_modules/graphql/language/ast.mjs
var Token = class {
/**
* The kind of Token.
*/
/**
* The character offset at which this Node begins.
*/
/**
* The character offset at which this Node ends.
*/
/**
* The 1-indexed line number on which this Token appears.
*/
/**
* The 1-indexed column number at which this Token begins.
*/
/**
* For non-punctuation tokens, represents the interpreted value of the token.
*
* Note: is undefined for punctuation tokens, but typed as string for
* convenience in the parser.
*/
/**
* Tokens exist as nodes in a double-linked-list amongst all tokens
* including ignored tokens. <SOF> is always the first node and <EOF>
* the last.
*/
constructor(kind, start, end, line, column, value) {
this.kind = kind;
this.start = start;
this.end = end;
this.line = line;
this.column = column;
this.value = value;
this.prev = null;
this.next = null;
}
get [Symbol.toStringTag]() {
return "Token";
}
toJSON() {
return {
kind: this.kind,
value: this.value,
line: this.line,
column: this.column
};
}
};
var QueryDocumentKeys = {
Name: [],
Document: ["definitions"],
OperationDefinition: [
"name",
"variableDefinitions",
"directives",
"selectionSet"
],
VariableDefinition: ["variable", "type", "defaultValue", "directives"],
Variable: ["name"],
SelectionSet: ["selections"],
Field: ["alias", "name", "arguments", "directives", "selectionSet"],
Argument: ["name", "value"],
FragmentSpread: ["name", "directives"],
InlineFragment: ["typeCondition", "directives", "selectionSet"],
FragmentDefinition: [
"name",
// Note: fragment variable definitions are deprecated and will removed in v17.0.0
"variableDefinitions",
"typeCondition",
"directives",
"selectionSet"
],
IntValue: [],
FloatValue: [],
StringValue: [],
BooleanValue: [],
NullValue: [],
EnumValue: [],
ListValue: ["values"],
ObjectValue: ["fields"],
ObjectField: ["name", "value"],
Directive: ["name", "arguments"],
NamedType: ["name"],
ListType: ["type"],
NonNullType: ["type"],
SchemaDefinition: ["description", "directives", "operationTypes"],
OperationTypeDefinition: ["type"],
ScalarTypeDefinition: ["description", "name", "directives"],
ObjectTypeDefinition: [
"description",
"name",
"interfaces",
"directives",
"fields"
],
FieldDefinition: ["description", "name", "arguments", "type", "directives"],
InputValueDefinition: [
"description",
"name",
"type",
"defaultValue",
"directives"
],
InterfaceTypeDefinition: [
"description",
"name",
"interfaces",
"directives",
"fields"
],
UnionTypeDefinition: ["description", "name", "directives", "types"],
EnumTypeDefinition: ["description", "name", "directives", "values"],
EnumValueDefinition: ["description", "name", "directives"],
InputObjectTypeDefinition: ["description", "name", "directives", "fields"],
DirectiveDefinition: ["description", "name", "arguments", "locations"],
SchemaExtension: ["directives", "operationTypes"],
ScalarTypeExtension: ["name", "directives"],
ObjectTypeExtension: ["name", "interfaces", "directives", "fields"],
InterfaceTypeExtension: ["name", "interfaces", "directives", "fields"],
UnionTypeExtension: ["name", "directives", "types"],
EnumTypeExtension: ["name", "directives", "values"],
InputObjectTypeExtension: ["name", "directives", "fields"]
};
new Set(Object.keys(QueryDocumentKeys));
var OperationTypeNode;
(function(OperationTypeNode2) {
OperationTypeNode2["QUERY"] = "query";
OperationTypeNode2["MUTATION"] = "mutation";
OperationTypeNode2["SUBSCRIPTION"] = "subscription";
})(OperationTypeNode || (OperationTypeNode = {}));
// ../../node_modules/graphql/language/characterClasses.mjs
function isWhiteSpace(code) {
return code === 9 || code === 32;
}
function isDigit(code) {
return code >= 48 && code <= 57;
}
function isLetter(code) {
return code >= 97 && code <= 122 || // A-Z
code >= 65 && code <= 90;
}
function isNameStart(code) {
return isLetter(code) || code === 95;
}
function isNameContinue(code) {
return isLetter(code) || isDigit(code) || code === 95;
}
// ../../node_modules/graphql/language/blockString.mjs
function dedentBlockStringLines(lines) {
var _firstNonEmptyLine2;
let commonIndent = Number.MAX_SAFE_INTEGER;
let firstNonEmptyLine = null;
let lastNonEmptyLine = -1;
for (let i = 0; i < lines.length; ++i) {
var _firstNonEmptyLine;
const line = lines[i];
const indent = leadingWhitespace(line);
if (indent === line.length) {
continue;
}
firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i;
lastNonEmptyLine = i;
if (i !== 0 && indent < commonIndent) {
commonIndent = indent;
}
}
return lines.map((line, i) => i === 0 ? line : line.slice(commonIndent)).slice(
(_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0,
lastNonEmptyLine + 1
);
}
function leadingWhitespace(str) {
let i = 0;
while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {
++i;
}
return i;
}
function printBlockString(value, options) {
const escapedValue = value.replace(/"""/g, '\\"""');
const lines = escapedValue.split(/\r\n|[\n\r]/g);
const isSingleLine = lines.length === 1;
const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0)));
const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""');
const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes;
const hasTrailingSlash = value.endsWith("\\");
const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;
const printAsMultipleLines = !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability
(!isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes);
let result = "";
const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));
if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) {
result += "\n";
}
result += escapedValue;
if (printAsMultipleLines || forceTrailingNewline) {
result += "\n";
}
return '"""' + result + '"""';
}
// ../../node_modules/graphql/language/tokenKind.mjs
var TokenKind;
(function(TokenKind2) {
TokenKind2["SOF"] = "<SOF>";
TokenKind2["EOF"] = "<EOF>";
TokenKind2["BANG"] = "!";
TokenKind2["DOLLAR"] = "$";
TokenKind2["AMP"] = "&";
TokenKind2["PAREN_L"] = "(";
TokenKind2["PAREN_R"] = ")";
TokenKind2["SPREAD"] = "...";
TokenKind2["COLON"] = ":";
TokenKind2["EQUALS"] = "=";
TokenKind2["AT"] = "@";
TokenKind2["BRACKET_L"] = "[";
TokenKind2["BRACKET_R"] = "]";
TokenKind2["BRACE_L"] = "{";
TokenKind2["PIPE"] = "|";
TokenKind2["BRACE_R"] = "}";
TokenKind2["NAME"] = "Name";
TokenKind2["INT"] = "Int";
TokenKind2["FLOAT"] = "Float";
TokenKind2["STRING"] = "String";
TokenKind2["BLOCK_STRING"] = "BlockString";
TokenKind2["COMMENT"] = "Comment";
})(TokenKind || (TokenKind = {}));
// ../../node_modules/graphql/language/lexer.mjs
var Lexer = class {
/**
* The previously focused non-ignored token.
*/
/**
* The currently focused non-ignored token.
*/
/**
* The (1-indexed) line containing the current token.
*/
/**
* The character offset at which the current line begins.
*/
constructor(source) {
const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);
this.source = source;
this.lastToken = startOfFileToken;
this.token = startOfFileToken;
this.line = 1;
this.lineStart = 0;
}
get [Symbol.toStringTag]() {
return "Lexer";
}
/**
* Advances the token stream to the next non-ignored token.
*/
advance() {
this.lastToken = this.token;
const token = this.token = this.lookahead();
return token;
}
/**
* Looks ahead and returns the next non-ignored token, but does not change
* the state of Lexer.
*/
lookahead() {
let token = this.token;
if (token.kind !== TokenKind.EOF) {
do {
if (token.next) {
token = token.next;
} else {
const nextToken = readNextToken(this, token.end);
token.next = nextToken;
nextToken.prev = token;
token = nextToken;
}
} while (token.kind === TokenKind.COMMENT);
}
return token;
}
};
function isPunctuatorTokenKind(kind) {
return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;
}
function isUnicodeScalarValue(code) {
return code >= 0 && code <= 55295 || code >= 57344 && code <= 1114111;
}
function isSupplementaryCodePoint(body, location) {
return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1));
}
function isLeadingSurrogate(code) {
return code >= 55296 && code <= 56319;
}
function isTrailingSurrogate(code) {
return code >= 56320 && code <= 57343;
}
function printCodePointAt(lexer, location) {
const code = lexer.source.body.codePointAt(location);
if (code === void 0) {
return TokenKind.EOF;
} else if (code >= 32 && code <= 126) {
const char = String.fromCodePoint(code);
return char === '"' ? `'"'` : `"${char}"`;
}
return "U+" + code.toString(16).toUpperCase().padStart(4, "0");
}
function createToken(lexer, kind, start, end, value) {
const line = lexer.line;
const col = 1 + start - lexer.lineStart;
return new Token(kind, start, end, line, col, value);
}
function readNextToken(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start;
while (position < bodyLength) {
const code = body.charCodeAt(position);
switch (code) {
case 65279:
case 9:
case 32:
case 44:
++position;
continue;
case 10:
++position;
++lexer.line;
lexer.lineStart = position;
continue;
case 13:
if (body.charCodeAt(position + 1) === 10) {
position += 2;
} else {
++position;
}
++lexer.line;
lexer.lineStart = position;
continue;
case 35:
return readComment(lexer, position);
case 33:
return createToken(lexer, TokenKind.BANG, position, position + 1);
case 36:
return createToken(lexer, TokenKind.DOLLAR, position, position + 1);
case 38:
return createToken(lexer, TokenKind.AMP, position, position + 1);
case 40:
return createToken(lexer, TokenKind.PAREN_L, position, position + 1);
case 41:
return createToken(lexer, TokenKind.PAREN_R, position, position + 1);
case 46:
if (body.charCodeAt(position + 1) === 46 && body.charCodeAt(position + 2) === 46) {
return createToken(lexer, TokenKind.SPREAD, position, position + 3);
}
break;
case 58:
return createToken(lexer, TokenKind.COLON, position, position + 1);
case 61:
return createToken(lexer, TokenKind.EQUALS, position, position + 1);
case 64:
return createToken(lexer, TokenKind.AT, position, position + 1);
case 91:
return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);
case 93:
return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);
case 123:
return createToken(lexer, TokenKind.BRACE_L, position, position + 1);
case 124:
return createToken(lexer, TokenKind.PIPE, position, position + 1);
case 125:
return createToken(lexer, TokenKind.BRACE_R, position, position + 1);
case 34:
if (body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
return readBlockString(lexer, position);
}
return readString(lexer, position);
}
if (isDigit(code) || code === 45) {
return readNumber(lexer, position, code);
}
if (isNameStart(code)) {
return readName(lexer, position);
}
throw syntaxError(
lexer.source,
position,
code === 39 ? `Unexpected single quote character ('), did you mean to use a double quote (")?` : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`
);
}
return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);
}
function readComment(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 10 || code === 13) {
break;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
break;
}
}
return createToken(
lexer,
TokenKind.COMMENT,
start,
position,
body.slice(start + 1, position)
);
}
function readNumber(lexer, start, firstCode) {
const body = lexer.source.body;
let position = start;
let code = firstCode;
let isFloat = false;
if (code === 45) {
code = body.charCodeAt(++position);
}
if (code === 48) {
code = body.charCodeAt(++position);
if (isDigit(code)) {
throw syntaxError(
lexer.source,
position,
`Invalid number, unexpected digit after 0: ${printCodePointAt(
lexer,
position
)}.`
);
}
} else {
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 46) {
isFloat = true;
code = body.charCodeAt(++position);
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 69 || code === 101) {
isFloat = true;
code = body.charCodeAt(++position);
if (code === 43 || code === 45) {
code = body.charCodeAt(++position);
}
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 46 || isNameStart(code)) {
throw syntaxError(
lexer.source,
position,
`Invalid number, expected digit but got: ${printCodePointAt(
lexer,
position
)}.`
);
}
return createToken(
lexer,
isFloat ? TokenKind.FLOAT : TokenKind.INT,
start,
position,
body.slice(start, position)
);
}
function readDigits(lexer, start, firstCode) {
if (!isDigit(firstCode)) {
throw syntaxError(
lexer.source,
start,
`Invalid number, expected digit but got: ${printCodePointAt(
lexer,
start
)}.`
);
}
const body = lexer.source.body;
let position = start + 1;
while (isDigit(body.charCodeAt(position))) {
++position;
}
return position;
}
function readString(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
let chunkStart = position;
let value = "";
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 34) {
value += body.slice(chunkStart, position);
return createToken(lexer, TokenKind.STRING, start, position + 1, value);
}
if (code === 92) {
value += body.slice(chunkStart, position);
const escape = body.charCodeAt(position + 1) === 117 ? body.charCodeAt(position + 2) === 123 ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position);
value += escape.value;
position += escape.size;
chunkStart = position;
continue;
}
if (code === 10 || code === 13) {
break;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
throw syntaxError(
lexer.source,
position,
`Invalid character within String: ${printCodePointAt(
lexer,
position
)}.`
);
}
}
throw syntaxError(lexer.source, position, "Unterminated string.");
}
function readEscapedUnicodeVariableWidth(lexer, position) {
const body = lexer.source.body;
let point = 0;
let size = 3;
while (size < 12) {
const code = body.charCodeAt(position + size++);
if (code === 125) {
if (size < 5 || !isUnicodeScalarValue(point)) {
break;
}
return {
value: String.fromCodePoint(point),
size
};
}
point = point << 4 | readHexDigit(code);
if (point < 0) {
break;
}
}
throw syntaxError(
lexer.source,
position,
`Invalid Unicode escape sequence: "${body.slice(
position,
position + size
)}".`
);
}
function readEscapedUnicodeFixedWidth(lexer, position) {
const body = lexer.source.body;
const code = read16BitHexCode(body, position + 2);
if (isUnicodeScalarValue(code)) {
return {
value: String.fromCodePoint(code),
size: 6
};
}
if (isLeadingSurrogate(code)) {
if (body.charCodeAt(position + 6) === 92 && body.charCodeAt(position + 7) === 117) {
const trailingCode = read16BitHexCode(body, position + 8);
if (isTrailingSurrogate(trailingCode)) {
return {
value: String.fromCodePoint(code, trailingCode),
size: 12
};
}
}
}
throw syntaxError(
lexer.source,
position,
`Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`
);
}
function read16BitHexCode(body, position) {
return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3));
}
function readHexDigit(code) {
return code >= 48 && code <= 57 ? code - 48 : code >= 65 && code <= 70 ? code - 55 : code >= 97 && code <= 102 ? code - 87 : -1;
}
function readEscapedCharacter(lexer, position) {
const body = lexer.source.body;
const code = body.charCodeAt(position + 1);
switch (code) {
case 34:
return {
value: '"',
size: 2
};
case 92:
return {
value: "\\",
size: 2
};
case 47:
return {
value: "/",
size: 2
};
case 98:
return {
value: "\b",
size: 2
};
case 102:
return {
value: "\f",
size: 2
};
case 110:
return {
value: "\n",
size: 2
};
case 114:
return {
value: "\r",
size: 2
};
case 116:
return {
value: " ",
size: 2
};
}
throw syntaxError(
lexer.source,
position,
`Invalid character escape sequence: "${body.slice(
position,
position + 2
)}".`
);
}
function readBlockString(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let lineStart = lexer.lineStart;
let position = start + 3;
let chunkStart = position;
let currentLine = "";
const blockLines = [];
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
currentLine += body.slice(chunkStart, position);
blockLines.push(currentLine);
const token = createToken(
lexer,
TokenKind.BLOCK_STRING,
start,
position + 3,
// Return a string of the lines joined with U+000A.
dedentBlockStringLines(blockLines).join("\n")
);
lexer.line += blockLines.length - 1;
lexer.lineStart = lineStart;
return token;
}
if (code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {
currentLine += body.slice(chunkStart, position);
chunkStart = position + 1;
position += 4;
continue;
}
if (code === 10 || code === 13) {
currentLine += body.slice(chunkStart, position);
blockLines.push(currentLine);
if (code === 13 && body.charCodeAt(position + 1) === 10) {
position += 2;
} else {
++position;
}
currentLine = "";
chunkStart = position;
lineStart = position;
continue;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
throw syntaxError(
lexer.source,
position,
`Invalid character within String: ${printCodePointAt(
lexer,
position
)}.`
);
}
}
throw syntaxError(lexer.source, position, "Unterminated string.");
}
function readName(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (isNameContinue(code)) {
++position;
} else {
break;
}
}
return createToken(
lexer,
TokenKind.NAME,
start,
position,
body.slice(start, position)
);
}
// ../../node_modules/graphql/jsutils/inspect.mjs
var MAX_ARRAY_LENGTH = 10;
var MAX_RECURSIVE_DEPTH = 2;
function inspect(value) {
return formatValue(value, []);
}
function formatValue(value, seenValues) {
switch (typeof value) {
case "string":
return JSON.stringify(value);
case "function":
return value.name ? `[function ${value.name}]` : "[function]";
case "object":
return formatObjectValue(value, seenValues);
default:
return String(value);
}
}
function formatObjectValue(value, previouslySeenValues) {
if (value === null) {
return "null";
}
if (previouslySeenValues.includes(value)) {
return "[Circular]";
}
const seenValues = [...previouslySeenValues, value];
if (isJSONable(value)) {
const jsonValue = value.toJSON();
if (jsonValue !== value) {
return typeof jsonValue === "string" ? jsonValue : formatValue(jsonValue, seenValues);
}
} else if (Array.isArray(value)) {
return formatArray(value, seenValues);
}
return formatObject(value, seenValues);
}
function isJSONable(value) {
return typeof value.toJSON === "function";
}
function formatObject(object, seenValues) {
const entries = Object.entries(object);
if (entries.length === 0) {
return "{}";
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return "[" + getObjectTag(object) + "]";
}
const properties = entries.map(
([key, value]) => key + ": " + formatValue(value, seenValues)
);
return "{ " + properties.join(", ") + " }";
}
function formatArray(array, seenValues) {
if (array.length === 0) {
return "[]";
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return "[Array]";
}
const len = Math.min(MAX_ARRAY_LENGTH, array.length);
const remaining = array.length - len;
const items = [];
for (let i = 0; i < len; ++i) {
items.push(formatValue(array[i], seenValues));
}
if (remaining === 1) {
items.push("... 1 more item");
} else if (remaining > 1) {
items.push(`... ${remaining} more items`);
}
return "[" + items.join(", ") + "]";
}
function getObjectTag(object) {
const tag = Object.prototype.toString.call(object).replace(/^\[object /, "").replace(/]$/, "");
if (tag === "Object" && typeof object.constructor === "function") {
const name = object.constructor.name;
if (typeof name === "string" && name !== "") {
return name;
}
}
return tag;
}
// ../../node_modules/graphql/jsutils/instanceOf.mjs
var instanceOf = (
/* c8 ignore next 6 */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
globalThis.process && globalThis.process.env.NODE_ENV === "production" ? function instanceOf2(value, constructor) {
return value instanceof constructor;
} : function instanceOf3(value, constructor) {
if (value instanceof constructor) {
return true;
}
if (typeof value === "object" && value !== null) {
var _value$constructor;
const className = constructor.prototype[Symbol.toStringTag];
const valueClassName = (
// We still need to support constructor's name to detect conflicts with older versions of this library.
Symbol.toStringTag in value ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name
);
if (className === valueClassName) {
const stringifiedValue = inspect(value);
throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.`);
}
}
return false;
}
);
// ../../node_modules/graphql/language/source.mjs
var Source = class {
constructor(body, name = "GraphQL request", locationOffset = {
line: 1,
column: 1
}) {
typeof body === "string" || devAssert(false, `Body must be a string. Received: ${inspect(body)}.`);
this.body = body;
this.name = name;
this.locationOffset = locationOffset;
this.locationOffset.line > 0 || devAssert(
false,
"line in locationOffset is 1-indexed and must be positive."
);
this.locationOffset.column > 0 || devAssert(
false,
"column in locationOffset is 1-indexed and must be positive."
);
}
get [Symbol.toStringTag]() {
return "Source";
}
};
function isSource(source) {
return instanceOf(source, Source);
}
// ../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs
function stripIgnoredCharacters(source) {
const sourceObj = isSource(source) ? source : new Source(source);
const body = sourceObj.body;
const lexer = new Lexer(sourceObj);
let strippedBody = "";
let wasLastAddedTokenNonPunctuator = false;
while (lexer.advance().kind !== TokenKind.EOF) {
const currentToken = lexer.token;
const tokenKind = currentToken.kind;
const isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind);
if (wasLastAddedTokenNonPunctuator) {
if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) {
strippedBody += " ";
}
}
const tokenBody = body.slice(currentToken.start, currentToken.end);
if (tokenKind === TokenKind.BLOCK_STRING) {
strippedBody += printBlockString(currentToken.value, {
minimize: true
});
} else {
strippedBody += tokenBody;
}
wasLastAddedTokenNonPunctuator = isNonPunctuator;
}
return strippedBody;
}
// src/DataTransportAbstraction/transportedOptions.ts
function serializeOptions(options) {
return {
...options,
query: printMinified(options.query)
};
}
function printMinified(query) {
return stripIgnoredCharacters(print(query));
}
function createTransportedQueryRef(options, queryKey, promise) {
const ref = {
__transportedQueryRef: true,
options,
queryKey
};
Object.defineProperty(ref, "toPromise", {
value: () => promise.then(() => ref),
enumerable: false
});
return ref;
}
// src/PreloadQuery.tsx
function PreloadQuery({
getClient,
children,
...options
}) {
const preloadOptions = {
...options,
fetchPolicy: "cache-first",
returnPartialData: false,
pollInterval: void 0,
nextFetchPolicy: void 0
};
const transportedOptions = sanitizeForTransport(
serializeOptions(preloadOptions)
);
const resultPromise = Promise.resolve(getClient()).then((client) => client.query(preloadOptions)).then(
(result) => [
{ type: "data", result: sanitizeForTransport(result) },
{ type: "complete" }
],
() => [{ type: "error" }]
);
const queryKey = crypto.randomUUID();
return /* @__PURE__ */ React.createElement(
SimulatePreloadedQuery,
{
options: transportedOptions,
result: resultPromise,
queryKey: typeof children === "function" ? queryKey : void 0
},
typeof children === "function" ? children(
createTransportedQueryRef(
transportedOptions,
queryKey,
resultPromise
)
) : children
);
}
function sanitizeForTransport(value) {
return JSON.parse(JSON.stringify(value));
}
// src/registerApolloClient.tsx
var seenWrappers = WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
var seenClients = WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;
function registerApolloClient(makeClient) {
const getClient = makeGetClient(makeClient);
const getPreloadClient = makeGetClient(makeClient);
const PreloadQuery2 = makePreloadQuery(getPreloadClient);
return {
getClient,
query: async (...args) => (await getClient()).query(...args),
PreloadQuery: PreloadQuery2
};
}
function makeGetClient(makeClient) {
function makeWrappedClient() {

@@ -45,4 +1280,7 @@ return { client: makeClient() };

}
return {
getClient
return getClient;
}
function makePreloadQuery(getClient) {
return function PreloadQuery2(props) {
return PreloadQuery({ ...props, getClient });
};

@@ -184,11 +1422,33 @@ }

};
var InMemoryCache = class extends InMemoryCache$1 {
};
// src/bundleInfo.ts
var bundle = {
pkg: "@apollo/client-react-streaming",
client: "ApolloClient",
cache: "InMemoryCache"
pkg: "@apollo/client-react-streaming"
};
var sourceSymbol = Symbol.for("apollo.source_package");
// src/DataTransportAbstraction/WrappedInMemoryCache.tsx
var InMemoryCache = class extends InMemoryCache$1 {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static info = bundle;
[sourceSymbol];
constructor(config) {
super(config);
const info = this.constructor.info;
this[sourceSymbol] = `${info.pkg}:InMemoryCache`;
}
};
// src/assertInstance.ts
function assertInstance(value, info, name) {
if (value[sourceSymbol] !== `${info.pkg}:${name}`) {
throw new Error(
`When using \`${name}\` in streaming SSR, you must use the \`${name}\` export provided by \`"${info.pkg}"\`.`
);
}
}
var ApolloClientBase = class extends ApolloClient$1 {

@@ -201,2 +1461,3 @@ /**

static info = bundle;
[sourceSymbol];
constructor(options) {

@@ -209,7 +1470,9 @@ super(

);
if (!(this.cache instanceof InMemoryCache)) {
throw new Error(
`When using \`InMemoryCache\` in streaming SSR, you must use the \`${this.constructor.info.cache}\` export provided by \`"${this.constructor.info.pkg}"\`.`
);
}
const info = this.constructor.info;
this[sourceSymbol] = `${info.pkg}:ApolloClient`;
assertInstance(
this.cache,
info,
"InMemoryCache"
);
}

@@ -216,0 +1479,0 @@ };

import * as _apollo_client_index_js from '@apollo/client/index.js';
import { ApolloLink, Operation, NextLink, FetchResult, InMemoryCache as InMemoryCache$1, Observable as Observable$1, WatchQueryOptions, ApolloClientOptions, OperationVariables, ApolloClient as ApolloClient$1 } from '@apollo/client/index.js';
import { ApolloLink, Operation, NextLink, FetchResult, InMemoryCache as InMemoryCache$1, InMemoryCacheConfig, WatchQueryOptions, Observable as Observable$1, NormalizedCacheObject, OperationVariables, ApolloClient as ApolloClient$1, DocumentNode, ApolloClientOptions, QueryRef } from '@apollo/client/index.js';
import { Observable } from '@apollo/client/utilities/index.js';

@@ -154,2 +154,4 @@ import React from 'react';

declare const sourceSymbol: unique symbol;
/**

@@ -163,4 +165,18 @@ * A version of `InMemoryCache` to be used with streaming SSR.

declare class InMemoryCache extends InMemoryCache$1 {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static readonly info: {
pkg: string;
};
[sourceSymbol]: string;
constructor(config?: InMemoryCacheConfig | undefined);
}
type TransportedOptions = {
query: string;
} & Omit<WatchQueryOptions, "query">;
interface DataTransportAbstraction {

@@ -229,3 +245,3 @@ /**

type: "started";
options: WatchQueryOptions;
options: TransportedOptions;
id: TransportIdentifier;

@@ -243,2 +259,5 @@ } | {

};
type ProgressEvent = Exclude<QueryEvent, {
type: "started";
}>;

@@ -250,3 +269,6 @@ type SimulatedQueryInfo = {

};
declare class ApolloClientBase<TCacheShape> extends ApolloClient$1<TCacheShape> {
interface WrappedApolloClientOptions extends Omit<ApolloClientOptions<NormalizedCacheObject>, "cache"> {
cache: InMemoryCache;
}
declare class ApolloClientBase extends ApolloClient$1<NormalizedCacheObject> {
/**

@@ -259,9 +281,31 @@ * Information about the current package and it's export names, for use in error messages.

pkg: string;
client: string;
cache: string;
};
constructor(options: ApolloClientOptions<TCacheShape>);
[sourceSymbol]: string;
constructor(options: WrappedApolloClientOptions);
}
declare class ApolloClientSSRImpl<TCacheShape> extends ApolloClientBase<TCacheShape> {
constructor(options: ApolloClientOptions<TCacheShape>);
declare class ApolloClientClientBaseImpl extends ApolloClientBase {
constructor(options: WrappedApolloClientOptions);
private simulatedStreamingQueries;
private transportedQueryOptions;
protected identifyUniqueQuery(options: {
query: DocumentNode;
variables?: unknown;
}): {
cacheKey: string;
cacheKeyArr: string[];
};
onQueryStarted({ options, id }: Extract<QueryEvent, {
type: "started";
}>): void;
onQueryProgress: (event: ProgressEvent) => void;
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries: () => void;
rerunSimulatedQuery: (queryInfo: SimulatedQueryInfo) => void;
}
declare class ApolloClientSSRImpl extends ApolloClientClientBaseImpl {
private forwardedQueries;
watchQueryQueue: {

@@ -286,25 +330,11 @@ push: (value: {

watchQuery<T = any, TVariables extends OperationVariables = OperationVariables>(options: WatchQueryOptions<TVariables, T>): _apollo_client_index_js.ObservableQuery<T, TVariables>;
}
declare class ApolloClientBrowserImpl<TCacheShape> extends ApolloClientBase<TCacheShape> {
constructor(options: ApolloClientOptions<TCacheShape>);
private simulatedStreamingQueries;
private transportedQueryOptions;
private identifyUniqueQuery;
onQueryStarted: ({ options, id, }: Extract<QueryEvent, {
onQueryStarted(event: Extract<QueryEvent, {
type: "started";
}>) => void;
onQueryProgress: (event: Exclude<QueryEvent, {
type: "started";
}>) => void;
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries: () => void;
rerunSimulatedQuery: (queryInfo: SimulatedQueryInfo) => void;
}>): void;
}
declare class ApolloClientBrowserImpl extends ApolloClientClientBaseImpl {
}
declare const ApolloClient_base: typeof ApolloClientBase;
/**
* A version of `ApolloClient` to be used with streaming SSR.
* A version of `ApolloClient` to be used with streaming SSR or in React Server Components.
*

@@ -315,13 +345,13 @@ * For more documentation, please see {@link https://www.apollographql.com/docs/react/api/core/ApolloClient | the Apollo Client API documentation}.

*/
declare class ApolloClient<TCacheShape> extends ApolloClient_base<TCacheShape> implements Partial<ApolloClientBrowserImpl<TCacheShape>>, Partial<ApolloClientSSRImpl<TCacheShape>> {
declare class ApolloClient<Ignored = NormalizedCacheObject> extends ApolloClient_base implements Partial<ApolloClientBrowserImpl>, Partial<ApolloClientSSRImpl> {
/** @internal */
onQueryStarted?: ApolloClientBrowserImpl<TCacheShape>["onQueryStarted"];
onQueryStarted?: ApolloClientBrowserImpl["onQueryStarted"];
/** @internal */
onQueryProgress?: ApolloClientBrowserImpl<TCacheShape>["onQueryProgress"];
onQueryProgress?: ApolloClientBrowserImpl["onQueryProgress"];
/** @internal */
rerunSimulatedQueries?: ApolloClientBrowserImpl<TCacheShape>["rerunSimulatedQueries"];
rerunSimulatedQueries?: ApolloClientBrowserImpl["rerunSimulatedQueries"];
/** @internal */
rerunSimulatedQuery?: ApolloClientBrowserImpl<TCacheShape>["rerunSimulatedQuery"];
rerunSimulatedQuery?: ApolloClientBrowserImpl["rerunSimulatedQuery"];
/** @internal */
watchQueryQueue?: ApolloClientSSRImpl<TCacheShape>["watchQueryQueue"];
watchQueryQueue?: ApolloClientSSRImpl["watchQueryQueue"];
}

@@ -366,4 +396,2 @@

pkg: string;
client: string;
cache: string;
};

@@ -383,2 +411,19 @@ }

export { ApolloClient, DataTransportContext, type DataTransportProviderImplementation, AccumulateMultipartResponsesLink as DebounceMultipartResponsesLink, InMemoryCache, type QueryEvent, RemoveMultipartDirectivesLink, SSRMultipartLink, WrapApolloProvider, type WrappedApolloProvider, resetApolloSingletons };
/**
* A `TransportedQueryRef` is an opaque object accessible via renderProp within `PreloadQuery`.
*
* A child client component reading the `TransportedQueryRef` via useReadQuery will suspend until the promise resolves.
*
* @public
*/
interface TransportedQueryRef<TData = unknown, TVariables = unknown> extends QueryRef<TData, TVariables> {
/**
* Only available in React Server Components.
* Will be `undefined` after being passed to Client Components.
*
* Returns a promise that resolves back to the `TransportedQueryRef` that can be awaited in RSC to suspend a subtree until the originating query has been loaded.
*/
toPromise?: () => Promise<TransportedQueryRef>;
}
export { ApolloClient, DataTransportContext, type DataTransportProviderImplementation, AccumulateMultipartResponsesLink as DebounceMultipartResponsesLink, InMemoryCache, type QueryEvent, RemoveMultipartDirectivesLink, SSRMultipartLink, type TransportedQueryRef, WrapApolloProvider, type WrappedApolloProvider, resetApolloSingletons };

@@ -1,4 +0,7 @@

import { ApolloLink, InMemoryCache as InMemoryCache$1, ApolloProvider, Observable as Observable$1, ApolloClient as ApolloClient$1 } from '@apollo/client/index.js';
import { hasDirectives, Observable, removeDirectivesFromDocument, mergeIncrementalData } from '@apollo/client/utilities/index.js';
import React, { createContext, useRef, useContext, useSyncExternalStore } from 'react';
import { ApolloLink, InMemoryCache as InMemoryCache$1, ApolloProvider, Observable as Observable$1, gql, ApolloClient as ApolloClient$1, useApolloClient } from '@apollo/client/index.js';
import { hasDirectives, Observable, removeDirectivesFromDocument, mergeIncrementalData, print } from '@apollo/client/utilities/index.js';
import { canonicalStringify } from '@apollo/client/cache/index.js';
import { invariant as invariant$1 } from 'ts-invariant';
import React, { createContext, useRef, useContext, useSyncExternalStore, useEffect } from 'react';
import { assertWrappedQueryRef, unwrapQueryRef, getSuspenseCache, wrapQueryRef } from '@apollo/client/react/internal/index.js';

@@ -140,3 +143,23 @@ // src/AccumulateMultipartResponsesLink.ts

};
// src/bundleInfo.ts
var bundle = {
pkg: "@apollo/client-react-streaming"
};
var sourceSymbol = Symbol.for("apollo.source_package");
// src/DataTransportAbstraction/WrappedInMemoryCache.tsx
var InMemoryCache = class extends InMemoryCache$1 {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static info = bundle;
[sourceSymbol];
constructor(config) {
super(config);
const info = this.constructor.info;
this[sourceSymbol] = `${info.pkg}:InMemoryCache`;
}
};

@@ -184,2 +207,1223 @@

// ../../node_modules/graphql/jsutils/devAssert.mjs
function devAssert(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(message);
}
}
// ../../node_modules/graphql/jsutils/isObjectLike.mjs
function isObjectLike(value) {
return typeof value == "object" && value !== null;
}
// ../../node_modules/graphql/jsutils/invariant.mjs
function invariant(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(
message != null ? message : "Unexpected invariant triggered."
);
}
}
// ../../node_modules/graphql/language/location.mjs
var LineRegExp = /\r\n|[\n\r]/g;
function getLocation(source, position) {
let lastLineStart = 0;
let line = 1;
for (const match of source.body.matchAll(LineRegExp)) {
typeof match.index === "number" || invariant(false);
if (match.index >= position) {
break;
}
lastLineStart = match.index + match[0].length;
line += 1;
}
return {
line,
column: position + 1 - lastLineStart
};
}
// ../../node_modules/graphql/language/printLocation.mjs
function printLocation(location) {
return printSourceLocation(
location.source,
getLocation(location.source, location.start)
);
}
function printSourceLocation(source, sourceLocation) {
const firstLineColumnOffset = source.locationOffset.column - 1;
const body = "".padStart(firstLineColumnOffset) + source.body;
const lineIndex = sourceLocation.line - 1;
const lineOffset = source.locationOffset.line - 1;
const lineNum = sourceLocation.line + lineOffset;
const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
const columnNum = sourceLocation.column + columnOffset;
const locationStr = `${source.name}:${lineNum}:${columnNum}
`;
const lines = body.split(/\r\n|[\n\r]/g);
const locationLine = lines[lineIndex];
if (locationLine.length > 120) {
const subLineIndex = Math.floor(columnNum / 80);
const subLineColumnNum = columnNum % 80;
const subLines = [];
for (let i = 0; i < locationLine.length; i += 80) {
subLines.push(locationLine.slice(i, i + 80));
}
return locationStr + printPrefixedLines([
[`${lineNum} |`, subLines[0]],
...subLines.slice(1, subLineIndex + 1).map((subLine) => ["|", subLine]),
["|", "^".padStart(subLineColumnNum)],
["|", subLines[subLineIndex + 1]]
]);
}
return locationStr + printPrefixedLines([
// Lines specified like this: ["prefix", "string"],
[`${lineNum - 1} |`, lines[lineIndex - 1]],
[`${lineNum} |`, locationLine],
["|", "^".padStart(columnNum)],
[`${lineNum + 1} |`, lines[lineIndex + 1]]
]);
}
function printPrefixedLines(lines) {
const existingLines = lines.filter(([_, line]) => line !== void 0);
const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));
return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? " " + line : "")).join("\n");
}
// ../../node_modules/graphql/error/GraphQLError.mjs
function toNormalizedOptions(args) {
const firstArg = args[0];
if (firstArg == null || "kind" in firstArg || "length" in firstArg) {
return {
nodes: firstArg,
source: args[1],
positions: args[2],
path: args[3],
originalError: args[4],
extensions: args[5]
};
}
return firstArg;
}
var GraphQLError = class _GraphQLError extends Error {
/**
* An array of `{ line, column }` locations within the source GraphQL document
* which correspond to this error.
*
* Errors during validation often contain multiple locations, for example to
* point out two things with the same name. Errors during execution include a
* single location, the field which produced the error.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array describing the JSON-path into the execution response which
* corresponds to this error. Only included for errors during execution.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array of GraphQL AST Nodes corresponding to this error.
*/
/**
* The source GraphQL document for the first location of this error.
*
* Note that if this Error represents more than one node, the source may not
* represent nodes after the first node.
*/
/**
* An array of character offsets within the source GraphQL document
* which correspond to this error.
*/
/**
* The original error thrown from a field resolver during execution.
*/
/**
* Extension fields to add to the formatted error.
*/
/**
* @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
*/
constructor(message, ...rawArgs) {
var _this$nodes, _nodeLocations$, _ref;
const { nodes, source, positions, path, originalError, extensions } = toNormalizedOptions(rawArgs);
super(message);
this.name = "GraphQLError";
this.path = path !== null && path !== void 0 ? path : void 0;
this.originalError = originalError !== null && originalError !== void 0 ? originalError : void 0;
this.nodes = undefinedIfEmpty(
Array.isArray(nodes) ? nodes : nodes ? [nodes] : void 0
);
const nodeLocations = undefinedIfEmpty(
(_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map((node) => node.loc).filter((loc) => loc != null)
);
this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source;
this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => loc.start);
this.locations = positions && source ? positions.map((pos) => getLocation(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => getLocation(loc.source, loc.start));
const originalExtensions = isObjectLike(
originalError === null || originalError === void 0 ? void 0 : originalError.extensions
) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : void 0;
this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : /* @__PURE__ */ Object.create(null);
Object.defineProperties(this, {
message: {
writable: true,
enumerable: true
},
name: {
enumerable: false
},
nodes: {
enumerable: false
},
source: {
enumerable: false
},
positions: {
enumerable: false
},
originalError: {
enumerable: false
}
});
if (originalError !== null && originalError !== void 0 && originalError.stack) {
Object.defineProperty(this, "stack", {
value: originalError.stack,
writable: true,
configurable: true
});
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, _GraphQLError);
} else {
Object.defineProperty(this, "stack", {
value: Error().stack,
writable: true,
configurable: true
});
}
}
get [Symbol.toStringTag]() {
return "GraphQLError";
}
toString() {
let output = this.message;
if (this.nodes) {
for (const node of this.nodes) {
if (node.loc) {
output += "\n\n" + printLocation(node.loc);
}
}
} else if (this.source && this.locations) {
for (const location of this.locations) {
output += "\n\n" + printSourceLocation(this.source, location);
}
}
return output;
}
toJSON() {
const formattedError = {
message: this.message
};
if (this.locations != null) {
formattedError.locations = this.locations;
}
if (this.path != null) {
formattedError.path = this.path;
}
if (this.extensions != null && Object.keys(this.extensions).length > 0) {
formattedError.extensions = this.extensions;
}
return formattedError;
}
};
function undefinedIfEmpty(array) {
return array === void 0 || array.length === 0 ? void 0 : array;
}
// ../../node_modules/graphql/error/syntaxError.mjs
function syntaxError(source, position, description) {
return new GraphQLError(`Syntax Error: ${description}`, {
source,
positions: [position]
});
}
// ../../node_modules/graphql/language/ast.mjs
var Token = class {
/**
* The kind of Token.
*/
/**
* The character offset at which this Node begins.
*/
/**
* The character offset at which this Node ends.
*/
/**
* The 1-indexed line number on which this Token appears.
*/
/**
* The 1-indexed column number at which this Token begins.
*/
/**
* For non-punctuation tokens, represents the interpreted value of the token.
*
* Note: is undefined for punctuation tokens, but typed as string for
* convenience in the parser.
*/
/**
* Tokens exist as nodes in a double-linked-list amongst all tokens
* including ignored tokens. <SOF> is always the first node and <EOF>
* the last.
*/
constructor(kind, start, end, line, column, value) {
this.kind = kind;
this.start = start;
this.end = end;
this.line = line;
this.column = column;
this.value = value;
this.prev = null;
this.next = null;
}
get [Symbol.toStringTag]() {
return "Token";
}
toJSON() {
return {
kind: this.kind,
value: this.value,
line: this.line,
column: this.column
};
}
};
var QueryDocumentKeys = {
Name: [],
Document: ["definitions"],
OperationDefinition: [
"name",
"variableDefinitions",
"directives",
"selectionSet"
],
VariableDefinition: ["variable", "type", "defaultValue", "directives"],
Variable: ["name"],
SelectionSet: ["selections"],
Field: ["alias", "name", "arguments", "directives", "selectionSet"],
Argument: ["name", "value"],
FragmentSpread: ["name", "directives"],
InlineFragment: ["typeCondition", "directives", "selectionSet"],
FragmentDefinition: [
"name",
// Note: fragment variable definitions are deprecated and will removed in v17.0.0
"variableDefinitions",
"typeCondition",
"directives",
"selectionSet"
],
IntValue: [],
FloatValue: [],
StringValue: [],
BooleanValue: [],
NullValue: [],
EnumValue: [],
ListValue: ["values"],
ObjectValue: ["fields"],
ObjectField: ["name", "value"],
Directive: ["name", "arguments"],
NamedType: ["name"],
ListType: ["type"],
NonNullType: ["type"],
SchemaDefinition: ["description", "directives", "operationTypes"],
OperationTypeDefinition: ["type"],
ScalarTypeDefinition: ["description", "name", "directives"],
ObjectTypeDefinition: [
"description",
"name",
"interfaces",
"directives",
"fields"
],
FieldDefinition: ["description", "name", "arguments", "type", "directives"],
InputValueDefinition: [
"description",
"name",
"type",
"defaultValue",
"directives"
],
InterfaceTypeDefinition: [
"description",
"name",
"interfaces",
"directives",
"fields"
],
UnionTypeDefinition: ["description", "name", "directives", "types"],
EnumTypeDefinition: ["description", "name", "directives", "values"],
EnumValueDefinition: ["description", "name", "directives"],
InputObjectTypeDefinition: ["description", "name", "directives", "fields"],
DirectiveDefinition: ["description", "name", "arguments", "locations"],
SchemaExtension: ["directives", "operationTypes"],
ScalarTypeExtension: ["name", "directives"],
ObjectTypeExtension: ["name", "interfaces", "directives", "fields"],
InterfaceTypeExtension: ["name", "interfaces", "directives", "fields"],
UnionTypeExtension: ["name", "directives", "types"],
EnumTypeExtension: ["name", "directives", "values"],
InputObjectTypeExtension: ["name", "directives", "fields"]
};
new Set(Object.keys(QueryDocumentKeys));
var OperationTypeNode;
(function(OperationTypeNode2) {
OperationTypeNode2["QUERY"] = "query";
OperationTypeNode2["MUTATION"] = "mutation";
OperationTypeNode2["SUBSCRIPTION"] = "subscription";
})(OperationTypeNode || (OperationTypeNode = {}));
// ../../node_modules/graphql/language/characterClasses.mjs
function isWhiteSpace(code) {
return code === 9 || code === 32;
}
function isDigit(code) {
return code >= 48 && code <= 57;
}
function isLetter(code) {
return code >= 97 && code <= 122 || // A-Z
code >= 65 && code <= 90;
}
function isNameStart(code) {
return isLetter(code) || code === 95;
}
function isNameContinue(code) {
return isLetter(code) || isDigit(code) || code === 95;
}
// ../../node_modules/graphql/language/blockString.mjs
function dedentBlockStringLines(lines) {
var _firstNonEmptyLine2;
let commonIndent = Number.MAX_SAFE_INTEGER;
let firstNonEmptyLine = null;
let lastNonEmptyLine = -1;
for (let i = 0; i < lines.length; ++i) {
var _firstNonEmptyLine;
const line = lines[i];
const indent = leadingWhitespace(line);
if (indent === line.length) {
continue;
}
firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i;
lastNonEmptyLine = i;
if (i !== 0 && indent < commonIndent) {
commonIndent = indent;
}
}
return lines.map((line, i) => i === 0 ? line : line.slice(commonIndent)).slice(
(_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0,
lastNonEmptyLine + 1
);
}
function leadingWhitespace(str) {
let i = 0;
while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {
++i;
}
return i;
}
function printBlockString(value, options) {
const escapedValue = value.replace(/"""/g, '\\"""');
const lines = escapedValue.split(/\r\n|[\n\r]/g);
const isSingleLine = lines.length === 1;
const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0)));
const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""');
const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes;
const hasTrailingSlash = value.endsWith("\\");
const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;
const printAsMultipleLines = !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability
(!isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes);
let result = "";
const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));
if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) {
result += "\n";
}
result += escapedValue;
if (printAsMultipleLines || forceTrailingNewline) {
result += "\n";
}
return '"""' + result + '"""';
}
// ../../node_modules/graphql/language/tokenKind.mjs
var TokenKind;
(function(TokenKind2) {
TokenKind2["SOF"] = "<SOF>";
TokenKind2["EOF"] = "<EOF>";
TokenKind2["BANG"] = "!";
TokenKind2["DOLLAR"] = "$";
TokenKind2["AMP"] = "&";
TokenKind2["PAREN_L"] = "(";
TokenKind2["PAREN_R"] = ")";
TokenKind2["SPREAD"] = "...";
TokenKind2["COLON"] = ":";
TokenKind2["EQUALS"] = "=";
TokenKind2["AT"] = "@";
TokenKind2["BRACKET_L"] = "[";
TokenKind2["BRACKET_R"] = "]";
TokenKind2["BRACE_L"] = "{";
TokenKind2["PIPE"] = "|";
TokenKind2["BRACE_R"] = "}";
TokenKind2["NAME"] = "Name";
TokenKind2["INT"] = "Int";
TokenKind2["FLOAT"] = "Float";
TokenKind2["STRING"] = "String";
TokenKind2["BLOCK_STRING"] = "BlockString";
TokenKind2["COMMENT"] = "Comment";
})(TokenKind || (TokenKind = {}));
// ../../node_modules/graphql/language/lexer.mjs
var Lexer = class {
/**
* The previously focused non-ignored token.
*/
/**
* The currently focused non-ignored token.
*/
/**
* The (1-indexed) line containing the current token.
*/
/**
* The character offset at which the current line begins.
*/
constructor(source) {
const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);
this.source = source;
this.lastToken = startOfFileToken;
this.token = startOfFileToken;
this.line = 1;
this.lineStart = 0;
}
get [Symbol.toStringTag]() {
return "Lexer";
}
/**
* Advances the token stream to the next non-ignored token.
*/
advance() {
this.lastToken = this.token;
const token = this.token = this.lookahead();
return token;
}
/**
* Looks ahead and returns the next non-ignored token, but does not change
* the state of Lexer.
*/
lookahead() {
let token = this.token;
if (token.kind !== TokenKind.EOF) {
do {
if (token.next) {
token = token.next;
} else {
const nextToken = readNextToken(this, token.end);
token.next = nextToken;
nextToken.prev = token;
token = nextToken;
}
} while (token.kind === TokenKind.COMMENT);
}
return token;
}
};
function isPunctuatorTokenKind(kind) {
return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;
}
function isUnicodeScalarValue(code) {
return code >= 0 && code <= 55295 || code >= 57344 && code <= 1114111;
}
function isSupplementaryCodePoint(body, location) {
return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1));
}
function isLeadingSurrogate(code) {
return code >= 55296 && code <= 56319;
}
function isTrailingSurrogate(code) {
return code >= 56320 && code <= 57343;
}
function printCodePointAt(lexer, location) {
const code = lexer.source.body.codePointAt(location);
if (code === void 0) {
return TokenKind.EOF;
} else if (code >= 32 && code <= 126) {
const char = String.fromCodePoint(code);
return char === '"' ? `'"'` : `"${char}"`;
}
return "U+" + code.toString(16).toUpperCase().padStart(4, "0");
}
function createToken(lexer, kind, start, end, value) {
const line = lexer.line;
const col = 1 + start - lexer.lineStart;
return new Token(kind, start, end, line, col, value);
}
function readNextToken(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start;
while (position < bodyLength) {
const code = body.charCodeAt(position);
switch (code) {
case 65279:
case 9:
case 32:
case 44:
++position;
continue;
case 10:
++position;
++lexer.line;
lexer.lineStart = position;
continue;
case 13:
if (body.charCodeAt(position + 1) === 10) {
position += 2;
} else {
++position;
}
++lexer.line;
lexer.lineStart = position;
continue;
case 35:
return readComment(lexer, position);
case 33:
return createToken(lexer, TokenKind.BANG, position, position + 1);
case 36:
return createToken(lexer, TokenKind.DOLLAR, position, position + 1);
case 38:
return createToken(lexer, TokenKind.AMP, position, position + 1);
case 40:
return createToken(lexer, TokenKind.PAREN_L, position, position + 1);
case 41:
return createToken(lexer, TokenKind.PAREN_R, position, position + 1);
case 46:
if (body.charCodeAt(position + 1) === 46 && body.charCodeAt(position + 2) === 46) {
return createToken(lexer, TokenKind.SPREAD, position, position + 3);
}
break;
case 58:
return createToken(lexer, TokenKind.COLON, position, position + 1);
case 61:
return createToken(lexer, TokenKind.EQUALS, position, position + 1);
case 64:
return createToken(lexer, TokenKind.AT, position, position + 1);
case 91:
return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);
case 93:
return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);
case 123:
return createToken(lexer, TokenKind.BRACE_L, position, position + 1);
case 124:
return createToken(lexer, TokenKind.PIPE, position, position + 1);
case 125:
return createToken(lexer, TokenKind.BRACE_R, position, position + 1);
case 34:
if (body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
return readBlockString(lexer, position);
}
return readString(lexer, position);
}
if (isDigit(code) || code === 45) {
return readNumber(lexer, position, code);
}
if (isNameStart(code)) {
return readName(lexer, position);
}
throw syntaxError(
lexer.source,
position,
code === 39 ? `Unexpected single quote character ('), did you mean to use a double quote (")?` : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`
);
}
return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);
}
function readComment(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 10 || code === 13) {
break;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
break;
}
}
return createToken(
lexer,
TokenKind.COMMENT,
start,
position,
body.slice(start + 1, position)
);
}
function readNumber(lexer, start, firstCode) {
const body = lexer.source.body;
let position = start;
let code = firstCode;
let isFloat = false;
if (code === 45) {
code = body.charCodeAt(++position);
}
if (code === 48) {
code = body.charCodeAt(++position);
if (isDigit(code)) {
throw syntaxError(
lexer.source,
position,
`Invalid number, unexpected digit after 0: ${printCodePointAt(
lexer,
position
)}.`
);
}
} else {
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 46) {
isFloat = true;
code = body.charCodeAt(++position);
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 69 || code === 101) {
isFloat = true;
code = body.charCodeAt(++position);
if (code === 43 || code === 45) {
code = body.charCodeAt(++position);
}
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 46 || isNameStart(code)) {
throw syntaxError(
lexer.source,
position,
`Invalid number, expected digit but got: ${printCodePointAt(
lexer,
position
)}.`
);
}
return createToken(
lexer,
isFloat ? TokenKind.FLOAT : TokenKind.INT,
start,
position,
body.slice(start, position)
);
}
function readDigits(lexer, start, firstCode) {
if (!isDigit(firstCode)) {
throw syntaxError(
lexer.source,
start,
`Invalid number, expected digit but got: ${printCodePointAt(
lexer,
start
)}.`
);
}
const body = lexer.source.body;
let position = start + 1;
while (isDigit(body.charCodeAt(position))) {
++position;
}
return position;
}
function readString(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
let chunkStart = position;
let value = "";
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 34) {
value += body.slice(chunkStart, position);
return createToken(lexer, TokenKind.STRING, start, position + 1, value);
}
if (code === 92) {
value += body.slice(chunkStart, position);
const escape = body.charCodeAt(position + 1) === 117 ? body.charCodeAt(position + 2) === 123 ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position);
value += escape.value;
position += escape.size;
chunkStart = position;
continue;
}
if (code === 10 || code === 13) {
break;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
throw syntaxError(
lexer.source,
position,
`Invalid character within String: ${printCodePointAt(
lexer,
position
)}.`
);
}
}
throw syntaxError(lexer.source, position, "Unterminated string.");
}
function readEscapedUnicodeVariableWidth(lexer, position) {
const body = lexer.source.body;
let point = 0;
let size = 3;
while (size < 12) {
const code = body.charCodeAt(position + size++);
if (code === 125) {
if (size < 5 || !isUnicodeScalarValue(point)) {
break;
}
return {
value: String.fromCodePoint(point),
size
};
}
point = point << 4 | readHexDigit(code);
if (point < 0) {
break;
}
}
throw syntaxError(
lexer.source,
position,
`Invalid Unicode escape sequence: "${body.slice(
position,
position + size
)}".`
);
}
function readEscapedUnicodeFixedWidth(lexer, position) {
const body = lexer.source.body;
const code = read16BitHexCode(body, position + 2);
if (isUnicodeScalarValue(code)) {
return {
value: String.fromCodePoint(code),
size: 6
};
}
if (isLeadingSurrogate(code)) {
if (body.charCodeAt(position + 6) === 92 && body.charCodeAt(position + 7) === 117) {
const trailingCode = read16BitHexCode(body, position + 8);
if (isTrailingSurrogate(trailingCode)) {
return {
value: String.fromCodePoint(code, trailingCode),
size: 12
};
}
}
}
throw syntaxError(
lexer.source,
position,
`Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`
);
}
function read16BitHexCode(body, position) {
return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3));
}
function readHexDigit(code) {
return code >= 48 && code <= 57 ? code - 48 : code >= 65 && code <= 70 ? code - 55 : code >= 97 && code <= 102 ? code - 87 : -1;
}
function readEscapedCharacter(lexer, position) {
const body = lexer.source.body;
const code = body.charCodeAt(position + 1);
switch (code) {
case 34:
return {
value: '"',
size: 2
};
case 92:
return {
value: "\\",
size: 2
};
case 47:
return {
value: "/",
size: 2
};
case 98:
return {
value: "\b",
size: 2
};
case 102:
return {
value: "\f",
size: 2
};
case 110:
return {
value: "\n",
size: 2
};
case 114:
return {
value: "\r",
size: 2
};
case 116:
return {
value: " ",
size: 2
};
}
throw syntaxError(
lexer.source,
position,
`Invalid character escape sequence: "${body.slice(
position,
position + 2
)}".`
);
}
function readBlockString(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let lineStart = lexer.lineStart;
let position = start + 3;
let chunkStart = position;
let currentLine = "";
const blockLines = [];
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
currentLine += body.slice(chunkStart, position);
blockLines.push(currentLine);
const token = createToken(
lexer,
TokenKind.BLOCK_STRING,
start,
position + 3,
// Return a string of the lines joined with U+000A.
dedentBlockStringLines(blockLines).join("\n")
);
lexer.line += blockLines.length - 1;
lexer.lineStart = lineStart;
return token;
}
if (code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {
currentLine += body.slice(chunkStart, position);
chunkStart = position + 1;
position += 4;
continue;
}
if (code === 10 || code === 13) {
currentLine += body.slice(chunkStart, position);
blockLines.push(currentLine);
if (code === 13 && body.charCodeAt(position + 1) === 10) {
position += 2;
} else {
++position;
}
currentLine = "";
chunkStart = position;
lineStart = position;
continue;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
throw syntaxError(
lexer.source,
position,
`Invalid character within String: ${printCodePointAt(
lexer,
position
)}.`
);
}
}
throw syntaxError(lexer.source, position, "Unterminated string.");
}
function readName(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (isNameContinue(code)) {
++position;
} else {
break;
}
}
return createToken(
lexer,
TokenKind.NAME,
start,
position,
body.slice(start, position)
);
}
// ../../node_modules/graphql/jsutils/inspect.mjs
var MAX_ARRAY_LENGTH = 10;
var MAX_RECURSIVE_DEPTH = 2;
function inspect(value) {
return formatValue(value, []);
}
function formatValue(value, seenValues) {
switch (typeof value) {
case "string":
return JSON.stringify(value);
case "function":
return value.name ? `[function ${value.name}]` : "[function]";
case "object":
return formatObjectValue(value, seenValues);
default:
return String(value);
}
}
function formatObjectValue(value, previouslySeenValues) {
if (value === null) {
return "null";
}
if (previouslySeenValues.includes(value)) {
return "[Circular]";
}
const seenValues = [...previouslySeenValues, value];
if (isJSONable(value)) {
const jsonValue = value.toJSON();
if (jsonValue !== value) {
return typeof jsonValue === "string" ? jsonValue : formatValue(jsonValue, seenValues);
}
} else if (Array.isArray(value)) {
return formatArray(value, seenValues);
}
return formatObject(value, seenValues);
}
function isJSONable(value) {
return typeof value.toJSON === "function";
}
function formatObject(object, seenValues) {
const entries = Object.entries(object);
if (entries.length === 0) {
return "{}";
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return "[" + getObjectTag(object) + "]";
}
const properties = entries.map(
([key, value]) => key + ": " + formatValue(value, seenValues)
);
return "{ " + properties.join(", ") + " }";
}
function formatArray(array, seenValues) {
if (array.length === 0) {
return "[]";
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return "[Array]";
}
const len = Math.min(MAX_ARRAY_LENGTH, array.length);
const remaining = array.length - len;
const items = [];
for (let i = 0; i < len; ++i) {
items.push(formatValue(array[i], seenValues));
}
if (remaining === 1) {
items.push("... 1 more item");
} else if (remaining > 1) {
items.push(`... ${remaining} more items`);
}
return "[" + items.join(", ") + "]";
}
function getObjectTag(object) {
const tag = Object.prototype.toString.call(object).replace(/^\[object /, "").replace(/]$/, "");
if (tag === "Object" && typeof object.constructor === "function") {
const name = object.constructor.name;
if (typeof name === "string" && name !== "") {
return name;
}
}
return tag;
}
// ../../node_modules/graphql/jsutils/instanceOf.mjs
var instanceOf = (
/* c8 ignore next 6 */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
globalThis.process && globalThis.process.env.NODE_ENV === "production" ? function instanceOf2(value, constructor) {
return value instanceof constructor;
} : function instanceOf3(value, constructor) {
if (value instanceof constructor) {
return true;
}
if (typeof value === "object" && value !== null) {
var _value$constructor;
const className = constructor.prototype[Symbol.toStringTag];
const valueClassName = (
// We still need to support constructor's name to detect conflicts with older versions of this library.
Symbol.toStringTag in value ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name
);
if (className === valueClassName) {
const stringifiedValue = inspect(value);
throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.`);
}
}
return false;
}
);
// ../../node_modules/graphql/language/source.mjs
var Source = class {
constructor(body, name = "GraphQL request", locationOffset = {
line: 1,
column: 1
}) {
typeof body === "string" || devAssert(false, `Body must be a string. Received: ${inspect(body)}.`);
this.body = body;
this.name = name;
this.locationOffset = locationOffset;
this.locationOffset.line > 0 || devAssert(
false,
"line in locationOffset is 1-indexed and must be positive."
);
this.locationOffset.column > 0 || devAssert(
false,
"column in locationOffset is 1-indexed and must be positive."
);
}
get [Symbol.toStringTag]() {
return "Source";
}
};
function isSource(source) {
return instanceOf(source, Source);
}
// ../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs
function stripIgnoredCharacters(source) {
const sourceObj = isSource(source) ? source : new Source(source);
const body = sourceObj.body;
const lexer = new Lexer(sourceObj);
let strippedBody = "";
let wasLastAddedTokenNonPunctuator = false;
while (lexer.advance().kind !== TokenKind.EOF) {
const currentToken = lexer.token;
const tokenKind = currentToken.kind;
const isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind);
if (wasLastAddedTokenNonPunctuator) {
if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) {
strippedBody += " ";
}
}
const tokenBody = body.slice(currentToken.start, currentToken.end);
if (tokenKind === TokenKind.BLOCK_STRING) {
strippedBody += printBlockString(currentToken.value, {
minimize: true
});
} else {
strippedBody += tokenBody;
}
wasLastAddedTokenNonPunctuator = isNonPunctuator;
}
return strippedBody;
}
// src/DataTransportAbstraction/transportedOptions.ts
function serializeOptions(options) {
return {
...options,
query: printMinified(options.query)
};
}
function deserializeOptions(options) {
return {
...options,
// `gql` memoizes results, but based on the input string.
// We parse-stringify-parse here to ensure that our minified query
// has the best chance of being the referential same query as the one used in
// client-side code.
query: gql(print(gql(options.query)))
};
}
function printMinified(query) {
return stripIgnoredCharacters(print(query));
}
function reviveTransportedQueryRef(queryRef, client) {
const hydratedOptions = deserializeOptions(queryRef.options);
const cacheKey = [
hydratedOptions.query,
canonicalStringify(hydratedOptions.variables),
queryRef.queryKey
];
if (queryRef.__transportedQueryRef === true) {
queryRef.__transportedQueryRef = wrapQueryRef(
getSuspenseCache(client).getQueryRef(
cacheKey,
() => client.watchQuery(hydratedOptions)
)
);
}
return [queryRef.__transportedQueryRef, cacheKey];
}
function isTransportedQueryRef(queryRef) {
return "__transportedQueryRef" in queryRef;
}
function useWrapTransportedQueryRef(queryRef) {
const client = useApolloClient();
let cacheKey;
let isTransported;
if (isTransported = isTransportedQueryRef(queryRef)) {
[queryRef, cacheKey] = reviveTransportedQueryRef(queryRef, client);
}
assertWrappedQueryRef(queryRef);
const unwrapped = unwrapQueryRef(queryRef);
useEffect(() => {
if (!isTransported)
return;
if (cacheKey) {
if (unwrapped.disposed) {
getSuspenseCache(client).add(cacheKey, unwrapped);
}
}
});
useEffect(() => {
if (isTransported) {
return unwrapped.softRetain();
}
}, [isTransported, unwrapped]);
return queryRef;
}
// src/DataTransportAbstraction/hooks.ts

@@ -200,3 +1444,13 @@ var hookWrappers = {

useReadQuery(orig_useReadQuery) {
return wrap(orig_useReadQuery, ["data", "networkStatus"]);
return wrap(
(queryRef) => {
return orig_useReadQuery(useWrapTransportedQueryRef(queryRef));
},
["data", "networkStatus"]
);
},
useQueryRefHandlers(orig_useQueryRefHandlers) {
return wrap((queryRef) => {
return orig_useQueryRefHandlers(useWrapTransportedQueryRef(queryRef));
}, []);
}

@@ -207,2 +1461,5 @@ };

const result = useFn(...args);
if (transportKeys.length == 0) {
return result;
}
const transported = {};

@@ -216,8 +1473,10 @@ for (const key of transportKeys) {

// src/bundleInfo.ts
var bundle = {
pkg: "@apollo/client-react-streaming",
client: "ApolloClient",
cache: "InMemoryCache"
};
// src/assertInstance.ts
function assertInstance(value, info, name) {
if (value[sourceSymbol] !== `${info.pkg}:${name}`) {
throw new Error(
`When using \`${name}\` in streaming SSR, you must use the \`${name}\` export provided by \`"${info.pkg}"\`.`
);
}
}

@@ -228,2 +1487,5 @@ // src/DataTransportAbstraction/WrappedApolloClient.tsx

}
function getTrieConstructor(client) {
return getQueryManager(client)["inFlightLinkObservables"].constructor;
}
var wrappers = Symbol.for("apollo.hook.wrappers");

@@ -237,2 +1499,3 @@ var ApolloClientBase = class extends ApolloClient$1 {

static info = bundle;
[sourceSymbol];
constructor(options) {

@@ -245,17 +1508,149 @@ super(

);
if (!(this.cache instanceof InMemoryCache)) {
throw new Error(
`When using \`InMemoryCache\` in streaming SSR, you must use the \`${this.constructor.info.cache}\` export provided by \`"${this.constructor.info.pkg}"\`.`
);
}
const info = this.constructor.info;
this[sourceSymbol] = `${info.pkg}:ApolloClient`;
assertInstance(
this.cache,
info,
"InMemoryCache"
);
}
};
var ApolloClientSSRImpl = class extends ApolloClientBase {
var ApolloClientClientBaseImpl = class extends ApolloClientBase {
constructor(options) {
super(options);
this.onQueryStarted = this.onQueryStarted.bind(this);
getQueryManager(this)[wrappers] = hookWrappers;
}
simulatedStreamingQueries = /* @__PURE__ */ new Map();
transportedQueryOptions = /* @__PURE__ */ new Map();
identifyUniqueQuery(options) {
const transformedDocument = this.documentTransform.transformDocument(
options.query
);
const queryManager = getQueryManager(this);
const { serverQuery } = queryManager.getDocumentInfo(transformedDocument);
if (!serverQuery) {
throw new Error("could not identify unique query");
}
const canonicalVariables = canonicalStringify(options.variables || {});
const cacheKeyArr = [print(serverQuery), canonicalVariables];
const cacheKey = JSON.stringify(cacheKeyArr);
return {
cacheKey,
cacheKeyArr
};
}
onQueryStarted({ options, id }) {
const hydratedOptions = deserializeOptions(options);
const { cacheKey, cacheKeyArr } = this.identifyUniqueQuery(hydratedOptions);
this.transportedQueryOptions.set(id, hydratedOptions);
const queryManager = getQueryManager(this);
if (!queryManager["inFlightLinkObservables"].peekArray(cacheKeyArr)?.observable) {
let simulatedStreamingQuery, fetchCancelFn;
const cleanup = () => {
if (queryManager["fetchCancelFns"].get(cacheKey) === fetchCancelFn)
queryManager["fetchCancelFns"].delete(cacheKey);
queryManager["inFlightLinkObservables"].removeArray(cacheKeyArr);
if (this.simulatedStreamingQueries.get(id) === simulatedStreamingQuery)
this.simulatedStreamingQueries.delete(id);
};
const promise = new Promise((resolve, reject) => {
this.simulatedStreamingQueries.set(
id,
simulatedStreamingQuery = {
resolve,
reject,
options: hydratedOptions
}
);
});
promise.then(cleanup, cleanup);
const observable = new Observable$1((observer) => {
promise.then((result) => {
observer.next(result);
observer.complete();
}).catch((err) => {
observer.error(err);
});
});
queryManager["inFlightLinkObservables"].lookupArray(
cacheKeyArr
).observable = observable;
queryManager["fetchCancelFns"].set(
cacheKey,
fetchCancelFn = (reason) => {
const { reject } = this.simulatedStreamingQueries.get(id) ?? {};
if (reject) {
reject(reason);
}
cleanup();
}
);
}
}
onQueryProgress = (event) => {
const queryInfo = this.simulatedStreamingQueries.get(event.id);
if (event.type === "data") {
queryInfo?.resolve?.({
data: event.result.data
});
const options = this.transportedQueryOptions.get(event.id);
if (options) {
this.cache.writeQuery({
query: options.query,
data: event.result.data,
variables: options.variables
});
}
} else if (event.type === "error") {
if (queryInfo) {
this.simulatedStreamingQueries.delete(event.id);
{
invariant$1.debug(
"Query failed upstream, will fail it during SSR and rerun it in the browser:",
queryInfo.options
);
queryInfo?.reject?.(new Error("Query failed upstream."));
}
}
this.transportedQueryOptions.delete(event.id);
} else if (event.type === "complete") {
this.transportedQueryOptions.delete(event.id);
}
};
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries = () => {
for (const [id, queryInfo] of this.simulatedStreamingQueries) {
this.simulatedStreamingQueries.delete(id);
invariant$1.debug(
"streaming connection closed before server query could be fully transported, rerunning:",
queryInfo.options
);
this.rerunSimulatedQuery(queryInfo);
}
};
rerunSimulatedQuery = (queryInfo) => {
const queryManager = getQueryManager(this);
const queryId = queryManager.generateQueryId();
queryManager.fetchQuery(queryId, {
...queryInfo.options,
query: queryManager.transform(queryInfo.options.query),
context: {
...queryInfo.options.context,
queryDeduplication: false
}
}).finally(() => queryManager.stopQuery(queryId)).then(queryInfo.resolve, queryInfo.reject);
};
};
var ApolloClientSSRImpl = class extends ApolloClientClientBaseImpl {
forwardedQueries = new (getTrieConstructor(this))();
watchQueryQueue = createBackpressuredCallback();
watchQuery(options) {
if (options.fetchPolicy !== "cache-only" && options.fetchPolicy !== "standby") {
const { cacheKeyArr } = this.identifyUniqueQuery(options);
if (options.fetchPolicy !== "cache-only" && options.fetchPolicy !== "standby" && !this.forwardedQueries.peekArray(cacheKeyArr)) {
this.forwardedQueries.lookupArray(cacheKeyArr);
const observableQuery = super.watchQuery(options);

@@ -294,3 +1689,3 @@ const queryInfo = observableQuery["queryInfo"];

type: "started",
options,
options: serializeOptions(options),
id

@@ -304,2 +1699,8 @@ },

}
onQueryStarted(event) {
const hydratedOptions = deserializeOptions(event.options);
const { cacheKeyArr } = this.identifyUniqueQuery(hydratedOptions);
this.forwardedQueries.lookupArray(cacheKeyArr);
super.onQueryStarted(event);
}
};

@@ -325,11 +1726,11 @@ var ApolloClientImplementation = ApolloClientSSRImpl ;

}) => {
const clientRef = useRef();
{
if (!clientRef.current) {
const clientRef = useRef(void 0);
if (!clientRef.current) {
{
clientRef.current = makeClient();
}
}
if (!(clientRef.current instanceof ApolloClient)) {
throw new Error(
`When using \`ApolloClient\` in streaming SSR, you must use the \`${WrappedApolloProvider3.info.client}\` export provided by \`"${WrappedApolloProvider3.info.pkg}"\`.`
assertInstance(
clientRef.current,
WrappedApolloProvider3.info,
"ApolloClient"
);

@@ -336,0 +1737,0 @@ }

@@ -20,3 +20,3 @@ import React from 'react';

interface BuildArgs {
interface ManualDataTransportOptions {
/**

@@ -27,2 +27,13 @@ * A hook that allows for insertion into the stream.

useInsertHtml(): (callbacks: () => React.ReactNode) => void;
/**
* Prepare data for injecting into the stream by converting it into a string that can be parsed as JavaScript by the browser.
* Could e.g. be `SuperJSON.stringify` or `serialize-javascript`.
* The default implementation act like a JSON.stringify that preserves `undefined`, but not do much on top of that.
*/
stringifyForStream?: (value: any) => string;
/**
* If necessary, additional deserialization steps that need to be applied on top of executing the result of `stringifyForStream` in the browser.
* Could e.g. be `SuperJSON.deserialize`. (Not needed in the case of using `serialize-javascript`)
*/
reviveFromStream?: (value: any) => any;
}

@@ -77,3 +88,3 @@ /**

*/
declare const buildManualDataTransport: (args: BuildArgs) => DataTransportProviderImplementation<HydrationContextOptions>;
declare const buildManualDataTransport: (args: ManualDataTransportOptions) => DataTransportProviderImplementation<HydrationContextOptions>;

@@ -80,0 +91,0 @@ /**

import React2, { useRef, useEffect, useCallback, useId, useMemo } from 'react';
import { resetApolloSingletons, DataTransportContext } from '@apollo/client-react-streaming';
import SuperJSON from 'superjson';
import { invariant } from 'ts-invariant';

@@ -29,6 +28,7 @@

onQueryEvent,
onRehydrate
onRehydrate,
revive: revive2
}) {
registerLateInitializingQueue(ApolloSSRDataTransport, (data) => {
const parsed = SuperJSON.deserialize(data);
const parsed = revive2(data);
invariant.debug(`received data from the server:`, parsed);

@@ -42,4 +42,11 @@ onRehydrate(parsed.rehydrate);

// src/ManualDataTransport/serialization.ts
function revive(value) {
return value;
}
// src/ManualDataTransport/ManualDataTransport.tsx
var buildManualDataTransportBrowserImpl = () => function ManualDataTransportBrowserImpl({
var buildManualDataTransportBrowserImpl = ({
reviveFromStream = revive
}) => function ManualDataTransportBrowserImpl({
children,

@@ -54,3 +61,4 @@ onQueryEvent,

Object.assign(hookRehydrationCache.current, rehydrate);
}
},
revive: reviveFromStream
});

@@ -57,0 +65,0 @@ useEffect(() => {

@@ -20,3 +20,3 @@ import React from 'react';

interface BuildArgs {
interface ManualDataTransportOptions {
/**

@@ -27,2 +27,13 @@ * A hook that allows for insertion into the stream.

useInsertHtml(): (callbacks: () => React.ReactNode) => void;
/**
* Prepare data for injecting into the stream by converting it into a string that can be parsed as JavaScript by the browser.
* Could e.g. be `SuperJSON.stringify` or `serialize-javascript`.
* The default implementation act like a JSON.stringify that preserves `undefined`, but not do much on top of that.
*/
stringifyForStream?: (value: any) => string;
/**
* If necessary, additional deserialization steps that need to be applied on top of executing the result of `stringifyForStream` in the browser.
* Could e.g. be `SuperJSON.deserialize`. (Not needed in the case of using `serialize-javascript`)
*/
reviveFromStream?: (value: any) => any;
}

@@ -77,3 +88,3 @@ /**

*/
declare const buildManualDataTransport: (args: BuildArgs) => DataTransportProviderImplementation<HydrationContextOptions>;
declare const buildManualDataTransport: (args: ManualDataTransportOptions) => DataTransportProviderImplementation<HydrationContextOptions>;

@@ -80,0 +91,0 @@ /**

import React, { useRef, useMemo, useId } from 'react';
import { resetApolloSingletons, DataTransportContext } from '@apollo/client-react-streaming';
import SuperJSON from 'superjson';
import { invariant } from 'ts-invariant';

@@ -27,11 +26,12 @@

// src/ManualDataTransport/dataTransport.ts
function transportDataToJS(data) {
function transportDataToJS(data, stringify2) {
const key = Symbol.keyFor(ApolloSSRDataTransport);
return `(window[Symbol.for("${key}")] ??= []).push(${htmlEscapeJsonString(
SuperJSON.stringify(data)
stringify2(data)
)})`;
}
function buildApolloRehydrationContext({
extraScriptProps,
insertHtml
insertHtml,
stringify: stringify2,
extraScriptProps
}) {

@@ -58,10 +58,13 @@ function ensureInserted() {

invariant.debug("transporting events", rehydrationContext.incomingEvents);
const __html = transportDataToJS({
rehydrate: Object.fromEntries(
Object.entries(rehydrationContext.transportValueData).filter(
([key, value]) => rehydrationContext.transportedValues[key] !== value
)
),
events: rehydrationContext.incomingEvents
});
const __html = transportDataToJS(
{
rehydrate: Object.fromEntries(
Object.entries(rehydrationContext.transportValueData).filter(
([key, value]) => rehydrationContext.transportedValues[key] !== value
)
),
events: rehydrationContext.incomingEvents
},
stringify2
);
Object.assign(

@@ -111,5 +114,19 @@ rehydrationContext.transportedValues,

// src/ManualDataTransport/serialization.ts
function stringify(value) {
let undefinedPlaceholder = "$apollo.undefined$";
const stringified = JSON.stringify(value);
while (stringified.includes(JSON.stringify(undefinedPlaceholder))) {
undefinedPlaceholder = "$" + undefinedPlaceholder;
}
return JSON.stringify(
value,
(_, v) => v === void 0 ? undefinedPlaceholder : v
).replaceAll(JSON.stringify(undefinedPlaceholder), "undefined");
}
// src/ManualDataTransport/ManualDataTransport.tsx
var buildManualDataTransportSSRImpl = ({
useInsertHtml
useInsertHtml,
stringifyForStream = stringify
}) => function ManualDataTransportSSRImpl({

@@ -121,7 +138,8 @@ extraScriptProps,

const insertHtml = useInsertHtml();
const rehydrationContext = useRef();
const rehydrationContext = useRef(void 0);
if (!rehydrationContext.current) {
rehydrationContext.current = buildApolloRehydrationContext({
insertHtml,
extraScriptProps
extraScriptProps,
stringify: stringifyForStream
});

@@ -128,0 +146,0 @@ }

{
"name": "@apollo/client-react-streaming",
"version": "0.10.1",
"version": "0.11.0",
"repository": {

@@ -79,2 +79,18 @@ "url": "git+https://github.com/apollographql/apollo-client-nextjs"

},
"./stream-utils": {
"require": {
"types": "./dist/stream-utils.node.d.cts",
"edge-light": "./dist/stream-utils.node.cjs",
"react-server": "./dist/empty.cjs",
"browser": "./dist/empty.cjs",
"node": "./dist/stream-utils.node.cjs"
},
"import": {
"types": "./dist/stream-utils.node.d.ts",
"edge-light": "./dist/stream-utils.node.js",
"react-server": "./dist/empty.js",
"browser": "./dist/empty.js",
"node": "./dist/stream-utils.node.js"
}
},
"./package.json": "./package.json"

@@ -86,2 +102,5 @@ },

"./dist/manual-transport.ssr.d.ts"
],
"stream-utils": [
"./dist/stream-utils.node.d.ts"
]

@@ -103,5 +122,5 @@ }

"test:base": "TSX_TSCONFIG_PATH=./tsconfig.tests.json node --import tsx/esm --no-warnings --test \"$@\" src/**/*.test.(ts|tsx)",
"test:ssr": "NODE_OPTIONS=\"$NODE_OPTIONS --conditions=node\" yarn run test:base",
"test:browser": "NODE_OPTIONS=\"$NODE_OPTIONS --conditions=browser\" yarn run test:base",
"test:rsc": "NODE_OPTIONS=\"$NODE_OPTIONS --conditions=react-server\" yarn run test:base",
"test:ssr": "NODE_OPTIONS=\"${NODE_OPTIONS:-} --conditions=node\" yarn run test:base",
"test:browser": "NODE_OPTIONS=\"${NODE_OPTIONS:-} --conditions=browser\" yarn run test:base",
"test:rsc": "NODE_OPTIONS=\"${NODE_OPTIONS:-} --conditions=react-server\" yarn run test:base",
"prepack": "yarn build",

@@ -118,10 +137,11 @@ "prepublishOnly": "yarn pack -o attw.tgz && attw attw.tgz && rm attw.tgz && yarn run test",

"devDependencies": {
"@apollo/client": "3.9.9",
"@arethetypeswrong/cli": "0.15.2",
"@microsoft/api-extractor": "7.43.0",
"@testing-library/react": "14.2.2",
"@apollo/client": "^3.10.4",
"@arethetypeswrong/cli": "0.15.3",
"@internal/test-utils": "workspace:^",
"@microsoft/api-extractor": "7.43.2",
"@testing-library/react": "15.0.7",
"@total-typescript/shoehorn": "0.1.2",
"@tsconfig/recommended": "1.0.5",
"@types/node": "20.12.2",
"@types/react": "18.2.73",
"@tsconfig/recommended": "1.0.6",
"@types/node": "20.12.11",
"@types/react": "18.3.1",
"@typescript-eslint/eslint-plugin": "7.5.0",

@@ -139,21 +159,19 @@ "@typescript-eslint/parser": "7.5.0",

"publint": "0.2.7",
"react": "18.3.0-canary-60a927d04-20240113",
"react": "18.3.0",
"react-error-boundary": "4.0.13",
"react-server-dom-webpack": "18.3.0-canary-60a927d04-20240113",
"react-server-dom-webpack": "0.0.1",
"rimraf": "5.0.5",
"superjson": "1.13.3",
"ts-node": "10.9.2",
"tsup": "8.0.2",
"tsx": "4.7.1",
"typescript": "5.4.3",
"vitest": "1.4.0"
"typescript": "5.4.5",
"vitest": "1.6.0"
},
"peerDependencies": {
"@apollo/client": "^3.9.6",
"@apollo/client": "^3.10.4",
"react": "^18"
},
"dependencies": {
"superjson": "^1.12.2 || ^2.0.0",
"ts-invariant": "^0.10.3"
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc