import { describe, expect, test } from 'bun:test'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import type { ParserOptions } from 'prettier'; import * as markdownPlugin from 'prettier/plugins/markdown'; import { DEFAULT_FIELD_SHAPE_LIMIT, DEFAULT_MAX_EXAMPLE_LENGTH, DEFAULT_MAX_EXAMPLES, FIELD_SHAPE_PROBE_COLLECTIONS, FIELD_VALUE_TYPES, MAX_EXAMPLE_LENGTH_CAP, MAX_EXAMPLES_CAP, MAX_FIELD_SHAPE_LIMIT, parseProbeSourceFieldShapesArgs, readFieldShapes, renderFieldShapesMarkdown, runSourceFieldShapesProbe, STRING_PATTERN_CLASSES, summarizeFieldShapes, UnknownProbeCollectionError, type FieldShapeSummary, type ReadOnlyMongoCollectionClient, type ReadOnlySourceSymbolCursor, type ReadOnlySourceSymbolReader, type SourceSymbolFindOptions, } from '../src/security-master'; interface RecordedFindCall { collectionName: string; filter: Record | undefined; options: SourceSymbolFindOptions | undefined; } interface FakeBsonWrapper { _bsontype: string; valueOf?: () => unknown; toString: () => string; } function fakeInt32(value: number): FakeBsonWrapper { return { _bsontype: 'Int32', valueOf: () => value, toString: () => String(value), }; } function fakeDouble(value: number): FakeBsonWrapper { return { _bsontype: 'Double', valueOf: () => value, toString: () => String(value), }; } function fakeLong(value: string): FakeBsonWrapper { return { _bsontype: 'Long', toString: () => value, }; } function fakeObjectId(hex: string): FakeBsonWrapper { return { _bsontype: 'ObjectId', toString: () => hex, }; } function fakeDecimal128(value: string): FakeBsonWrapper { return { _bsontype: 'Decimal128', toString: () => value, }; } function sumTypeCounts(summary: FieldShapeSummary): number { let total = 0; for (const typeName of FIELD_VALUE_TYPES) { total += summary.typeCounts[typeName]; } return total; } function sumPatternCounts(summary: FieldShapeSummary): number { if (summary.stringStats === null) { return 0; } let total = 0; for (const pattern of STRING_PATTERN_CLASSES) { total += summary.stringStats.patterns[pattern]; } return total; } function createFakeReader( docsByCollection: Record[]>, opts?: { readOnly?: boolean; failFindOnCollection?: string; failIterOnCollection?: string; failIterAtIndex?: number; failCloseOnCollection?: string; returnBufferedArrayOnCollection?: string; ignoreLimit?: boolean; } ): { reader: ReadOnlySourceSymbolReader; calls: RecordedFindCall[]; closedCollections: string[]; pullsByCollection: Record; } { const calls: RecordedFindCall[] = []; const closedCollections: string[] = []; const pullsByCollection: Record = {}; const readOnly = opts?.readOnly ?? true; const reader: ReadOnlySourceSymbolReader = { isReadOnly(): boolean { return readOnly; }, find = Record>( collectionName: string, filter?: Record, options?: SourceSymbolFindOptions ): ReadOnlySourceSymbolCursor { calls.push({ collectionName, filter, options }); if (opts?.failFindOnCollection === collectionName) { throw new Error('simulated find failure'); } if (opts?.returnBufferedArrayOnCollection === collectionName) { return [...(docsByCollection[collectionName] ?? [])] as unknown as ReadOnlySourceSymbolCursor; } const sourceDocs = docsByCollection[collectionName] ?? []; const maxToYield = opts?.ignoreLimit === true || options?.limit === undefined ? sourceDocs.length : Math.min(sourceDocs.length, options.limit); const failAt = opts?.failIterAtIndex ?? 1; return { async *[Symbol.asyncIterator](): AsyncIterator { for (let i = 0; i < maxToYield; i++) { pullsByCollection[collectionName] = (pullsByCollection[collectionName] ?? 0) + 1; if (opts?.failIterOnCollection === collectionName && i === failAt) { throw new Error('simulated cursor iteration failure'); } yield sourceDocs[i] as T; } }, async close(): Promise { closedCollections.push(collectionName); if (opts?.failCloseOnCollection === collectionName) { throw new Error('simulated cursor close failure'); } }, }; }, }; return { reader, calls, closedCollections, pullsByCollection }; } describe('source-field-shapes static purity', () => { test('source-field-shapes.ts has zero runtime DB, FS, or network imports', () => { const filePath = resolve(import.meta.dir, '../src/security-master/source-field-shapes.ts'); const source = readFileSync(filePath, 'utf8'); const runtimeImportLines = source .split('\n') .filter(line => /^\s*import\s+(?!type\b)/.test(line)); for (const line of runtimeImportLines) { expect(line).not.toMatch(/mongodb|postgres|node:fs|node:http|node:https|node:net|fetch/i); } expect(source).not.toMatch(/\bDate\.now\s*\(|\bnew Date\s*\(\s*\)/); }); }); describe('summarizeFieldShapes', () => { test('classifies mixed JS and BSON value types on one field and reconciles counts', () => { const docs: Record[] = [ { mixed: 'hello' }, { mixed: 42 }, { mixed: 3.14 }, { mixed: fakeInt32(7) }, { mixed: fakeLong('9007199254740993') }, { mixed: fakeDouble(1.0) }, { mixed: true }, { mixed: new Date('2025-01-15T12:00:00.000Z') }, { mixed: null }, { mixed: fakeObjectId('507f1f77bcf86cd799439011') }, { mixed: [1, 2, 3] }, { mixed: { nested: 'a' } }, { mixed: fakeDecimal128('12.34') }, { mixed: new Uint8Array([1, 2]) }, {}, // missing ]; const summary = summarizeFieldShapes(docs); expect(summary.docCount).toBe(docs.length); const mixed = summary.fields.find(f => f.field === 'mixed'); expect(mixed).toBeDefined(); expect(mixed!.presentCount).toBe(14); expect(mixed!.missingCount).toBe(1); expect(mixed!.presentCount + mixed!.missingCount).toBe(summary.docCount); expect(sumTypeCounts(mixed!)).toBe(mixed!.presentCount); expect(mixed!.typeCounts).toEqual({ string: 1, int: 3, // 42, Int32(7), Long(...) double: 2, // 3.14, Double(1.0) bool: 1, date: 1, null: 1, objectId: 1, array: 1, object: 1, other: 2, // Decimal128, Uint8Array }); }); test('tracks one level of nested parent.child keys and stops at depth 1', () => { const docs: Record[] = [ { meta: { exchange: 'TSX', deep: { level2: 'ignored' }, recordedAt: new Date('2025-02-01T00:00:00Z'), }, arr: [{ insideArray: 1 }], bsonObj: fakeObjectId('507f1f77bcf86cd799439012'), }, { meta: { exchange: 'NYSE', }, }, ]; const summary = summarizeFieldShapes(docs); const fieldNames = summary.fields.map(f => f.field); expect(fieldNames).toEqual([ 'arr', 'bsonObj', 'meta', 'meta.deep', 'meta.exchange', 'meta.recordedAt', ]); expect(fieldNames).not.toContain('meta.deep.level2'); expect(fieldNames).not.toContain('bsonObj._bsontype'); const metaExchange = summary.fields.find(f => f.field === 'meta.exchange')!; expect(metaExchange.presentCount).toBe(2); expect(metaExchange.missingCount).toBe(0); expect(metaExchange.typeCounts.string).toBe(2); const metaDeep = summary.fields.find(f => f.field === 'meta.deep')!; expect(metaDeep.presentCount).toBe(1); expect(metaDeep.missingCount).toBe(1); expect(metaDeep.typeCounts.object).toBe(1); }); test('keeps literal dotted top-level keys distinct from nested parent.child keys', () => { const docs: Record[] = [ { 'meta.exchange': 'LITERAL_EXCHANGE', meta: { exchange: 42, }, }, ]; const summary = summarizeFieldShapes(docs); expect(summary.docCount).toBe(1); const literalField = summary.fields.find(f => f.field === 'meta\\.exchange'); const nestedField = summary.fields.find(f => f.field === 'meta.exchange'); expect(literalField).toBeDefined(); expect(nestedField).toBeDefined(); expect(literalField!.presentCount).toBe(1); expect(literalField!.missingCount).toBe(0); expect(literalField!.typeCounts.string).toBe(1); expect(literalField!.typeCounts.int).toBe(0); expect(literalField!.examples).toEqual(['LITERAL_EXCHANGE']); expect(nestedField!.presentCount).toBe(1); expect(nestedField!.missingCount).toBe(0); expect(nestedField!.typeCounts.int).toBe(1); expect(nestedField!.typeCounts.string).toBe(0); expect(nestedField!.examples).toEqual(['42']); }); test('classifies all five string pattern classes and tracks min/max string length', () => { const docs: Record[] = [ { s: '2024-02-29' }, // valid leap-year ymd (len 10) { s: '2023-02-29' }, // invalid calendar date -> other (len 10) { s: '2025-05-01T14:30:00Z' }, // isoDatetime (len 20) { s: '2025-05-01T14:30:00.123-04:00' }, // isoDatetime (len 29) { s: '-123.45' }, // numeric (len 7) { s: '1.5e-4' }, // numeric (len 6) { s: '' }, // emptyOrWhitespace (len 0) { s: ' \t ' }, // emptyOrWhitespace (len 5) { s: 'AAPL.US' }, // other (len 7) ]; const summary = summarizeFieldShapes(docs); const field = summary.fields.find(f => f.field === 's')!; expect(field.typeCounts.string).toBe(9); expect(field.stringStats).toEqual({ minLength: 0, maxLength: 29, patterns: { ymd: 1, isoDatetime: 2, numeric: 2, emptyOrWhitespace: 2, other: 2, }, }); expect(sumPatternCounts(field)).toBe(field.typeCounts.string); }); test('truncates and caps examples, suppresses _id and _id.* examples, and validates bounds', () => { const docs: Record[] = [ { _id: fakeObjectId('507f1f77bcf86cd799439011'), symbol: 'ZZZZ', note: 'line1\nline2\twith a very long description that must be truncated', }, { _id: { key: 'secret-composite-id' }, symbol: 'AAAA', note: 'short', }, { _id: 'string-id-should-never-appear', symbol: 'MMMM', }, { symbol: 'BBBB', }, ]; const summary = summarizeFieldShapes(docs, { maxExamples: 2, maxExampleLength: 16 }); const idField = summary.fields.find(f => f.field === '_id')!; const idChildField = summary.fields.find(f => f.field === '_id.key')!; const symbolField = summary.fields.find(f => f.field === 'symbol')!; const noteField = summary.fields.find(f => f.field === 'note')!; expect(idField.examples).toEqual([]); expect(idChildField.examples).toEqual([]); expect(symbolField.examples).toEqual(['AAAA', 'BBBB']); expect(noteField.examples.length).toBe(2); expect(noteField.examples[0]).toBe('line1 line2 w...'); expect(noteField.examples[0]!.length).toBeLessThanOrEqual(16); expect(noteField.examples[1]).toBe('short'); expect(() => summarizeFieldShapes(docs, { maxExamples: -1 })).toThrow(RangeError); expect(() => summarizeFieldShapes(docs, { maxExamples: MAX_EXAMPLES_CAP + 1 })).toThrow( RangeError ); expect(() => summarizeFieldShapes(docs, { maxExampleLength: 0 })).toThrow(RangeError); expect(() => summarizeFieldShapes(docs, { maxExampleLength: MAX_EXAMPLE_LENGTH_CAP + 1 }) ).toThrow(RangeError); }); test('produces deep-equal output for shuffled input order and handles empty iterable', () => { expect(summarizeFieldShapes([])).toEqual({ docCount: 0, fields: [] }); const original: Record[] = [ { _id: fakeObjectId('000000000000000000000001'), z: 'delta', a: 10, meta: { k: 'v3' } }, { _id: fakeObjectId('000000000000000000000002'), z: 'alpha', a: 2.5, meta: { k: 'v1' } }, { _id: fakeObjectId('000000000000000000000003'), z: 'charlie', b: true, meta: { k: 'v4' } }, { _id: fakeObjectId('000000000000000000000004'), z: 'bravo', a: null, meta: { k: 'v2' } }, ]; const shuffled = [original[2]!, original[0]!, original[3]!, original[1]!]; const a = summarizeFieldShapes(original, { maxExamples: 2 }); const b = summarizeFieldShapes(shuffled, { maxExamples: 2 }); expect(b).toEqual(a); expect(a.fields.map(f => f.field)).toEqual(['_id', 'a', 'b', 'meta', 'meta.k', 'z']); }); }); describe('readFieldShapes', () => { test('calls only find() with limit and promoteValues/promoteLongs false, closes cursors, and enforces client limit', async () => { const docsByCollection: Record[]> = { qmDividends: [ { _id: fakeObjectId('507f1f77bcf86cd799439011'), amount: fakeDouble(0.25), currency: 'USD' }, { _id: fakeObjectId('507f1f77bcf86cd799439012'), amount: fakeDouble(0.5), currency: 'CAD' }, { _id: fakeObjectId('507f1f77bcf86cd799439013'), amount: fakeDouble(1.0), currency: 'USD' }, ], ceoShorts: [ { _id: fakeObjectId('507f1f77bcf86cd799439014'), symbol: 'ABC', shares: fakeInt32(1000) }, ], }; const { reader, calls, closedCollections, pullsByCollection } = createFakeReader( docsByCollection, { ignoreLimit: true, failIterOnCollection: 'qmDividends', failIterAtIndex: 2, } ); const result = await readFieldShapes(reader, { collections: ['qmDividends', 'ceoShorts', 'qmDividends'], limit: 2, batchSize: 500, }); expect(calls.length).toBe(2); expect(calls.map(c => c.collectionName)).toEqual(['ceoShorts', 'qmDividends']); for (const call of calls) { expect(call.filter).toEqual({}); expect(call.options).toEqual({ limit: 2, promoteValues: false, promoteLongs: false, batchSize: 500, }); } expect(closedCollections).toEqual(['ceoShorts', 'qmDividends']); // Breaks immediately after recording the limit-th doc without pulling a 3rd item expect(pullsByCollection).toEqual({ ceoShorts: 1, qmDividends: 2 }); // Defensively capped at limit=2 even though fake reader ignored limit expect(result.limit).toBe(2); expect(result.totalDocsSampled).toBe(3); const qmDiv = result.collections.find(c => c.collection === 'qmDividends')!; expect(qmDiv.docCount).toBe(2); const amountField = qmDiv.fields.find(f => f.field === 'amount')!; expect(amountField.typeCounts.double).toBe(2); }); test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => { const { reader, calls } = createFakeReader({}); const result = await readFieldShapes(reader); expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT); expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES); expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH); expect(calls.length).toBe(FIELD_SHAPE_PROBE_COLLECTIONS.length); for (const call of calls) { expect(call.options).toEqual({ limit: DEFAULT_FIELD_SHAPE_LIMIT, promoteValues: false, promoteLongs: false, }); } }); test('rejects invalid limit, unknown collection, and non-read-only reader before any query', async () => { const nonRo = createFakeReader({}, { readOnly: false }); await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i); expect(nonRo.calls.length).toBe(0); const badLimitHigh = createFakeReader({}); await expect( readFieldShapes(badLimitHigh.reader, { limit: MAX_FIELD_SHAPE_LIMIT + 1 }) ).rejects.toThrow(RangeError); expect(badLimitHigh.calls.length).toBe(0); const badLimitZero = createFakeReader({}); await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError); expect(badLimitZero.calls.length).toBe(0); const unknownCol = createFakeReader({}); let caught: unknown; try { await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(UnknownProbeCollectionError); expect((caught as UnknownProbeCollectionError).collectionName).toBe('notACollection'); expect(unknownCol.calls.length).toBe(0); }); test('rejects buffered array cursor with TypeError and surfaces per-collection errors with cause', async () => { const buffered = createFakeReader( { eodPrices: [{ date: '2025-01-02' }] }, { returnBufferedArrayOnCollection: 'eodPrices' } ); await expect( readFieldShapes(buffered.reader, { collections: ['eodPrices'] }) ).rejects.toThrow(TypeError); const findErr = createFakeReader({}, { failFindOnCollection: 'qmFilings' }); let caughtFind: unknown; try { await readFieldShapes(findErr.reader, { collections: ['eodPrices', 'qmFilings'] }); } catch (err) { caughtFind = err; } expect(caughtFind).toBeInstanceOf(Error); expect((caughtFind as Error).message).toContain('qmFilings'); expect((caughtFind as Error).cause).toBeInstanceOf(Error); const iterErr = createFakeReader( { qmEarnings: [{ a: 1 }, { a: 2 }] }, { failIterOnCollection: 'qmEarnings' } ); let caughtIter: unknown; try { await readFieldShapes(iterErr.reader, { collections: ['qmEarnings'] }); } catch (err) { caughtIter = err; } expect(caughtIter).toBeInstanceOf(Error); expect((caughtIter as Error).message).toContain('qmEarnings'); expect((caughtIter as Error).cause).toBeInstanceOf(Error); expect(iterErr.closedCollections).toEqual(['qmEarnings']); const closeErr = createFakeReader( { teMarketData: [{ country: 'US' }] }, { failCloseOnCollection: 'teMarketData' } ); let caughtClose: unknown; try { await readFieldShapes(closeErr.reader, { collections: ['teMarketData'] }); } catch (err) { caughtClose = err; } expect(caughtClose).toBeInstanceOf(Error); expect((caughtClose as Error).message).toContain('teMarketData'); expect((caughtClose as Error).cause).toBeInstanceOf(Error); }); }); interface MdastNode { type: string; value?: string; children?: MdastNode[]; } function decodeHtmlEntities(text: string): string { return text.replace(/&(amp|lt|gt|#(\d+));/g, (_, entity: string, code?: string) => { if (code !== undefined) { return String.fromCharCode(Number(code)); } switch (entity) { case 'amp': return '&'; case 'lt': return '<'; case 'gt': return '>'; default: return `&${entity};`; } }); } function parseGfmTables(markdown: string): MdastNode[][] { const ast = markdownPlugin.parsers.markdown.parse( markdown, {} as ParserOptions ) as unknown as MdastNode; const rows: MdastNode[][] = []; for (const node of ast.children ?? []) { if (node.type !== 'table') { continue; } const tableRows = node.children ?? []; for (let rowIndex = 1; rowIndex < tableRows.length; rowIndex++) { rows.push(tableRows[rowIndex]?.children ?? []); } } return rows; } function extractGfmCodeCellValues(cell: MdastNode): string[] { const nodes = cell.children ?? []; if (nodes.length === 1 && nodes[0]?.type === 'text' && nodes[0].value === '—') { return []; } const values: string[] = []; let i = 0; while (i < nodes.length) { const node = nodes[i]!; if (node.type === 'inlineCode') { values.push(node.value ?? ''); i += 1; } else if (node.type === 'html' && node.value === '') { let inner = ''; i += 1; let closed = false; while (i < nodes.length) { const innerNode = nodes[i]!; if (innerNode.type === 'html' && innerNode.value === '') { closed = true; i += 1; break; } if (innerNode.type !== 'text') { throw new Error( `Unexpected Markdown node "${innerNode.type}" inside element: ${JSON.stringify(innerNode)}` ); } inner += decodeHtmlEntities(innerNode.value ?? ''); i += 1; } if (!closed) { throw new Error('Unclosed HTML element in GFM table cell'); } values.push(inner); } else if (node.type === 'text' && node.value === ', ') { i += 1; } else { throw new Error(`Unexpected node in GFM code cell: ${JSON.stringify(node)}`); } } return values; } describe('renderFieldShapesMarkdown', () => { test('renders byte-identical Markdown with bounded-sample header, valid GFM code spans, and empty collection notice', async () => { const docsA = [ { _id: fakeObjectId('000000000000000000000001'), 'pipe|col': 'val|with`ticks\\slash', 'slash\\|field': 'slash\\|pipe*em*_u_&', 'tick`field\nname': '`leading`', edge: 'double``ticks', dt: '2025-01-02', }, { _id: fakeObjectId('000000000000000000000002'), 'pipe|col': 'slash\\|pipe', 'slash\\|field': 'slash\\\\|pipe', 'tick`field\nname': ' spaced ', edge: '', dt: '2025-01-03', }, ]; const docsB = [docsA[1]!, docsA[0]!]; const run1 = await readFieldShapes( createFakeReader({ eodPrices: docsA, qmSplits: [] }).reader, { collections: ['eodPrices', 'qmSplits'], limit: 500 } ); const run2 = await readFieldShapes( createFakeReader({ eodPrices: docsB, qmSplits: [] }).reader, { collections: ['qmSplits', 'eodPrices'], limit: 500 } ); const md1 = renderFieldShapesMarkdown(run1); const md2 = renderFieldShapesMarkdown(run2); expect(md1).toBe(md2); expect(md1).toContain('bounded sample'); expect(md1).toContain('Sample limit per collection:** 500'); expect(md1).toContain('Total documents sampled:** 2'); expect(md1).toContain('_No documents sampled._'); const tableRows = parseGfmTables(md1); expect(tableRows.length).toBe(6); const visibleByField = new Map(); for (const cells of tableRows) { expect(cells.length).toBe(5); const parsedField = extractGfmCodeCellValues(cells[0]!); expect(parsedField.length).toBe(1); const parsedExamples = extractGfmCodeCellValues(cells[4]!); visibleByField.set(parsedField[0]!, parsedExamples); } expect(visibleByField.get('pipe|col')).toEqual(['slash\\|pipe', 'val|with`ticks\\slash']); expect(visibleByField.get('slash\\\\|field')).toEqual([ 'slash\\\\|pipe', 'slash\\|pipe*em*_u_&', ]); expect(visibleByField.get('tick`field name')).toEqual([' spaced ', '`leading`']); expect(visibleByField.get('edge')).toEqual(['', 'double``ticks']); expect(visibleByField.get('_id')).toEqual([]); }); }); describe('CLI arg parsing and headless probe runner', () => { test('parseProbeSourceFieldShapesArgs validates flags without opening any DB connection', () => { expect(parseProbeSourceFieldShapesArgs(['--help'])).toEqual({ help: true }); expect(() => parseProbeSourceFieldShapesArgs([])).toThrow(/--out/); expect(() => parseProbeSourceFieldShapesArgs(['--out', ' '])).toThrow(/--out/); expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=0'])).toThrow( /--limit/ ); expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', '-1'])).toThrow( /--limit/ ); expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', String(MAX_FIELD_SHAPE_LIMIT + 1)]) ).toThrow(/--limit/); expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=abc'])).toThrow( /--limit/ ); expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=1.5'])).toThrow( /--limit/ ); expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--bogus'])).toThrow( /Unknown argument/ ); expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--collections=eodPrices,bogusCol']) ).toThrow(UnknownProbeCollectionError); const parsed = parseProbeSourceFieldShapesArgs([ '--out', './tmp/report.md', '--limit', '250', '--collections', 'qmDividends,ceoShorts,qmDividends', ]); expect(parsed).toEqual({ help: false, outPath: './tmp/report.md', limit: 250, collections: ['ceoShorts', 'qmDividends'], }); }); test('runSourceFieldShapesProbe rejects non-read-only client before any query and writes report headlessly', async () => { let getCollectionCalls = 0; let closeCalls = 0; const writableClient: ReadOnlyMongoCollectionClient = { isReadOnly: () => false, getCollection() { getCollectionCalls += 1; throw new Error('should never be called'); }, }; await expect( runSourceFieldShapesProbe( { mongoCollectionClient: writableClient, closeMongo: () => { closeCalls += 1; }, writeFile: () => {}, writeStdout: () => {}, }, { outPath: './tmp/should-not-write.md' } ) ).rejects.toThrow(/read-only/i); expect(getCollectionCalls).toBe(0); expect(closeCalls).toBe(1); const writtenFiles: Array<{ filePath: string; content: string }> = []; const stdoutChunks: string[] = []; let roCloseCalls = 0; const roClient: ReadOnlyMongoCollectionClient = { isReadOnly: () => true, getCollection(name: string) { return { find() { const docs = name === 'ceoShorts' ? [{ symbol: 'XYZ', shares: 100 }] : []; return { async *[Symbol.asyncIterator]() { for (const doc of docs) { yield doc; } }, async close() {}, }; }, }; }, }; const output = await runSourceFieldShapesProbe( { mongoCollectionClient: roClient, closeMongo: () => { roCloseCalls += 1; }, writeFile: (filePath, content) => { writtenFiles.push({ filePath, content }); }, writeStdout: text => { stdoutChunks.push(text); }, }, { outPath: './tmp/field-shapes.md', limit: 10, collections: ['ceoShorts'], } ); expect(roCloseCalls).toBe(1); expect(writtenFiles.length).toBe(1); expect(writtenFiles[0]!.filePath).toBe('./tmp/field-shapes.md'); expect(writtenFiles[0]!.content).toBe(output.markdown); expect(stdoutChunks.join('')).toContain('Documents sampled: 1'); }); });