import { AbortablePromise, EngineError, EngineErrorCode, wirePack, type DocumentSearchService, type SearchRequest, type SearchSlice, } from '@embedpdf/engine-core/runtime'; import type { ScopeGuard } from '../scope'; import type { JobId, WorkerResultPayload } from '../worker/protocol'; import type { JobQueue } from '../worker/WorkerQueue'; interface DocClosedView { isClosed(): boolean; } /** * Document-scoped search service. A search gates on `doc.text.search`; * `snippets: true` additionally needs `doc.text.copy` — a snippet is * extracted text, so the copy denial must * hold here too (cloud parity: the server's search route enforces the * same pair). The worker fans out to `SearchReader`, which serves page * text from the session's version-keyed corpus cache. */ export class LocalDocumentSearchService implements DocumentSearchService { constructor( private readonly docId: string, private readonly queue: JobQueue, private readonly view: DocClosedView, private readonly guard: ScopeGuard, ) {} query(request: SearchRequest): AbortablePromise { if (this.view.isClosed()) { return AbortablePromise.rejectReason( new EngineError(EngineErrorCode.DocNotOpen, `document not open: ${this.docId}`), ); } try { this.guard.assertCapability('doc.text.search'); if (request.snippets) { this.guard.assertCapability('doc.text.copy'); } } catch (err) { return AbortablePromise.rejectReason(err); } const docId = this.docId; const submission = this.queue.enqueue( { buildPack: (jobId: JobId) => wirePack({ kind: 'search.query', effect: 'read', jobId, docId, request }), }, // Search runs behind interactive work (renders, edits): a slice is // bounded but not small, and the next one can always wait a beat. ); return AbortablePromise.run(async (signal) => { const onAbort = () => submission.abort(signal.reason); if (signal.aborted) onAbort(); else signal.addEventListener('abort', onAbort, { once: true }); const payload = await submission; if (payload.tag !== 'search.query') { throw new EngineError(EngineErrorCode.WireFormat, `unexpected payload tag: ${payload.tag}`); } return payload.slice; }); } }