feat: add mobile shell and unified search
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Failing after 50s
ci / 워크스페이스 빌드 검증 (push) Has been skipped
ci / Supabase Edge Functions + Cloudflare Worker (push) Successful in 20s
ci / .NET API 서버 테스트 (push) Successful in 12s
deploy-site / deploy (push) Successful in 39s
ci / 모바일 린트·타입·Jest (push) Failing after 3h10m31s

This commit is contained in:
Yun Chan 2026-09-28 23:23:36 +09:00
parent f505a03d34
commit 5ca3709b32
98 changed files with 5168 additions and 2093 deletions

View file

@ -0,0 +1,5 @@
const MAX_INITIAL_QUERY_LENGTH = 100
export function normalizeUnifiedSearchInitialQuery(value: unknown): string {
return typeof value === 'string' ? value.slice(0, MAX_INITIAL_QUERY_LENGTH) : ''
}

View file

@ -0,0 +1,272 @@
import type { D3roSupabaseClient, HistoryEntry, Meeting } from '@d3ro/api-client'
import type {
UnifiedSearchResponse,
UnifiedSearchResult,
} from '@d3ro/core/types'
import { supabase } from '../../lib/supabase'
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const DEFAULT_LIMIT = 30
const MAX_LIMIT = 50
const MAX_QUERY_LENGTH = 100
const EXCERPT_LENGTH = 180
const HISTORY_SEARCH_COLUMNS = 'id,title,original_text,polished_text,summary_text,created_at'
const MEETING_SEARCH_COLUMNS = 'id,title,raw_transcript,edited_transcript,started_at'
export type UnifiedSearchServiceErrorCode = 'auth' | 'invalid' | 'network' | 'server'
export class UnifiedSearchServiceError extends Error {
constructor(
public readonly code: UnifiedSearchServiceErrorCode,
message: string,
) {
super(message)
this.name = 'UnifiedSearchServiceError'
}
}
export interface UnifiedSearchSourcePage<T> {
rows: T[]
total: number
}
type UnifiedSearchHistoryRow = Pick<
HistoryEntry,
'id' | 'title' | 'original_text' | 'polished_text' | 'summary_text' | 'created_at'
>
type UnifiedSearchMeetingRow = Pick<
Meeting,
'id' | 'title' | 'raw_transcript' | 'edited_transcript' | 'started_at'
>
export interface UnifiedSearchSourcePort {
searchRecords: (
userId: string,
query: string,
limit: number,
) => Promise<UnifiedSearchSourcePage<UnifiedSearchHistoryRow>>
searchMeetings: (
query: string,
limit: number,
) => Promise<UnifiedSearchSourcePage<UnifiedSearchMeetingRow>>
}
export interface MobileUnifiedSearchOptions {
userId: string
query: string
limit?: number
}
function client(): D3roSupabaseClient {
return supabase as unknown as D3roSupabaseClient
}
function requireOptions(options: MobileUnifiedSearchOptions): void {
if (typeof options !== 'object' || options === null || Array.isArray(options)) {
throw new UnifiedSearchServiceError('invalid', 'Unified search options are required')
}
}
function requireUserId(userId: unknown): asserts userId is string {
if (typeof userId !== 'string' || !UUID_PATTERN.test(userId)) {
throw new UnifiedSearchServiceError('auth', 'A valid authenticated user is required')
}
}
function requireQuery(query: unknown): asserts query is string {
if (typeof query !== 'string') {
throw new UnifiedSearchServiceError('invalid', 'Unified search query must be a string')
}
}
function normalizeLimit(limit: unknown): number {
if (limit === undefined) return DEFAULT_LIMIT
if (typeof limit !== 'number' || !Number.isFinite(limit)) {
throw new UnifiedSearchServiceError('invalid', 'Unified search limit must be a finite number')
}
return Math.max(1, Math.min(Math.floor(limit), MAX_LIMIT))
}
export function sanitizeUnifiedSearchQuery(value: string): string {
return value
.slice(0, MAX_QUERY_LENGTH)
.trim()
.replace(/[\u0000-\u001f\u007f,()"]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
}
export function createPostgrestLikePattern(query: string): string {
const escaped = query.replace(/[\\%_*]/g, (character) => `\\${character}`)
return `*${escaped}*`
}
function includesQuery(value: string | null | undefined, query: string): boolean {
return value?.toLocaleLowerCase().includes(query.toLocaleLowerCase()) === true
}
export function createMobileSearchExcerpt(
value: string | null | undefined,
query: string,
maxLength = EXCERPT_LENGTH,
): string {
const text = (value ?? '').replace(/\s+/g, ' ').trim()
if (text.length <= maxLength) return text
const matchAt = text.toLocaleLowerCase().indexOf(query.toLocaleLowerCase())
if (matchAt < 0) return `${text.slice(0, maxLength - 1).trimEnd()}…`
const context = Math.max(20, Math.floor((maxLength - query.length) / 2))
const start = Math.max(0, matchAt - context)
const end = Math.min(text.length, start + maxLength)
const excerpt = text.slice(start, end).trim()
return `${start > 0 ? '…' : ''}${excerpt}${end < text.length ? '…' : ''}`
}
function occurredAt(value: string): number {
const timestamp = Date.parse(value)
return Number.isFinite(timestamp) ? timestamp : 0
}
function recordResult(row: UnifiedSearchHistoryRow, query: string): UnifiedSearchResult {
const titleMatched = includesQuery(row.title, query)
const matchingContent = [row.polished_text, row.original_text, row.summary_text]
.find((value) => includesQuery(value, query))
const preview = matchingContent
?? row.polished_text
?? row.original_text
?? row.summary_text
?? row.title
return {
source: 'record',
id: row.id,
title: row.title,
excerpt: createMobileSearchExcerpt(preview, query),
matchedField: titleMatched ? 'title' : 'content',
occurredAt: occurredAt(row.created_at),
}
}
function meetingResult(row: UnifiedSearchMeetingRow, query: string): UnifiedSearchResult {
const titleMatched = includesQuery(row.title, query)
const matchingTranscript = [row.edited_transcript, row.raw_transcript]
.find((value) => includesQuery(value, query))
const preview = matchingTranscript
?? row.edited_transcript
?? row.raw_transcript
?? row.title
return {
source: 'meeting',
id: row.id,
title: row.title,
excerpt: createMobileSearchExcerpt(preview, query),
matchedField: titleMatched ? 'title' : 'transcript',
occurredAt: occurredAt(row.started_at),
}
}
export function mergeMobileUnifiedSearchResults(
records: readonly UnifiedSearchResult[],
meetings: readonly UnifiedSearchResult[],
limit: number,
): UnifiedSearchResult[] {
return [...records, ...meetings]
.sort((left, right) => right.occurredAt - left.occurredAt || left.id.localeCompare(right.id))
.slice(0, limit)
}
function toSearchError(error: unknown): UnifiedSearchServiceError {
if (error instanceof UnifiedSearchServiceError) return error
const candidate = error as { code?: unknown; message?: unknown }
const code = typeof candidate?.code === 'string' ? candidate.code : ''
const message = typeof candidate?.message === 'string'
? candidate.message
: 'Unified search request failed'
const lower = message.toLocaleLowerCase()
if (
error instanceof TypeError
|| lower.includes('network request failed')
|| lower.includes('failed to fetch')
|| lower.includes('networkerror')
) {
return new UnifiedSearchServiceError('network', message)
}
if (code === 'PGRST301' || code === '42501' || lower.includes('jwt')) {
return new UnifiedSearchServiceError('auth', message)
}
return new UnifiedSearchServiceError('server', message)
}
export function createSupabaseUnifiedSearchSource(
searchClient: D3roSupabaseClient,
): UnifiedSearchSourcePort {
return {
async searchRecords(userId, query, limit) {
const pattern = createPostgrestLikePattern(query)
const { data, error, count } = await searchClient
.from('history')
.select(HISTORY_SEARCH_COLUMNS, { count: 'exact' })
.eq('user_id', userId)
.or(
`title.ilike.${pattern},original_text.ilike.${pattern},polished_text.ilike.${pattern},summary_text.ilike.${pattern}`,
)
.order('created_at', { ascending: false })
.order('id', { ascending: false })
.limit(limit)
if (error !== null) throw error
return { rows: data ?? [], total: count ?? data?.length ?? 0 }
},
async searchMeetings(query, limit) {
const pattern = createPostgrestLikePattern(query)
const { data, error, count } = await searchClient
.from('meetings')
.select(MEETING_SEARCH_COLUMNS, { count: 'exact' })
.or(
`title.ilike.${pattern},raw_transcript.ilike.${pattern},edited_transcript.ilike.${pattern}`,
)
.order('started_at', { ascending: false })
.order('id', { ascending: false })
.limit(limit)
if (error !== null) throw error
return { rows: data ?? [], total: count ?? data?.length ?? 0 }
},
}
}
const supabaseSearchSource = createSupabaseUnifiedSearchSource(client())
export async function searchUnifiedContent(
options: MobileUnifiedSearchOptions,
source: UnifiedSearchSourcePort = supabaseSearchSource,
): Promise<UnifiedSearchResponse> {
requireOptions(options)
requireUserId(options.userId)
requireQuery(options.query)
const query = sanitizeUnifiedSearchQuery(options.query)
const limit = normalizeLimit(options.limit)
if (query.length === 0) return { query, results: [], total: 0 }
try {
const [recordPage, meetingPage] = await Promise.all([
source.searchRecords(options.userId, query, limit),
source.searchMeetings(query, limit),
])
const results = mergeMobileUnifiedSearchResults(
recordPage.rows.map((row) => recordResult(row, query)),
meetingPage.rows.map((row) => meetingResult(row, query)),
limit,
)
return {
query,
results,
total: recordPage.total + meetingPage.total,
}
} catch (error) {
throw toSearchError(error)
}
}