UNPKG

@tanstack/react-db

Version:

React integration for @tanstack/db

61 lines (60 loc) • 2.33 kB
import { isCollection, BaseQueryBuilder, IR } from "@tanstack/db"; const sourceObjectTokens = /* @__PURE__ */ new WeakMap(); let nextSourceObjectToken = 0; function getSourceObjectToken(source) { let id = sourceObjectTokens.get(source); if (id === void 0) { id = ++nextSourceObjectToken; sourceObjectTokens.set(source, id); } return id; } function getPreparedSources(preparedValue) { if (isCollection(preparedValue)) return [preparedValue]; const query = preparedValue instanceof BaseQueryBuilder ? preparedValue : preparedValue && typeof preparedValue === `object` && `query` in preparedValue && preparedValue.query instanceof BaseQueryBuilder ? preparedValue.query : void 0; return query ? IR.collectCollectionSources(query._getQuery()).map( ({ collection }) => collection ) : []; } function createSourceIdBindings() { return { unscoped: /* @__PURE__ */ new Map(), byClient: /* @__PURE__ */ new WeakMap() }; } function claimSourceIds(bindings, preparedValue, client, hookName, release) { const prior = client ? bindings.byClient.get(client) : bindings.unscoped; const seen = /* @__PURE__ */ new Map(); for (const source of getPreparedSources(preparedValue)) { const token = getSourceObjectToken(source); const previous = seen.get(source.id) ?? prior?.get(source.id); if (previous !== void 0 && previous !== token) { release(); throw new Error( `[${hookName}] Source Collection "${source.id}" was replaced by a different Collection with the same ID while this hook is mounted. Unmount the hook and clean up its previous source and client scope before reusing the ID.` ); } seen.set(source.id, token); } const claimed = prior ?? /* @__PURE__ */ new Map(); for (const [id, token] of seen) claimed.set(id, token); if (client) bindings.byClient.set(client, claimed); } function resumeSyncStarts(collections) { const pending = Array.from(collections); collections.clear(); const errors = []; for (const collection of pending) { try { collection._resumeSyncStart(); } catch (error) { errors.push(error); } } if (errors.length) throw errors[0]; } export { claimSourceIds, createSourceIdBindings, getPreparedSources, getSourceObjectToken, resumeSyncStarts }; //# sourceMappingURL=source-id-bindings.js.map