import assert from 'node:assert/strict' import { afterEach, beforeEach, test } from 'node:test' import { GoogleAccountError } from './accounts.ts' import { GoogleApiError, buildGoogleApiError, requestGoogle } from './core.ts' import { __resetPeopleWarmupForTests, findContacts, getMe, listConnections, searchContacts } from './people.ts' import { looseKey, scoreContact, tokenScore } from './people-match.ts' type Call = { url: URL; method: string; credential: string } let calls: Call[] = [] function person(id: number, name: string, extra: Record = {}) { return { resourceName: 'people/c' + id, etag: 'e' + id, names: [{ displayName: name }], emailAddresses: [{ value: name.toLowerCase().replace(/\s+/g, '.') + '@example.com' }], phoneNumbers: [{ value: '555-01' + String(id).padStart(2, '0') }], ...extra } } const directory = [ person(1, 'Jane Example', { addresses: [{ formattedValue: '1 Example St\nSpringfield' }] }), person(2, 'Cathy Sample'), person(3, 'John Placeholder'), ...Array.from({ length: 2500 }, (_, i) => person(100 + i, 'Filler Person' + i, { biographies: [{ value: 'x'.repeat(200) }] })), ] function json(body: unknown, status = 200) { return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }) } function fakeGoogle(options: { otherContacts403?: boolean; searchResults?: (q: string) => unknown[] } = {}) { return (input: RequestInfo | URL, init: RequestInit | undefined, credential: string) => { const url = new URL(String(input)) const method = init?.method || 'GET' calls.push({ url, method, credential }) if (url.pathname === '/v1/people:searchContacts') { if (method !== 'GET') return new Response('404', { status: 404, headers: { 'content-type': 'text/html' } }) const q = url.searchParams.get('query') || '' if (!q) return json({}) const results = options.searchResults ? options.searchResults(q) : directory.filter((p) => p.names[0].displayName.toLowerCase().split(' ').some((t) => t.startsWith(q.toLowerCase()))).slice(0, Number(url.searchParams.get('pageSize'))).map((p) => ({ person: p })) return json(results.length ? { results } : {}) } if (url.pathname === '/v1/otherContacts:search') { if (options.otherContacts403) return json({ error: { code: 403, message: 'Request had insufficient authentication scopes.', status: 'PERMISSION_DENIED', details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason: 'ACCESS_TOKEN_SCOPE_INSUFFICIENT' }] } }, 403) return json({}) } if (url.pathname === '/v1/people/me/connections') { const size = Number(url.searchParams.get('pageSize')) const start = Number(url.searchParams.get('pageToken') || 0) const page = directory.slice(start, start + size) const next = start + size < directory.length ? String(start + size) : undefined return json({ connections: page, totalPeople: directory.length, totalItems: directory.length, ...(next ? { nextPageToken: next } : {}) }) } if (url.pathname === '/v1/people/me') return json({ resourceName: 'people/me' }) return new Response('', { status: 404 }) } } beforeEach(() => { calls = []; __resetPeopleWarmupForTests(); (globalThis as any).__kodyTestFetch = fakeGoogle() }) afterEach(() => { delete (globalThis as any).__kodyTestFetch }) test('searchContacts uses GET with query params, warms up once, and works with any alias of the same account', async () => { const first = await searchContacts({ account: 'google', query: 'jane', readMask: 'names, emailAddresses,addresses,phoneNumbers' }) assert.equal((first.results as unknown[]).length, 1) const search = calls.filter((c) => c.url.pathname === '/v1/people:searchContacts') assert.equal(search.length, 2) assert.ok(search.every((c) => c.method === 'GET' && c.credential === 'google')) assert.equal(search[0].url.searchParams.get('query'), '') assert.equal(search[1].url.searchParams.get('readMask'), 'names,emailAddresses,addresses,phoneNumbers') await searchContacts({ account: 'personal', query: 'cathy' }) assert.equal(calls.filter((c) => c.url.searchParams.get('query') === '').length, 1, 'warmup only once per account') const compact = await searchContacts({ query: 'jane', compact: true, pageSize: 500 }) assert.deepEqual((compact.results as any[])[0], { resourceName: 'people/c1', name: 'Jane Example', emails: ['jane.example@example.com'], phones: ['555-0101'], addresses: ['1 Example St, Springfield'] }) assert.equal(calls.at(-1)!.url.searchParams.get('pageSize'), '30') }) test('people helpers default the account and reject unknown names before any request', async () => { await getMe() assert.equal(calls[0].credential, 'google') await assert.rejects(searchContacts({ account: 'nope', query: 'jane' }), (e: unknown) => e instanceof GoogleAccountError && /Pass one of/.test(e.message)) assert.equal(calls.length, 1) await assert.rejects(searchContacts({ query: ' ' }), /non-empty query/) }) test('Google errors carry helper, account, status, reason, and a next step without tokens', async () => { const error = buildGoogleApiError({ helper: 'people.searchOtherContacts', account: 'personal', integrationName: 'google', url: 'https://people.googleapis.com/v1/otherContacts:search?access_token=ya29.secretvalue', status: 403, data: { error: { message: 'Request had insufficient authentication scopes. Bearer ya29.abc123', status: 'PERMISSION_DENIED', details: [{ reason: 'ACCESS_TOKEN_SCOPE_INSUFFICIENT' }] } }, requiredScopes: ['https://www.googleapis.com/auth/contacts.other.readonly'] }) assert.match(error.message, /^people\.searchOtherContacts: Google API HTTP 403 for account "personal" \(google\)/) assert.match(error.message, /PERMISSION_DENIED\/ACCESS_TOKEN_SCOPE_INSUFFICIENT/) assert.match(error.message, /needs https:\/\/www\.googleapis\.com\/auth\/contacts\.other\.readonly/) assert.doesNotMatch(error.message + error.url, /ya29|secretvalue|abc123/) assert.equal(error.reason, 'ACCESS_TOKEN_SCOPE_INSUFFICIENT') ;(globalThis as any).__kodyTestFetch = fakeGoogle() await assert.rejects(requestGoogle({ account: 'personal', api: 'people', method: 'POST', path: '/v1/people:searchContacts', body: {}, helper: 'test' }), (e: unknown) => e instanceof GoogleApiError && e.status === 404 && /endpoint path or HTTP method \(POST\)/.test(e.message)) }) test('listConnections defaults to a compact page and paginates with tokens', async () => { const page = await listConnections({ pageSize: 3 }) assert.equal(page.returned, 3) assert.equal(page.truncated, false) assert.equal(page.nextPageToken, '3') assert.ok(page.nextCursor) assert.deepEqual(Object.keys(page.connections[0]).sort(), ['addresses', 'emails', 'name', 'phones', 'resourceName']) const raw = await listConnections({ pageSize: 1, raw: true }) assert.equal((raw.connections[0] as any).etag, 'e1') }) test('listConnections caps output bytes and resumes from nextCursor without skipping', async () => { const first = await listConnections({ pageSize: 1000, raw: true, maxBytes: 20_000 }) assert.equal(first.truncated, true) assert.equal(first.truncatedReason, 'maxBytes') assert.equal(first.nextPageToken, undefined) assert.ok(JSON.stringify(first).length < 21_000) const second = await listConnections({ cursor: first.nextCursor, raw: true, maxBytes: 20_000 }) const lastFirst = (first.connections.at(-1) as any).resourceName const firstSecond = (second.connections[0] as any).resourceName const indexOf = (name: string) => directory.findIndex((p) => p.resourceName === name) assert.equal(indexOf(firstSecond), indexOf(lastFirst) + 1) await assert.rejects(listConnections({ cursor: 'garbage' }), /invalid cursor/) }) test('listConnections filtering scans pages internally and matches fuzzily', async () => { const hit = await listConnections({ match: 'kathy sample' }) assert.equal(hit.returned, 1) assert.equal((hit.connections[0] as any).name, 'Cathy Sample') assert.equal(hit.pagesFetched, 3) assert.equal(hit.scanned, directory.length) assert.equal(calls.at(-1)!.url.searchParams.get('pageSize'), '1000') const byFilter = await listConnections({ filter: { email: 'jane.example@' } }) assert.equal(byFilter.returned, 1) const many = await listConnections({ match: 'filler', maxResults: 5 }) assert.equal(many.returned, 5) assert.equal(many.truncatedReason, 'maxResults') assert.ok(many.nextCursor) const pages = await listConnections({ match: 'nobody here', maxPages: 1 }) assert.equal(pages.truncatedReason, 'maxPages') }) test('findContacts uses searchContacts first and skips otherContacts cleanly without its scope', async () => { ;(globalThis as any).__kodyTestFetch = fakeGoogle({ otherContacts403: true }) const found = await findContacts({ query: 'Jane', limit: 5 }) assert.equal(found.strategy, 'searchContacts') assert.equal(found.count, 1) assert.equal(found.results[0].source, 'searchContacts') assert.equal(found.results[0].addresses?.[0], '1 Example St, Springfield') const other = found.strategiesTried.find((a) => a.strategy === 'otherContacts')! assert.match(other.skipped!, /contacts\.other\.readonly/) assert.equal(found.strategiesTried.find((a) => a.strategy === 'connectionsScan')!.skipped, 'earlier strategy found results') await findContacts({ query: 'Jane' }) assert.equal(calls.filter((c) => c.url.pathname === '/v1/otherContacts:search').length, 2, 'warmup plus one search, then cached as unavailable') }) test('findContacts falls back to a fuzzy connections scan for spelling variants and nicknames', async () => { ;(globalThis as any).__kodyTestFetch = fakeGoogle({ searchResults: () => [] }) const variant = await findContacts({ query: 'Kathy', account: 'default' }) assert.equal(variant.strategy, 'connectionsScan') assert.equal(variant.results[0].name, 'Cathy Sample') const nickname = await findContacts({ query: 'Johnny Placeholder' }) assert.equal(nickname.results[0].name, 'John Placeholder') const none = await findContacts({ query: 'Zzyzx' }) assert.equal(none.strategy, 'none') assert.equal(none.count, 0) const capped = await findContacts({ query: 'filler', limit: 50, maxBytes: 3000, strategies: ['connectionsScan'] }) assert.equal(capped.truncated, true) assert.ok(JSON.stringify(capped).length < 3500) }) test('findContacts rethrows when every strategy failed', async () => { ;(globalThis as any).__kodyTestFetch = () => json({ error: { code: 401, message: 'Invalid Credentials', status: 'UNAUTHENTICATED' } }, 401) await assert.rejects(findContacts({ query: 'Jane' }), (e: unknown) => e instanceof GoogleApiError && e.status === 401 && /Reconnect the "google" OAuth integration/.test(e.message)) }) test('matching helpers handle case, diacritics, variants, emails, and phones', () => { assert.equal(looseKey('kathy'), looseKey('cathy')) assert.ok(tokenScore('jon', 'john') > 0) assert.equal(tokenScore('jane', 'mark'), 0) const contact = { resourceName: 'people/c9', name: 'José Ëxample', emails: ['jose@example.com'], phones: ['+1 (555) 010-9999'] } assert.equal(scoreContact('jose example', contact), 1) assert.equal(scoreContact('JOSE@example.com', contact), 1) assert.equal(scoreContact('010-9999', contact), 1) assert.equal(scoreContact('someone else', contact), 0) })