import type { ConformanceTestRunner, ConformanceFixture, ConformanceOptions, } from './runMetadataConformance'; import type { Engine } from '../engine/Engine'; import { EngineError } from '../errors/EngineError'; import { EngineErrorCode } from '../errors/EngineErrorCode'; import { toPageRef } from '../identity/PageRef'; import { AbortError } from '../promise/AbortError'; import { foldText } from '../search/fold'; import type { SearchMatch, SearchSlice } from '../search/types'; import { SearchSliceSchema } from '../wire/schemas'; import { EVERY_PERMISSION } from './fixtureScope'; /** * Per-fixture expectations for the search harness. Suites supply a * literal known to be on a specific page, one known to be nowhere, and a * regex with a predictable hit — the harness asserts behavior (offsets, * rects, snippets, cursor mechanics, dialect rejection), never exact * match counts, so PDFium text-extraction tweaks don't require edits. */ export interface SearchConformanceFixture extends ConformanceFixture { /** Literal present in the document at least once. */ presentLiteral: string; /** A page (pon) guaranteed to carry a `presentLiteral` match. */ presentPageObjectNumber: number; /** Literal guaranteed to match nowhere. */ absentLiteral: string; /** Dialect-valid regex with at least one match in the document. */ presentRegex: string; } export interface SearchConformanceOptions extends Omit { fixture: SearchConformanceFixture; } export function runSearchConformance( runner: ConformanceTestRunner, options: SearchConformanceOptions, ): void { const { describe, test, beforeAll, afterAll, expect } = runner; const fixture = options.fixture; /** Drive the cursor loop to exhaustion; assert each slice parses. */ async function collectAll( doc: Awaited>, request: Parameters[0], ): Promise<{ matches: SearchMatch[]; slices: SearchSlice[] }> { const matches: SearchMatch[] = []; const slices: SearchSlice[] = []; let cursor: string | undefined; for (;;) { const slice = await doc.search.query({ ...request, cursor }); expect(SearchSliceSchema.safeParse(slice).success).toBe(true); matches.push(...slice.matches); slices.push(slice); if (slice.nextCursor === null) return { matches, slices }; cursor = slice.nextCursor; } } describe(`search conformance: ${options.label}`, () => { let engine: Engine; beforeAll(async () => { engine = await options.makeEngine(); }); afterAll(async () => { if (engine) await engine.destroy(); }); test('finds the present literal with sane matches', async () => { const doc = await openFixture(engine, options); try { const { matches } = await collectAll(doc, { text: fixture.presentLiteral, }); expect(matches.length > 0).toBe(true); expect(matches.some((m) => m.page.objectNumber === fixture.presentPageObjectNumber)).toBe( true, ); for (const m of matches) { expect(m.count > 0).toBe(true); expect(m.segments.length > 0).toBe(true); for (const s of m.segments) { expect(s.rect.width > 0).toBe(true); expect(s.rect.height > 0).toBe(true); // The pair is one constructor's output — enforce it stayed that way. const xs = [ s.quad.upperLeft.x, s.quad.upperRight.x, s.quad.lowerLeft.x, s.quad.lowerRight.x, ]; const ys = [ s.quad.upperLeft.y, s.quad.upperRight.y, s.quad.lowerLeft.y, s.quad.lowerRight.y, ]; expect(Math.abs(s.rect.x - Math.min(...xs)) < 1e-3).toBe(true); expect(Math.abs(s.rect.x + s.rect.width - Math.max(...xs)) < 1e-3).toBe(true); expect(Math.abs(s.rect.y - Math.min(...ys)) < 1e-3).toBe(true); expect(Math.abs(s.rect.y + s.rect.height - Math.max(...ys)) < 1e-3).toBe(true); expect(s.advance === 1 || s.advance === -1).toBe(true); } } } finally { await doc.close(); } }); test('matching is case-insensitive by default', async () => { const doc = await openFixture(engine, options); try { const lower = await collectAll(doc, { text: fixture.presentLiteral.toLowerCase(), }); const upper = await collectAll(doc, { text: fixture.presentLiteral.toUpperCase(), }); expect(lower.matches.length).toBe(upper.matches.length); expect(lower.matches.length > 0).toBe(true); } finally { await doc.close(); } }); test('snippets carry the matched text; without them a match has none', async () => { const doc = await openFixture(engine, options); try { const withSnippets = await collectAll(doc, { text: fixture.presentLiteral, snippets: true, }); for (const m of withSnippets.matches) { expect(!!m.snippet).toBe(true); const s = m.snippet!; const hit = s.match; // Fold both sides: the snippet keeps the page's original case // and (flattened) whitespace. expect(foldText(hit).folded).toBe(foldText(fixture.presentLiteral).folded); } const plain = await collectAll(doc, { text: fixture.presentLiteral, }); expect(plain.matches.length).toBe(withSnippets.matches.length); for (const m of plain.matches) expect(m.snippet === undefined).toBe(true); } finally { await doc.close(); } }); test('the absent literal exhausts with zero matches', async () => { const doc = await openFixture(engine, options); try { const { matches, slices } = await collectAll(doc, { text: fixture.absentLiteral, }); expect(matches.length).toBe(0); const last = slices[slices.length - 1]; expect(last.nextCursor).toBe(null); expect(last.pageCount > 0).toBe(true); } finally { await doc.close(); } }); test('a one-page limit walks the whole document via the cursor', async () => { const doc = await openFixture(engine, options); try { const whole = await collectAll(doc, { text: fixture.presentLiteral, }); const sliced = await collectAll(doc, { text: fixture.presentLiteral, limit: { pages: 1 }, }); expect(sliced.matches.length).toBe(whole.matches.length); const last = sliced.slices[sliced.slices.length - 1]; expect(last.pagesSearched).toBe(last.pageCount); expect(sliced.slices.length).toBe(last.pageCount); } finally { await doc.close(); } }); test('from rotates the scan order (viewport-first)', async () => { const doc = await openFixture(engine, options); try { const slice = await doc.search.query({ text: fixture.presentLiteral, from: toPageRef(fixture.presentPageObjectNumber), limit: { pages: 1 }, }); expect(slice.matches.length > 0).toBe(true); expect(slice.matches[0].page.objectNumber).toBe(fixture.presentPageObjectNumber); } finally { await doc.close(); } }); test('a cursor replayed against a different query is rejected', async () => { const doc = await openFixture(engine, options); try { const first = await doc.search.query({ text: fixture.presentLiteral, limit: { pages: 1 }, }); expect(first.nextCursor !== null).toBe(true); let caught: unknown; try { await doc.search.query({ text: fixture.absentLiteral, cursor: first.nextCursor!, }); } catch (err) { caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally { await doc.close(); } }); test('a malformed cursor is rejected', async () => { const doc = await openFixture(engine, options); try { let caught: unknown; try { await doc.search.query({ text: fixture.presentLiteral, cursor: 'not a cursor', }); } catch (err) { caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } finally { await doc.close(); } }); test('regex queries match with offsets and rects', async () => { const doc = await openFixture(engine, options); try { const { matches } = await collectAll(doc, { text: fixture.presentRegex, regex: true, }); expect(matches.length > 0).toBe(true); for (const m of matches) { expect(m.count > 0).toBe(true); expect(m.segments.length > 0).toBe(true); } } finally { await doc.close(); } }); test('regex flags are restrictions: matchCase and wholeWord return subsets', async () => { const doc = await openFixture(engine, options); try { const all = await collectAll(doc, { text: fixture.presentRegex, regex: true, }); const key = (m: SearchMatch) => `${m.page.objectNumber}:${m.start}:${m.count}`; const allKeys = new Set(all.matches.map(key)); // Each flag can only remove matches, never invent them — true for // any fixture pattern, so the suite needs no per-fixture counts. for (const flags of [{ matchCase: true }, { wholeWord: true }]) { const restricted = await collectAll(doc, { text: fixture.presentRegex, regex: true, ...flags, }); expect(restricted.matches.length <= all.matches.length).toBe(true); for (const m of restricted.matches) expect(allKeys.has(key(m))).toBe(true); } } finally { await doc.close(); } }); test('ignoreWhitespace keeps every default hit and finds the space-free needle', async () => { const doc = await openFixture(engine, options); try { const key = (m: SearchMatch) => `${m.page.objectNumber}:${m.start}:${m.count}`; const plain = await collectAll(doc, { text: fixture.presentLiteral }); // Dropping whitespace can only add matches over the collapsing default // fold — every default hit survives, at the same place. const relaxed = await collectAll(doc, { text: fixture.presentLiteral, ignoreWhitespace: true, }); const relaxedKeys = new Set(relaxed.matches.map(key)); for (const m of plain.matches) expect(relaxedKeys.has(key(m))).toBe(true); // ...and the needle no longer needs the page's spaces. const squashed = await collectAll(doc, { text: fixture.presentLiteral.replace(/\s+/g, ''), ignoreWhitespace: true, }); expect(squashed.matches.map(key)).toEqual(relaxed.matches.map(key)); } finally { await doc.close(); } }); test('regex + matchDiacritics / ignoreWhitespace are rejected with InvalidArg', async () => { const doc = await openFixture(engine, options); try { for (const flags of [{ matchDiacritics: true }, { ignoreWhitespace: true }]) { let caught: unknown; try { await doc.search.query({ text: fixture.presentRegex, regex: true, ...flags, }); } catch (err) { caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } } finally { await doc.close(); } }); test('dialect violations are rejected with InvalidArg', async () => { const doc = await openFixture(engine, options); try { for (const pattern of ['(a)\\1', '(?=x)y', '(']) { let caught: unknown; try { await doc.search.query({ text: pattern, regex: true }); } catch (err) { caught = err; } expect(EngineError.is(caught, EngineErrorCode.InvalidArg)).toBe(true); } } finally { await doc.close(); } }); test('an empty needle returns an exhausted, empty slice', async () => { const doc = await openFixture(engine, options); try { const slice = await doc.search.query({ text: ' ' }); expect(slice.matches.length).toBe(0); expect(slice.nextCursor).toBe(null); } finally { await doc.close(); } }); test('abort() on query rejects with AbortError', async () => { const doc = await openFixture(engine, options); try { const p = doc.search.query({ text: fixture.presentLiteral }); p.abort('test'); await expect(p).rejects.toBeInstanceOf(AbortError); } finally { await doc.close(); } }); test('query after close throws DocNotOpen', async () => { const doc = await openFixture(engine, options); await doc.close(); let caught: unknown; try { await doc.search.query({ text: fixture.presentLiteral }); } catch (err) { caught = err; } expect(EngineError.is(caught, EngineErrorCode.DocNotOpen)).toBe(true); }); }); } async function openFixture(engine: Engine, opts: SearchConformanceOptions) { if (opts.openKind === 'bytes') { const bytes = await opts.fixture.bytes(); return engine.open({ kind: 'bytes', id: opts.fixture.id, bytes }, EVERY_PERMISSION); } return engine.open({ kind: 'id', id: opts.fixture.cloudId ?? opts.fixture.id }); }