@apollo/client-react-streaming
Version:
This package provides building blocks to create framework-level integration of Apollo Client with React's streaming SSR. See the [@apollo/client-integration-nextjs](https://github.com/apollographql/apollo-client-integrations/tree/main/packages/nextjs) pac
341 lines (324 loc) • 11.3 kB
JavaScript
;
"use client";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/SimulatePreloadedQuery.cc.ts
var SimulatePreloadedQuery_cc_exports = {};
__export(SimulatePreloadedQuery_cc_exports, {
default: () => SimulatePreloadedQuery
});
module.exports = __toCommonJS(SimulatePreloadedQuery_cc_exports);
var import_react9 = require("@apollo/client/react");
var import_react10 = require("react");
// src/transportedQueryRef.ts
var import_internal = require("@apollo/client/react/internal");
// src/ReadableStreamLink.tsx
var import_client = require("@apollo/client");
var teeToReadableStreamKey = Symbol.for(
"apollo.tee.readableStreamController"
);
var readFromReadableStreamKey = Symbol.for("apollo.read.readableStream");
function readFromReadableStream(readableStream, context) {
return Object.assign(context, {
[readFromReadableStreamKey]: readableStream
});
}
var TeeToReadableStreamLink = class extends import_client.ApolloLink {
constructor() {
super((operation, forward) => {
const context = operation.getContext();
const onLinkHit = context[teeToReadableStreamKey];
if (onLinkHit) {
const controller = onLinkHit();
const tryClose = () => {
try {
controller.close();
} catch {
}
};
return new import_client.Observable((observer) => {
const subscription = forward(operation).subscribe({
next(result) {
controller.enqueue({ type: "next", value: result });
observer.next(result);
},
error(error) {
controller.enqueue({ type: "error" });
tryClose();
observer.error(error);
},
complete() {
controller.enqueue({ type: "completed" });
tryClose();
observer.complete();
}
});
return () => {
tryClose();
subscription.unsubscribe();
};
});
}
return forward(operation);
});
}
};
var ReadFromReadableStreamLink = class extends import_client.ApolloLink {
constructor() {
super((operation, forward) => {
const context = operation.getContext();
const eventSteam = context[readFromReadableStreamKey];
if (eventSteam) {
return new import_client.Observable((observer) => {
let aborted = false;
const reader = (() => {
try {
return eventSteam.getReader();
} catch {
}
})();
if (!reader) {
const subscription = forward(operation).subscribe(observer);
return () => subscription.unsubscribe();
}
consume(reader);
let onAbort = () => {
aborted = true;
reader.cancel();
};
return () => onAbort();
async function consume(reader2) {
let event = void 0;
while (!aborted && !event?.done) {
event = await reader2.read();
if (aborted)
break;
if (event.value) {
switch (event.value.type) {
case "next":
observer.next(event.value.value);
break;
case "completed":
observer.complete();
break;
case "error":
if (false) {
observer.error(
new Error(
"Error from event stream. Redacted for security concerns."
)
);
} else {
onAbort();
const subscription = forward(operation).subscribe(observer);
onAbort = () => subscription.unsubscribe();
}
break;
}
}
}
}
});
}
return forward(operation);
});
}
};
// src/DataTransportAbstraction/WrappedInMemoryCache.tsx
var import_client2 = require("@apollo/client");
// 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 import_client2.InMemoryCache {
/**
* 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/DataTransportAbstraction/WrappedApolloClient.tsx
var import_client4 = require("@apollo/client");
var import_ts_invariant = require("ts-invariant");
// src/DataTransportAbstraction/useTransportValue.tsx
var import_react2 = require("react");
// src/DataTransportAbstraction/DataTransportAbstraction.ts
var import_react = require("react");
// src/DataTransportAbstraction/useTransportValue.tsx
var import_equality = require("@wry/equality");
// src/DataTransportAbstraction/hooks.ts
var import_react3 = require("react");
// src/DataTransportAbstraction/transportedOptions.ts
var import_client3 = require("@apollo/client");
var import_utilities = require("@apollo/client/utilities");
var import_graphql = require("graphql");
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: (0, import_client3.gql)((0, import_utilities.print)((0, import_client3.gql)(options.query)))
};
}
// 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}"\`.`
);
}
}
// src/DataTransportAbstraction/WrappedApolloClient.tsx
var wrappers = Symbol.for("apollo.hook.wrappers");
var ApolloClientBase = class extends import_client4.ApolloClient {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static info = bundle;
[sourceSymbol];
constructor(options) {
const warnings = [];
if ("ssrMode" in options) {
delete options.ssrMode;
warnings.push(
"The `ssrMode` option is not supported in %s. Please remove it from your %s constructor options."
);
}
if ("ssrForceFetchDelay" in options) {
delete options.ssrForceFetchDelay;
warnings.push(
"The `ssrForceFetchDelay` option is not supported in %s. Please remove it from your %s constructor options."
);
}
super(
false ? {
connectToDevTools: false,
...options
} : options
);
const info = this.constructor.info;
this[sourceSymbol] = `${info.pkg}:ApolloClient`;
for (const warning of warnings) {
console.warn(warning, info.pkg, "ApolloClient");
}
assertInstance(
this.cache,
info,
"InMemoryCache"
);
this.setLink(this.link);
}
setLink(newLink) {
super.setLink.call(
this,
import_client4.ApolloLink.from([
new ReadFromReadableStreamLink(),
new TeeToReadableStreamLink(),
newLink
])
);
}
};
var skipDataTransportKey = Symbol.for("apollo.dataTransport.skip");
function skipDataTransport(context) {
return Object.assign(context, {
[skipDataTransportKey]: true
});
}
// src/DataTransportAbstraction/WrapApolloProvider.tsx
var import_react4 = __toESM(require("react"), 1);
var import_react5 = require("react");
var import_react6 = require("@apollo/client/react");
// src/transportedQueryRef.ts
var import_react7 = require("@apollo/client/react");
var import_react8 = require("react");
var import_cache = require("@apollo/client/cache");
var import_stream_utils = require("@apollo/client-react-streaming/stream-utils");
var hydrationCache = /* @__PURE__ */ new WeakMap();
function reviveTransportedQueryRef(queryRef, client) {
const {
$__apollo_queryRef: { options, stream, queryKey }
} = queryRef;
if (!hydrationCache.has(queryRef)) {
const hydratedOptions = deserializeOptions(options);
const cacheKey = [
hydratedOptions.query,
(0, import_cache.canonicalStringify)(hydratedOptions.variables),
queryKey
];
hydrationCache.set(queryRef, { cacheKey });
const internalQueryRef = (0, import_internal.getSuspenseCache)(client).getQueryRef(
cacheKey,
() => client.watchQuery({
...hydratedOptions,
fetchPolicy: "network-only",
context: skipDataTransport(
readFromReadableStream(stream.pipeThrough(new import_stream_utils.JSONDecodeStream()), {
...hydratedOptions.context,
queryDeduplication: true
})
)
})
);
Object.assign(queryRef, (0, import_internal.wrapQueryRef)(internalQueryRef));
}
}
// src/SimulatePreloadedQuery.cc.ts
function SimulatePreloadedQuery({
queryRef,
children
}) {
const client = (0, import_react9.useApolloClient)();
reviveTransportedQueryRef(queryRef, client);
const bgQueryArgs = (0, import_react10.useMemo)(() => {
const { query, ...hydratedOptions } = deserializeOptions(
queryRef.$__apollo_queryRef.options
);
return [
query,
{ ...hydratedOptions, queryKey: queryRef.$__apollo_queryRef.queryKey }
];
}, [queryRef.$__apollo_queryRef]);
(0, import_react9.useBackgroundQuery)(...bgQueryArgs);
return children;
}
exports.built_for_browser = true;
//# sourceMappingURL=SimulatePreloadedQuery.cc.cjs.map