{"version":3,"file":"index.cjs","names":["resolveLiveQueryValue","isCollection","configPool","computed","signal","getLiveQueryStatusFlags","getPublicCollection","isSingleResultCollection","createLiveQueryObserver"],"sources":["../../src/index.ts"],"sourcesContent":["import {\n  assertInInjectionContext,\n  computed,\n  effect,\n  signal,\n  untracked,\n} from '@angular/core'\nimport {\n  configPool,\n  createLiveQueryObserver,\n  getLiveQueryStatusFlags,\n  getPublicCollection,\n  isCollection,\n  isSingleResultCollection,\n  resolveLiveQueryValue,\n} from '@tanstack/db'\nimport type {\n  Collection,\n  CollectionStatus,\n  Context,\n  GetResult,\n  InferResultType,\n  InitialQueryBuilder,\n  LiveQueryHookConfig,\n  LiveQuerySnapshot,\n  LiveQueryStatusFlags,\n  NonSingleResult,\n  PooledLiveQueries,\n  QueryBuilder,\n  SingleResult,\n} from '@tanstack/db'\nimport type { Signal } from '@angular/core'\n\nconst DEFAULT_GC_TIME_MS = 1\n\nexport * from '@tanstack/db'\n\n/**\n * The result of calling `injectLiveQuery`.\n * Contains reactive signals for the query state and data.\n */\n/** The status and flag signals every `injectLiveQuery` result has. */\nexport type InjectLiveQueryFlags = {\n  /** A signal containing the current status of the collection */\n  status: Signal<CollectionStatus | `disabled`>\n} & {\n  [K in keyof LiveQueryStatusFlags]: Signal<LiveQueryStatusFlags[K]>\n}\n\nexport interface InjectLiveQueryResult<\n  TContext extends Context,\n> extends InjectLiveQueryFlags {\n  /** A signal containing the complete state map of results keyed by their ID */\n  state: Signal<Map<string | number, GetResult<TContext>>>\n  /** A signal containing the results as an array, or single result for findOne queries */\n  data: Signal<InferResultType<TContext>>\n  /** A signal containing the underlying collection instance (null for disabled queries) */\n  collection: Signal<Collection<\n    GetResult<TContext>,\n    string | number,\n    {}\n  > | null>\n}\n\ntype InferConditionalResultType<TContext extends Context> =\n  TContext extends SingleResult\n    ? InferResultType<TContext> | []\n    : InferResultType<TContext>\n\nexport type InjectConditionalLiveQueryResult<TContext extends Context> = Omit<\n  InjectLiveQueryResult<TContext>,\n  `data`\n> & {\n  data: Signal<InferConditionalResultType<TContext>>\n}\n\nexport interface InjectLiveQueryResultWithCollection<\n  TResult extends object = any,\n  TKey extends string | number = string | number,\n  TUtils extends Record<string, any> = {},\n> extends InjectLiveQueryFlags {\n  state: Signal<Map<TKey, TResult>>\n  data: Signal<Array<TResult>>\n  collection: Signal<Collection<TResult, TKey, TUtils> | null>\n}\n\nexport interface InjectLiveQueryResultWithSingleResultCollection<\n  TResult extends object = any,\n  TKey extends string | number = string | number,\n  TUtils extends Record<string, any> = {},\n> extends InjectLiveQueryFlags {\n  state: Signal<Map<TKey, TResult>>\n  data: Signal<TResult | undefined>\n  collection: Signal<(Collection<TResult, TKey, TUtils> & SingleResult) | null>\n}\n\nexport function injectLiveQuery<\n  TContext extends Context,\n  TParams extends any,\n>(options: {\n  params: () => TParams\n  /** Pass `pooledLiveQueries` to share one partition among equal-shape queries. */\n  pool?: PooledLiveQueries\n  query: (args: {\n    params: TParams\n    q: InitialQueryBuilder\n  }) => QueryBuilder<TContext>\n}): InjectLiveQueryResult<TContext>\nexport function injectLiveQuery<\n  TContext extends Context,\n  TParams extends any,\n>(options: {\n  params: () => TParams\n  /** Pass `pooledLiveQueries` to share one partition among equal-shape queries. */\n  pool?: PooledLiveQueries\n  query: (args: {\n    params: TParams\n    q: InitialQueryBuilder\n  }) => QueryBuilder<TContext> | undefined | null\n}): InjectConditionalLiveQueryResult<TContext>\nexport function injectLiveQuery<TContext extends Context>(\n  queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n): InjectLiveQueryResult<TContext>\nexport function injectLiveQuery<TContext extends Context>(\n  queryFn: (\n    q: InitialQueryBuilder,\n  ) => QueryBuilder<TContext> | undefined | null,\n): InjectConditionalLiveQueryResult<TContext>\nexport function injectLiveQuery<TContext extends Context>(\n  config: LiveQueryHookConfig<TContext>,\n): InjectLiveQueryResult<TContext>\n// Pre-created collection without singleResult\nexport function injectLiveQuery<\n  TResult extends object,\n  TKey extends string | number,\n  TUtils extends Record<string, any>,\n>(\n  liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,\n): InjectLiveQueryResultWithCollection<TResult, TKey, TUtils>\n// Pre-created collection with singleResult\nexport function injectLiveQuery<\n  TResult extends object,\n  TKey extends string | number,\n  TUtils extends Record<string, any>,\n>(\n  liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,\n): InjectLiveQueryResultWithSingleResultCollection<TResult, TKey, TUtils>\nexport function injectLiveQuery(opts: any) {\n  assertInInjectionContext(injectLiveQuery)\n\n  let pendingWindow: (() => void) | undefined\n  let previousCollection: ReturnType<typeof resolveLiveQueryValue> = null\n  const resolveNext = (value: unknown, pool?: PooledLiveQueries) =>\n    (previousCollection = resolveLiveQueryValue(value, {\n      gcTime: DEFAULT_GC_TIME_MS,\n      pool,\n      previousCollection,\n      windowOwner: resolveNext,\n      onWindowChange: (move) => {\n        pendingWindow = move\n      },\n    }))\n  const resolveInput = () => {\n    // Check if it's an existing collection\n    if (isCollection(opts)) {\n      previousCollection = null\n      return opts\n    }\n\n    if (typeof opts === `function`) {\n      return resolveNext(opts)\n    }\n\n    // Handle LiveQueryCollectionConfig objects. Default startSync/gcTime to\n    // match the query-fn and reactive-options paths, but let an explicit value\n    // in the config win — otherwise a bare `{ query }` never syncs.\n    if (opts && typeof opts === `object` && typeof opts.query === `function`) {\n      if (typeof opts.params === `function`) {\n        // The pool is checked first, so a disabled query rejects it too.\n        const pool = configPool(opts)\n        return resolveNext(\n          (q: InitialQueryBuilder) => opts.query({ params: opts.params(), q }),\n          pool,\n        )\n      }\n      return resolveNext(opts)\n    }\n\n    throw new Error(`Invalid options provided to injectLiveQuery`)\n  }\n  const resolved = computed<{\n    collection: ReturnType<typeof resolveLiveQueryValue>\n    move: (() => void) | undefined\n  }>(() => {\n    pendingWindow = undefined\n    const collection = resolveInput()\n    return { collection, move: pendingWindow }\n  })\n  const collection = computed(() => resolved().collection)\n  effect(() => {\n    const { move } = resolved()\n    untracked(() => move?.())\n  })\n\n  // The shared observer already captures one coherent view per publication.\n  // Signals project that snapshot instead of copying its rows and health again.\n  const snapshot = signal<LiveQuerySnapshot<any, string | number> | null>(null)\n  const state = computed(\n    () => (snapshot()?.state ?? new Map()) as Map<string | number, any>,\n  )\n  const status = computed(() => {\n    const value = snapshot()?.status ?? `idle`\n    return value === `idle` && !collection() ? `disabled` : value\n  })\n  const health = computed(() => snapshot()?.health)\n  // Every status flag comes from the shared rule; a disabled query is ready.\n  const flags = computed(() =>\n    getLiveQueryStatusFlags(status() as CollectionStatus, health()),\n  )\n\n  // Between input resolution and observer attachment, the snapshot can belong\n  // to the previous query. Reapply the current query's projection to its rows.\n  const data = computed(() => {\n    // Read the current input even when a snapshot exists: a compile rejection\n    // must propagate instead of exposing the previous query's rows.\n    const currentCollection = collection()\n    const currentSnapshot = snapshot()\n    if (\n      currentSnapshot &&\n      currentSnapshot.collection === getPublicCollection(currentCollection)\n    )\n      return currentSnapshot.data\n    // Public pooled Collections materialize when their properties are read.\n    // The captured keyed rows let us reproject without inspecting that facade.\n    const rows = Array.from(currentSnapshot?.state?.values() ?? [])\n    return currentCollection && isSingleResultCollection(currentCollection)\n      ? rows[0]\n      : rows\n  })\n\n  // The effect owns this observer through reruns and injector destruction.\n  effect((onCleanup) => {\n    const currentCollection = collection()\n\n    // Handle null collection (disabled query)\n    if (!currentCollection) {\n      snapshot.set(null)\n      return\n    }\n\n    // Wholesale mode preserves Angular's loading policy: attaching requests no\n    // initial-state snapshot from the source.\n    const observer = createLiveQueryObserver(currentCollection, {\n      mode: `wholesale`,\n    })\n\n    const syncSnapshot = () => snapshot.set(observer.getSnapshot())\n    observer.subscribe(syncSnapshot)\n    // Wholesale attach suppresses listener calls raised by synchronous sync\n    // startup. Read once after subscribe returns to capture that final state.\n    syncSnapshot()\n    onCleanup(() => observer.dispose())\n  })\n\n  return {\n    state,\n    data,\n    // Loosely typed so the impl return stays compatible with every overload\n    // (the shared `isCollection` guard narrows the computed to `Collection | null`).\n    collection: computed(() =>\n      getPublicCollection(collection()),\n    ) as Signal<any>,\n    status,\n    isLoading: computed(() => flags().isLoading),\n    isReady: computed(() => flags().isReady || status() === `disabled`),\n    isIdle: computed(() => flags().isIdle),\n    isLoadingError: computed(() => flags().isLoadingError),\n    isCrashed: computed(() => flags().isCrashed),\n    isCleanedUp: computed(() => flags().isCleanedUp),\n    isSyncError: computed(() => flags().isSyncError),\n    health,\n  }\n}\n"],"mappings":";;;;AAiCA,IAAM,qBAAqB;AAkH3B,SAAgB,gBAAgB,MAAW;CACzC,CAAA,GAAA,cAAA,yBAAA,CAAyB,eAAe;CAExC,IAAI;CACJ,IAAI,qBAA+D;CACnE,MAAM,eAAe,OAAgB,SAClC,sBAAA,GAAqBA,aAAAA,sBAAAA,CAAsB,OAAO;EACjD,QAAQ;EACR;EACA;EACA,aAAa;EACb,iBAAiB,SAAS;GACxB,gBAAgB;EAClB;CACF,CAAC;CACH,MAAM,qBAAqB;EAEzB,KAAA,GAAIC,aAAAA,aAAAA,CAAa,IAAI,GAAG;GACtB,qBAAqB;GACrB,OAAO;EACT;EAEA,IAAI,OAAO,SAAS,YAClB,OAAO,YAAY,IAAI;EAMzB,IAAI,QAAQ,OAAO,SAAS,YAAY,OAAO,KAAK,UAAU,YAAY;GACxE,IAAI,OAAO,KAAK,WAAW,YAAY;IAErC,MAAM,QAAA,GAAOC,aAAAA,WAAAA,CAAW,IAAI;IAC5B,OAAO,aACJ,MAA2B,KAAK,MAAM;KAAE,QAAQ,KAAK,OAAO;KAAG;IAAE,CAAC,GACnE,IACF;GACF;GACA,OAAO,YAAY,IAAI;EACzB;EAEA,MAAM,IAAI,MAAM,6CAA6C;CAC/D;CACA,MAAM,YAAA,GAAWC,cAAAA,SAAAA,OAGR;EACP,gBAAgB,KAAA;EAEhB,OAAO;GAAE,YADU,aACV;GAAY,MAAM;EAAc;CAC3C,CAAC;CACD,MAAM,cAAA,GAAaA,cAAAA,SAAAA,OAAe,SAAS,CAAC,CAAC,UAAU;CACvD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