import fs from 'node:fs' import path from 'node:path' import vm from 'node:vm' import { afterEach, describe, expect, it, vi } from 'vitest' import { createFakeClock, createSeededRandom } from '@d3ro/core/ports' import { toErrorMessage } from '../../src/renderer/utils/error-message' import { formatElapsed } from '../../src/renderer/components/meeting/meeting-format' import { formatClockTime, formatDayLabel, formatDurationLong, formatNumber, formatRecordingTime, formatRecordingTimeUnit, getDateKey, } from '../../src/renderer/utils/formatters' interface FakeClassList { tokens: Set add: (...cls: string[]) => void remove: (...cls: string[]) => void toggle: (cls: string, force?: boolean) => boolean contains: (cls: string) => boolean } class FakeElement { id: string tagName: string children: FakeElement[] = [] parentNode: FakeElement | null = null attributes = new Map() listeners = new Map void>>() style: Record = {} hidden = false type = '' scrollTop = 0 offsetWidth = 0 innerHtmlWrites: string[] = [] private _innerHTML = '' private _textContent = '' readonly classList: FakeClassList constructor(tagName: string, id = '') { this.tagName = tagName.toUpperCase() this.id = id const tokens = new Set() this.classList = { tokens, add: (...cls: string[]) => { for (const c of cls) tokens.add(c) }, remove: (...cls: string[]) => { for (const c of cls) tokens.delete(c) }, toggle: (cls: string, force?: boolean) => { const next = force ?? !tokens.has(cls) if (next) tokens.add(cls) else tokens.delete(cls) return next }, contains: (cls: string) => tokens.has(cls), } } get className(): string { return Array.from(this.classList.tokens).join(' ') } set className(val: string) { this.classList.tokens.clear() for (const part of val.split(/\s+/).filter(Boolean)) { this.classList.tokens.add(part) } } get firstChild(): FakeElement | null { return this.children[0] ?? null } get textContent(): string { if (this.tagName === '#TEXT') return this._textContent return this.children.map((c) => c.textContent).join('') } set textContent(val: string) { if (this.tagName === '#TEXT') { this._textContent = val this.children = [] return } this._textContent = '' if (val === '') { this.children = [] return } const textNode = new FakeElement('#TEXT') textNode._textContent = val this.children = [textNode] } get innerHTML(): string { return this._innerHTML } set innerHTML(val: string) { this.innerHtmlWrites.push(val) this._innerHTML = val if (val === '') this.children = [] } appendChild(child: FakeElement): FakeElement { child.parentNode = this this.children.push(child) return child } insertBefore(child: FakeElement, refChild: FakeElement | null): FakeElement { child.parentNode = this const idx = refChild ? this.children.indexOf(refChild) : -1 if (idx < 0) this.children.push(child) else this.children.splice(idx, 0, child) return child } removeChild(child: FakeElement): FakeElement { const idx = this.children.indexOf(child) if (idx >= 0) { this.children.splice(idx, 1) child.parentNode = null } return child } setAttribute(name: string, value: string): void { this.attributes.set(name, value) } getAttribute(name: string): string | null { return this.attributes.get(name) ?? null } removeAttribute(name: string): void { this.attributes.delete(name) } addEventListener(type: string, cb: (event?: unknown) => void): void { const list = this.listeners.get(type) ?? [] list.push(cb) this.listeners.set(type, list) } removeEventListener(type: string, cb: (event?: unknown) => void): void { const list = this.listeners.get(type) if (!list) return const idx = list.indexOf(cb) if (idx >= 0) list.splice(idx, 1) } dispatch(type: string, event: unknown = {}): void { for (const cb of this.listeners.get(type) ?? []) cb(event) } scrollIntoView(): void {} setPointerCapture(): void {} getBoundingClientRect(): { width: number; height: number } { return { width: 200, height: 80 } } } interface PopupSandbox { elements: Map emitIpc: (channel: string, data?: unknown) => void sent: Array<{ channel: string; payload: unknown }> unsubCalls: () => number registeredCount: () => number triggerDocument: (type: string) => void triggerWindow: (type: string) => void flushRaf: () => void pendingRafCount: () => number } function loadPopupSandbox(popupName: string, elementIds: readonly string[]): PopupSandbox { const scriptPath = path.resolve( __dirname, '../../src/renderer/popups', popupName, 'script.js', ) const code = fs.readFileSync(scriptPath, 'utf8') const elements = new Map() for (const id of elementIds) { elements.set(id, new FakeElement('div', id)) } const ipcHandlers = new Map void>>() const sent: Array<{ channel: string; payload: unknown }> = [] let activeSubscriptions = 0 let totalUnsubs = 0 const docListeners = new Map void>>() const winListeners = new Map void>>() let rafId = 0 const rafQueue = new Map void>() const fakeClock = createFakeClock(1_700_000_000_000) const seededRandom = createSeededRandom(42) const fakeWindow = { addEventListener(type: string, cb: () => void): void { const list = winListeners.get(type) ?? [] list.push(cb) winListeners.set(type, list) }, removeEventListener(type: string, cb: () => void): void { const list = winListeners.get(type) if (!list) return const idx = list.indexOf(cb) if (idx >= 0) list.splice(idx, 1) }, popupAPI: { send(channel: string, payload?: unknown): void { sent.push({ channel, payload }) }, on(channel: string, cb: (data?: unknown) => void): () => void { activeSubscriptions += 1 const list = ipcHandlers.get(channel) ?? [] list.push(cb) ipcHandlers.set(channel, list) let removed = false return () => { if (removed) return removed = true activeSubscriptions -= 1 totalUnsubs += 1 const current = ipcHandlers.get(channel) ?? [] const idx = current.indexOf(cb) if (idx >= 0) current.splice(idx, 1) } }, }, } const FakeDate = class extends Date { constructor(value?: number | string | Date) { super(value === undefined ? fakeClock.now() : (value as number)) } static now(): number { return fakeClock.now() } } const fakeMath = Object.assign(Object.create(Math), { random: () => seededRandom.next(), }) const context: Record = { window: fakeWindow, document: { getElementById: (id: string) => elements.get(id) ?? null, querySelectorAll: () => [], createElement: (tag: string) => new FakeElement(tag), createTextNode: (text: string) => { const node = new FakeElement('#text') node.textContent = text return node }, addEventListener(type: string, cb: () => void): void { const list = docListeners.get(type) ?? [] list.push(cb) docListeners.set(type, list) }, removeEventListener(type: string, cb: () => void): void { const list = docListeners.get(type) if (!list) return const idx = list.indexOf(cb) if (idx >= 0) list.splice(idx, 1) }, }, Date: FakeDate, Math: fakeMath, Number, String, Array, setTimeout, clearTimeout, setInterval, clearInterval, requestAnimationFrame(cb: () => void): number { rafId += 1 rafQueue.set(rafId, cb) return rafId }, cancelAnimationFrame(id: number): void { rafQueue.delete(id) }, } vm.runInNewContext(code, context, { filename: scriptPath }) return { elements, sent, unsubCalls: () => totalUnsubs, registeredCount: () => activeSubscriptions, emitIpc(channel: string, data?: unknown): void { for (const cb of [...(ipcHandlers.get(channel) ?? [])]) { cb(data) } }, triggerDocument(type: string): void { for (const cb of docListeners.get(type) ?? []) cb() }, triggerWindow(type: string): void { for (const cb of winListeners.get(type) ?? []) cb() }, flushRaf(): void { const entries = Array.from(rafQueue.entries()) rafQueue.clear() for (const [, cb] of entries) cb() }, pendingRafCount: () => rafQueue.size, } } describe('렌더러 포맷터 및 팝업 스크립트 방어 동작', () => { afterEach(() => { vi.useRealTimers() }) it('formatters와formatElapsed_비유한수와음수입력시_NaN이나음수문자열을반환하지않는다', () => { expect(formatElapsed(Number.NaN)).toBe('00:00') expect(formatElapsed(-500)).toBe('00:00') expect(formatElapsed(3_665_000)).toBe('1:01:05') expect(formatDurationLong(Number.NaN, 'en')).toBe('0 min') expect(formatNumber(Number.NaN)).toBe('0') expect(formatRecordingTime(Number.NaN)).toBe('0') expect(formatRecordingTimeUnit(Number.NaN)).toBe('MIN') expect(getDateKey(Number.NaN)).toBe('') expect(formatClockTime(Number.NaN, 'en')).toBe('') expect(formatDayLabel(Number.NaN, 'en')).toBe('') expect(toErrorMessage(new Error('network down'))).toBe('network down') expect(toErrorMessage('plain failure')).toBe('plain failure') }) it('commandPopup_innerHTML을사용하지않고null페이로드및beforeunload해제를안전하게처리한다', () => { const sandbox = loadPopupSandbox('command-popup', ['container', 'items']) const items = sandbox.elements.get('items')! sandbox.emitIpc('command:showItems', { commands: [{ id: '1', name: '', description: 'desc' }], activeId: '', }) sandbox.emitIpc('command:showItems', null) sandbox.emitIpc('command:keyEvent', null) expect(items.innerHtmlWrites).toEqual([]) expect(items.children[1]?.textContent).toContain('') sandbox.triggerWindow('beforeunload') expect(sandbox.registeredCount()).toBe(0) expect(sandbox.unsubCalls()).toBe(4) }) it('historyPopup_비유한타임스탬프와null페이로드에서도_NaN을렌더링하지않고언로드시구독을해제한다', () => { const sandbox = loadPopupSandbox('history-popup', ['container', 'items']) const items = sandbox.elements.get('items')! sandbox.emitIpc('history:showItems', { entries: [{ id: '1', originalText: '원문', polishedText: '', createdAt: Number.NaN }], }) sandbox.emitIpc('history:showItems', null) sandbox.emitIpc('history:keyEvent', null) expect(items.innerHtmlWrites).toEqual([]) expect(items.children[0]?.textContent.includes('NaN')).toBe(false) sandbox.triggerWindow('beforeunload') expect(sandbox.registeredCount()).toBe(0) }) it('resultPopup_prepare직후hide수신시_측정IPC를보내지않고숨겨진상태mouseleave로타이머가돌지않는다', () => { vi.useFakeTimers({ now: 1_700_000_000_000 }) const sandbox = loadPopupSandbox('result-popup', [ 'container', 'result-text', 'copy-btn', 'copy-icon', 'check-icon', 'copy-label', 'close-btn', ]) const container = sandbox.elements.get('container')! sandbox.emitIpc('result:prepare', { text: '복사할 문장' }) sandbox.emitIpc('result:hide') sandbox.flushRaf() sandbox.flushRaf() expect(sandbox.sent.filter((item) => item.channel === 'result:measured')).toEqual([]) container.dispatch('mouseleave') vi.advanceTimersByTime(5000) expect(sandbox.sent.filter((item) => item.channel === 'window:hideResultPopup')).toEqual([]) sandbox.triggerWindow('beforeunload') expect(sandbox.registeredCount()).toBe(0) }) it('captionOverlay_hide이후지연페이드타이머가새세션자막을지우지않고언로드시리소스를정리한다', () => { vi.useFakeTimers({ now: 1_700_000_000_000 }) const sandbox = loadPopupSandbox('caption-overlay', [ 'lines', 'container', 'root', 'handle', 'handleHint', ]) const lines = sandbox.elements.get('lines')! sandbox.emitIpc('caption:config', { autoClearMs: 1000 }) sandbox.emitIpc('caption:segment', { id: 's1', text: '첫 문장', timestamp: 1, isFinal: true }) // 1000ms 뒤 fadeAndRemoveLine(500ms 타이머 시작) 진입 vi.advanceTimersByTime(1000) // fade-out 도중 hide 후 곧바로 새 자막이 들어와도 이전 fade 타이머는 취소되어야 한다 sandbox.emitIpc('caption:hide') expect(lines.children).toHaveLength(0) sandbox.emitIpc('caption:segment', { id: 's2', text: '새 세션 문장', timestamp: 2, isFinal: true }) sandbox.emitIpc('caption:stateChanged', null) vi.advanceTimersByTime(600) expect(lines.children).toHaveLength(1) expect(lines.children[0]?.textContent).toBe('새 세션 문장') sandbox.triggerWindow('beforeunload') expect(vi.getTimerCount()).toBe(0) expect(sandbox.registeredCount()).toBe(0) }) it('suggestionOverlay_범위초과activeIndex에서도_유효페이지후보를표시하고언로드시정리한다', () => { vi.useFakeTimers({ now: 1_700_000_000_000 }) const sandbox = loadPopupSandbox('suggestion-overlay', [ 'candidates', 'provenance', 'progress', 'keyHints', 'footer', 'status', 'statusText', 'panel', 'close', ]) const candidates = sandbox.elements.get('candidates')! sandbox.emitIpc('suggestionPopup:show', { candidates: [{ text: '첫째' }, { text: '둘째' }], activeIndex: 99, generating: true, }) expect(candidates.children).toHaveLength(2) expect(candidates.children[1]?.classList.contains('active')).toBe(true) sandbox.triggerWindow('beforeunload') expect(vi.getTimerCount()).toBe(0) expect(sandbox.registeredCount()).toBe(0) }) it('recordingTip_음수레벨클램프와언로드시인터벌및IPC해제를수행한다', () => { vi.useFakeTimers({ now: 1_700_000_000_000 }) const sandbox = loadPopupSandbox('recording-tip', [ 'container', 'wave-bars', 'duration-text', 'status-text', 'cancel-hint', 'progress', 'partial-text', 'done-view', 'done-text', 'error-view', 'error-text', 'head-row', ]) sandbox.triggerDocument('DOMContentLoaded') sandbox.emitIpc('voice:audioLevel', { level: -2 }) sandbox.emitIpc('window:tipStateChanged', { state: 'recording' }) vi.advanceTimersByTime(1000) const barHeights = sandbox.elements .get('wave-bars')! .children.map((bar) => Number.parseInt(bar.style.height, 10)) expect(barHeights.every((h) => Number.isFinite(h) && h >= 2 && h <= 22)).toBe(true) sandbox.triggerWindow('beforeunload') expect(vi.getTimerCount()).toBe(0) expect(sandbox.registeredCount()).toBe(0) }) })