import { type AbstractType } from "@dao-xyz/borsh"; import type { PeerId, TypedEventTarget } from "@libp2p/interface"; import type { Multiaddr } from "@multiformats/multiaddr"; import { type MaybePromise, PublicSignKey } from "@peerbit/crypto"; import { type DiagnosticSink } from "@peerbit/diagnostics"; import * as types from "@peerbit/document-interface"; import { type QueryCacheOptions } from "@peerbit/indexer-cache"; import * as indexerTypes from "@peerbit/indexer-interface"; import { type Encoding, Entry } from "@peerbit/log"; import { Program } from "@peerbit/program"; import { RPC, type RPCRequestAllOptions } from "@peerbit/rpc"; import { type CoverRange, type ReplicationDomain, SharedLog } from "@peerbit/shared-log"; import { type PeerRefs } from "@peerbit/stream-interface"; import type { DocumentEvents, DocumentsChange } from "./events.js"; import type { QueryPredictor } from "./most-common-query-predictor.js"; import { type Operation } from "./operation.js"; import { Prefetch } from "./prefetch.js"; import type { ExtractArgs } from "./program.js"; import { type DocumentTransformFacts, type DocumentTransformer } from "./transform.js"; export type UpdateMergeStrategy> = boolean | { filter?: (evt: DocumentsChange) => MaybePromise | void>; }; export type UpdateReason = "initial" | "manual" | "join" | "change" | "push"; export type UpdateCallbacks> = { /** * Fires whenever the iterator detects new work (e.g. push, join, change). * Ideal for reactive consumers that need to call `next()` or trigger UI work. */ notify?: (reason: UpdateReason) => void | Promise; /** * Fires whenever the iterator yields a batch to the consumer. * Good for external sync (e.g. React state). */ onBatch?: (batch: RT[], meta: { reason: UpdateReason; }) => void | Promise; }; /** * Unified update options for iterate()/search()/get() and hooks. * If you pass `true`, defaults to `{ merge: "sorted" }`. */ export type UpdateModeShortcut = "local" | "remote" | "all"; export type UpdateOptions = boolean | UpdateModeShortcut | ({ /** Live update behavior. Only sorted merging is supported; optional filter can mutate/ignore events. */ merge?: UpdateMergeStrategy; /** Request push-style notifications backed by the prefetch channel. */ push?: boolean | types.PushUpdatesMode; } & UpdateCallbacks); export type JoiningTargets = { /** Specific peers you care about */ peers?: Array; /** Multiaddrs you care about */ multiaddrs?: (string | Multiaddr)[]; /** * From the previous cover set (what you "knew" about earlier). * - "any": wait until at least 1 of the known peers is ready * - "all": wait until all known peers are ready * - number: wait until N known peers are ready */ known?: "any" | "all" | number; }; export type JoiningTimeoutPolicy = "proceed" | "error"; export type JoiningOnMissedResults = (evt: { /** How many items should have preceded the current frontier. */ amount: number; /** The peer whose arrival triggered the gap calculation. */ peer: PublicSignKey; }) => void | Promise; export type OutOfOrderMode = "drop" | "queue"; export type LateResultsItem = { indexed: WithContext; context: types.Context; from: PublicSignKey; value?: any; }; export type LateResultsEvent = { /** Count of items that should have appeared earlier than the current frontier */ amount: number; /** If attributable, the peer that produced the late items */ peer?: PublicSignKey; } & (M extends "queue" ? { items: Item[]; } : { items?: undefined; }); export type LateResultsHelpers = { /** Collect concrete late items if available for the chosen mode */ collect: () => Promise; }; export type WaitBehavior = "block" | "keep-open"; export type WaitPolicy = { timeout: number; until?: "any"; onTimeout?: "proceed" | "error"; behavior?: WaitBehavior; }; export type ReachScope = { /** who to consider for readiness */ eager?: boolean; discover?: PublicSignKey[]; }; export type RemoteQueryOptions = RPCRequestAllOptions & { replicate?: boolean; from?: string[]; minAge?: number; /** * Reject missing responses, query-level denials and page-processing errors. * A replicator outside `from` or `reach.discover` that a join adds is still * asked, best-effort. */ throwOnMissing?: boolean; retryMissingResponses?: boolean; strategy?: "fallback"; domain?: { args: ExtractArgs; } | { range: CoverRange; }; /** WHO can answer? How do we grow the candidate set? */ reach?: ReachScope; /** WHEN are we allowed to proceed? Quorum semantics over a chosen group. */ wait?: WaitPolicy; }; export type QueryOptions = { remote?: boolean | RemoteQueryOptions; local?: boolean; resolve?: Resolve; signal?: AbortSignal; updates?: UpdateOptions; outOfOrder?: { mode?: "drop"; handle?: (evt: LateResultsEvent<"drop">, helpers: LateResultsHelpers<"drop">) => void | Promise; } | { mode: "queue"; handle?: (evt: LateResultsEvent<"queue">, helpers: LateResultsHelpers<"queue">) => void | Promise; }; /** * Controls iterator liveness after batches are consumed. * - 'onEmpty' (default): close when no more results * - 'manual': keep open until iterator.close() or program close; good for live updates */ closePolicy?: "onEmpty" | "manual"; }; export type GetOptions<_T, _I, D, Resolve extends boolean | undefined> = { remote?: boolean | RemoteQueryOptions; local?: boolean; resolve?: Resolve; signal?: AbortSignal; waitFor?: number; }; export type SearchOptions = QueryOptions; type Transformer = (obj: T, context: types.Context, facts?: DocumentTransformFacts) => MaybePromise; export type ResultsIterator = { close: () => Promise; next: (number: number) => Promise; done: () => boolean; all: () => Promise; pending: () => MaybePromise; first: () => Promise; [Symbol.asyncIterator]: () => AsyncIterator; }; type QueryLike = { query?: indexerTypes.Query[] | indexerTypes.QueryLike; sort?: indexerTypes.Sort[] | indexerTypes.Sort | indexerTypes.SortLike; }; type ExtractResolveFromOptions = O extends QueryOptions ? X extends boolean ? X : true : true; /** * A query-level denial (`NoAccess`) from a remote responder, raised when * `remote.throwOnMissing` is true. `peers` holds the first denying responder * processed, not necessarily every peer that denied. */ export declare class AccessDeniedError extends Error { readonly peers: string[]; constructor(peers: string[]); } export type CanSearch = (request: types.SearchRequest | types.SearchRequestIndexed | types.IterationRequest | types.CollectNextRequest, from: PublicSignKey) => Promise | boolean; export type CanRead = (result: T, from: PublicSignKey) => Promise | boolean; export type CanReadIndexed = (result: I, from: PublicSignKey) => Promise | boolean; export type WithContext = { __context: types.Context; } & I; export type DocumentIndexWriteSession> = indexerTypes.OrderedIndexWriteSession>; export declare const INDEX_CONTEXT_SHAPE: { readonly __context: { readonly created: true; readonly modified: true; readonly head: true; readonly gid: true; readonly size: true; }; }; export type IndexedContextOnly> = indexerTypes.ReturnTypeFromShape, typeof INDEX_CONTEXT_SHAPE>; export type WithIndexed = { __indexed: I; } & T; export type WithIndexedContext = WithContext>; export type ValueTypeFromRequest = Resolve extends false ? WithContext : WithIndexedContext; export type TransformerAsConstructor = { type?: new (arg: T, context: types.Context) => I; }; export type TransformerAsFunction = { type: AbstractType; transform: DocumentTransformer; }; export type TransformOptions = TransformerAsConstructor | TransformerAsFunction; export type PrefetchOptions = { predictor?: QueryPredictor; ttl: number; accumulator: Prefetch; strict?: boolean; }; export type OpenOptions> = { documentEvents: TypedEventTarget>; documentType: AbstractType; dbType: AbstractType>; log: SharedLog; canRead?: CanRead; canSearch?: CanSearch; replicate: (request: types.SearchRequest | types.SearchRequestIndexed | types.IterationRequest, results: types.Results>) => Promise; indexBy?: string | string[]; transform?: TransformOptions; cache?: { resolver?: number; query?: QueryCacheOptions; }; maybeOpen: (value: T & Program) => Promise; prefetch?: boolean | Partial; includeIndexed?: boolean; immutable?: boolean; /** Advisory query timing; no effect on coverage, authorization or deadlines. */ profile?: DiagnosticSink; }; type IndexableClass = new (value: I, context: types.Context) => WithContext; type ContextualPutOptions = { replace?: boolean; encodedValue?: Uint8Array; encodedValueParts?: { prefix: Uint8Array; suffix: Uint8Array; }; transformFacts?: DocumentTransformFacts; }; export declare const encodeContextSuffix: (context: types.Context) => Uint8Array; export declare const coerceWithContext: (value: T | WithContext, context: types.Context) => WithContext; export declare const coerceWithIndexed: (value: T | WithIndexed, indexed: I) => WithIndexed; export declare const coerceWithLazyIndexed: (value: T | WithIndexedContext, getIndexable: () => I) => WithIndexedContext; export declare class DocumentIndex, D extends ReplicationDomain> extends Program> { _query: RPC; documentType: AbstractType; transformer: Transformer; private transformerIsIdentity; private detachTransformerFacts; private nativeTransformDescriptor?; private nativeTransformProjectionPlan?; private nativeBackboneDocumentProjection?; wrappedIndexedType: IndexableClass; indexedType: AbstractType; dbType: AbstractType>; indexedTypeIsDocumentType: boolean; private indexBy; private indexByResolver; index: indexerTypes.Index>; private _resumableIterators; private _prefetch?; private includeIndexed; private immutable; private _valueEncoding; private _sync; private _log; private _queryProfile?; private _resolverProgramCache?; private _resolverCache?; private isProgramValued; private _maybeOpen; private canSearch?; private canRead?; private documentEvents; private _joinListener?; private _resultQueue; private iteratorKeepAliveTimers?; private deleteResolvedCacheForKey; constructor(properties?: { query?: RPC; }); get valueEncoding(): Encoding; canUseOrderedWriteSession(): boolean; withOrderedWriteSession(operation: (session: DocumentIndexWriteSession) => MaybePromise): Promise; private ensurePrefetchAccumulator; /** * Resolve documents without bypassing the resolver/program caches. Cache and * identity-index hits are collected first; only the remaining heads cross the * log read boundary, and those reads stay aligned in one batch. */ private resolveDocumentsWithBatchedHeads; /** * Return a head that the local document-interface Entry schema can encode. * Consumers can install the same @peerbit/log version at more than one * physical path, giving its Entry class more than one runtime identity. * Rehydrate only foreign or hollow entries through this log's block store; * the normal colocated path preserves the existing Entry object. */ private getSerializableHead; private wrapPushResults; private drainQueuedResults; private handleDocumentChange?; private onDocumentChange; private get nestedProperties(); open(properties: OpenOptions): Promise; private attachNativeBackboneDocumentIndex; private canUseNativeBackboneDocumentIndex; private getNativeDocumentFieldExtractionPlan; private canPrepareNativeBackboneDocumentIndexCommit; private canPrepareNativeBackboneDocumentIndexCommitWithAppendFacts; private canUseNativeBackboneContextualBatch; private transformWithDetachedFacts; private prepareNativeBackboneDocumentIndexCommit; private prepareNativeBackboneDocumentIndexCommitWithAppendFacts; private prepareNativeBackboneDocumentIndexStoredCommitWithAppendFacts; private nativeBackboneDocumentIndexValuePrefixBytes; private asIndexedTypeValue; get prefetch(): PrefetchOptions | undefined; private queryRPCResponseHandler; private handleSearchRequest; afterOpen(): Promise; getPending(cursorId: string): Promise; get hasPending(): boolean; private releaseClosedResolverCache; close(from?: Program): Promise; drop(from?: Program): Promise; get>(key: indexerTypes.Ideable | indexerTypes.IdKey, options?: Options): Promise>; get>(key: indexerTypes.Ideable | indexerTypes.IdKey, options?: Options): Promise>; getFromGid(gid: string): Promise>>; getFromHash(hash: string): Promise>>; getIdentityIndexedByHead(head: string): Promise> | undefined>; getIdentityIndexedKeyByHead(head: string): Promise; private getIndexedKeyByHead; getIndexedKeysByHeads(heads: string[]): Array | undefined; tryGetIdentityIndexedKeyByHead(head: string): { supported: boolean; key?: indexerTypes.IdKey; }; getIdentityIndexedByHeads(heads: string[]): Promise> | undefined> | undefined>; canGetIdentityIndexedByHead(): boolean; canGetIndexedKeyByHead(): boolean; canReadOriginalFieldPathsFromIndexedValue(paths: readonly (string | readonly string[])[]): boolean; canReadNativeIndexedFieldValues(paths: readonly (string | readonly string[])[]): boolean; getNativeIndexedFieldValue(id: indexerTypes.IdKey, path: string | readonly string[]): unknown; _putIdentityWithContext(value: T, id: indexerTypes.IdKey, context: types.Context, options?: ContextualPutOptions): MaybePromise | undefined>; _putStoredIdentityWithContext(value: T, id: indexerTypes.IdKey, context: types.Context, encodedValueParts: NonNullable, options?: { replace?: boolean; }): MaybePromise | undefined>; private _putPreparedNativeBackboneDocumentIndexWithContext; private _putPreparedNativeBackboneDocumentIndexStoredWithContext; private _persistPreparedNativeBackboneDocumentIndexStoredWithContext; private _putManyPreparedNativeBackboneDocumentIndexWithContext; private _putManyPreparedNativeBackboneDocumentIndexStored; _putManyIdentityWithContext(values: Array<{ value: T; id: indexerTypes.IdKey; context: types.Context; options?: ContextualPutOptions; }>): Promise[] | undefined>; put(value: T, id: indexerTypes.IdKey, entry: Entry, existing: indexerTypes.IndexedResult> | indexerTypes.IndexedResult> | null | undefined, orderedSession?: DocumentIndexWriteSession): Promise<{ context: types.Context; indexable: I; }>; putWithContext(value: T, id: indexerTypes.IdKey, context: types.Context, options?: ContextualPutOptions, orderedSession?: DocumentIndexWriteSession): Promise<{ context: types.Context; indexable: I; }>; putManyWithContext(values: Array<{ value: T; id: indexerTypes.IdKey; context: types.Context; options?: ContextualPutOptions; }>): Promise>; _cacheResolvedIdentityValue(id: string | number | bigint, value: T): void; private cacheResolvedValue; private withContextualEncodedValue; private encodeContextualIndexedValueParts; del(key: indexerTypes.IdKey): indexerTypes.IdKey[] | Promise; /** * Remove `key`'s row only while its `__context.head` is `head`. * * The head check and the removal are one indexer call, so a version indexed * after the caller read `head` is never removed. An index that keeps native * document contexts checks the head where it removes the row; any other index * runs one delete that matches both the id and the head. Engines must evaluate * every predicate of a delete at the moment they remove the row. * * @returns whether a row was removed. */ delIfHead(key: indexerTypes.IdKey, head: string): Promise; private removeIfHead; /** * The removal counterpart of `putWithContext`'s guard. Once this index is * closed there is nothing left to remove from, so a `NotStartedError` marks * the teardown window rather than a failure. * * This exists because the guard used to be one-legged: the read leg * (`Documents.getLocalIndexedContextForChange`) tolerated a closed index while * the remove leg did not, so a DELETE-carrying change still threw out of a * join in exactly the window the read guard was written for. A guard that * covers one direction of the same operation is worse than none, because it * reads as covered. * * Narrow in the same way as the read leg: only `NotStartedError`, and only * once this index is actually closed. An indexer that breaks while open still * throws. */ private recoverClosedRemoval; delMany(keys: indexerTypes.IdKey[]): Promise; clearResolvedCacheForKeys(keys: indexerTypes.IdKey[]): void; delManyMaybe(keys: indexerTypes.IdKey[]): MaybePromise; getDetailed, Resolve extends boolean | undefined = ExtractResolveFromOptions, RT extends types.Result = Resolve extends true ? types.ResultValue> : types.ResultIndexedValue>>(key: indexerTypes.IdKey | indexerTypes.IdPrimitive, options?: QueryOptions): Promise[] | undefined>; getSize(): Promise | number; private resolveDocument; processQuery(query: R, from: PublicSignKey, isLocal: boolean, options?: { canRead?: CanRead; }): Promise>>; private scheduleIteratorKeepAlive; private cancelIteratorKeepAlive; private clearResultsQueue; get countIteratorsInProgress(): number; private clearAllResultQueues; private waitForCoverReady; private createReplicatorJoinListener; processCloseIteratorRequest(query: types.CloseIteratorRequest, publicKey: PublicSignKey): void; /** * Query and retrieve results with most details * @param queryRequest * @param options * @returns */ private queryCommence; private queryCommenceWithProfile; search(queryRequest: QueryLike, options?: SearchOptions): Promise[]>; search(queryRequest: QueryLike, options?: SearchOptions): Promise[]>; private resolveIndexed; iterate(query?: QueryLike, options?: QueryOptions): ResultsIterator>; iterate(query?: QueryLike, options?: QueryOptions): ResultsIterator>; updateResults(into: WithContext[], change: { added?: WithContext[] | WithContext[]; removed?: WithContext[] | WithContext[]; }, query: QueryLike, resolve: R): Promise[]>; /** * Resolve the primary key for a document or indexed representation using the configured indexBy fields. * Useful when consumers need a stable id without assuming a specific property name exists. */ resolveId(value: ValueTypeFromRequest | WithContext | WithIndexedContext | WithIndexed | I): indexerTypes.IdKey; waitFor(other: PeerRefs, options?: { seek?: "any" | "present"; signal?: AbortSignal; timeout?: number; }): Promise; } export {}; //# sourceMappingURL=search.d.ts.map