feat: ship Wave 5-6 multi-surface hygiene, optimization, and bug fixes

This commit is contained in:
Yun Chan 2026-11-14 11:51:41 +09:00
parent 01ef3293cf
commit 66b6b45ba9
399 changed files with 17828 additions and 11330 deletions

View file

@ -0,0 +1,426 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
interface HookStateSlot {
kind: 'state'
value: unknown
setter: (next: unknown) => void
}
interface HookRefSlot {
kind: 'ref'
ref: { current: unknown }
}
interface HookMemoSlot {
kind: 'memo'
deps: readonly unknown[] | undefined
value: unknown
}
interface HookEffectSlot {
kind: 'effect'
deps: readonly unknown[] | undefined
create: () => void | (() => void)
cleanup: (() => void) | undefined
}
type HookSlot = HookStateSlot | HookRefSlot | HookMemoSlot | HookEffectSlot
interface HarnessContext<T> {
defaultValue: T
currentValue: T
Provider: string
}
interface HarnessState {
mounted: boolean
unmountedSetStateCalls: number
cursor: number
slots: HookSlot[]
pendingEffects: number[]
renderFn: (() => unknown) | null
lastContextValue: unknown
}
const reactHarness = vi.hoisted(() => {
const state: HarnessState = {
mounted: false,
unmountedSetStateCalls: 0,
cursor: 0,
slots: [],
pendingEffects: [],
renderFn: null,
lastContextValue: undefined,
}
function depsChanged(
prev: readonly unknown[] | undefined,
next: readonly unknown[] | undefined,
): boolean {
if (prev === undefined || next === undefined) return true
if (prev.length !== next.length) return true
for (let i = 0; i < next.length; i += 1) {
if (!Object.is(prev[i], next[i])) return true
}
return false
}
function flushEffects(): void {
const indices = state.pendingEffects.splice(0)
for (const idx of indices) {
const slot = state.slots[idx]
if (!slot || slot.kind !== 'effect') continue
if (slot.cleanup) {
slot.cleanup()
slot.cleanup = undefined
}
const cleanup = slot.create()
slot.cleanup = typeof cleanup === 'function' ? cleanup : undefined
}
}
function renderCycle(): void {
if (!state.mounted || !state.renderFn) return
state.cursor = 0
const element = state.renderFn() as { props?: { value?: unknown } } | undefined
if (element?.props && 'value' in element.props) {
state.lastContextValue = element.props.value
}
flushEffects()
}
function reset(): void {
for (const slot of state.slots) {
if (slot.kind === 'effect' && slot.cleanup) {
slot.cleanup()
}
}
state.mounted = false
state.unmountedSetStateCalls = 0
state.cursor = 0
state.slots = []
state.pendingEffects = []
state.renderFn = null
state.lastContextValue = undefined
}
function mount(renderFn: () => unknown): void {
reset()
state.mounted = true
state.renderFn = renderFn
renderCycle()
}
function rerender(renderFn?: () => unknown): void {
if (renderFn) state.renderFn = renderFn
renderCycle()
}
function unmount(): void {
state.mounted = false
for (const slot of state.slots) {
if (slot.kind === 'effect' && slot.cleanup) {
slot.cleanup()
slot.cleanup = undefined
}
}
}
const reactMock = {
createContext<T>(defaultValue: T): HarnessContext<T> {
return {
defaultValue,
currentValue: defaultValue,
Provider: 'HarnessContextProvider',
}
},
useContext<T>(ctx: HarnessContext<T>): T {
return (state.lastContextValue as T | undefined) ?? ctx.defaultValue
},
useState<T>(initial: T | (() => T)): [T, (next: T | ((prev: T) => T)) => void] {
const idx = state.cursor++
const existing = state.slots[idx]
if (existing && existing.kind === 'state') {
return [existing.value as T, existing.setter as (next: T | ((prev: T) => T)) => void]
}
const initialVal = typeof initial === 'function' ? (initial as () => T)() : initial
const slot: HookStateSlot = {
kind: 'state',
value: initialVal,
setter: (next: unknown) => {
if (!state.mounted) {
state.unmountedSetStateCalls += 1
return
}
const prev = slot.value as T
const resolved =
typeof next === 'function' ? (next as (p: T) => T)(prev) : (next as T)
if (Object.is(prev, resolved)) return
slot.value = resolved
renderCycle()
},
}
state.slots[idx] = slot
return [slot.value as T, slot.setter as (next: T | ((prev: T) => T)) => void]
},
useRef<T>(initial: T): { current: T } {
const idx = state.cursor++
const existing = state.slots[idx]
if (existing && existing.kind === 'ref') {
return existing.ref as { current: T }
}
const slot: HookRefSlot = { kind: 'ref', ref: { current: initial } }
state.slots[idx] = slot
return slot.ref as { current: T }
},
useMemo<T>(factory: () => T, deps?: readonly unknown[]): T {
const idx = state.cursor++
const existing = state.slots[idx]
if (existing && existing.kind === 'memo' && !depsChanged(existing.deps, deps)) {
return existing.value as T
}
const value = factory()
state.slots[idx] = { kind: 'memo', deps, value }
return value
},
useCallback<T extends (...args: never[]) => unknown>(fn: T, deps: readonly unknown[]): T {
const idx = state.cursor++
const existing = state.slots[idx]
if (existing && existing.kind === 'memo' && !depsChanged(existing.deps, deps)) {
return existing.value as T
}
state.slots[idx] = { kind: 'memo', deps, value: fn }
return fn
},
useEffect(create: () => void | (() => void), deps?: readonly unknown[]): void {
const idx = state.cursor++
const existing = state.slots[idx]
if (!existing || existing.kind !== 'effect') {
state.slots[idx] = { kind: 'effect', deps, create, cleanup: undefined }
state.pendingEffects.push(idx)
return
}
if (depsChanged(existing.deps, deps)) {
existing.deps = deps
existing.create = create
state.pendingEffects.push(idx)
}
},
}
return { state, mount, rerender, unmount, reset, reactMock }
})
vi.mock('react', () => ({
...reactHarness.reactMock,
default: reactHarness.reactMock,
}))
vi.mock('react/jsx-runtime', () => ({
Fragment: 'Fragment',
jsx: (type: unknown, props: unknown) => ({ type, props }),
jsxs: (type: unknown, props: unknown) => ({ type, props }),
}))
vi.mock('react/jsx-dev-runtime', () => ({
Fragment: 'Fragment',
jsxDEV: (type: unknown, props: unknown) => ({ type, props }),
}))
import {
I18nProvider as WebI18nProvider,
loadLocaleCatalog,
type I18nContextValue,
type I18nStorage,
} from '../src/index'
import { I18nProvider as NativeI18nProvider } from '../src/index.native'
interface Deferred<T> {
promise: Promise<T>
resolve: (value: T) => void
reject: (reason: unknown) => void
}
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T) => void
let reject!: (reason: unknown) => void
const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
async function flushAsyncTurns(): Promise<void> {
await Promise.resolve()
await Promise.resolve()
await new Promise<void>((resolve) => {
setImmediate(resolve)
})
}
const PROVIDERS = [
{ name: 'web(index.tsx)', Provider: WebI18nProvider },
{ name: 'native(index.native.tsx)', Provider: NativeI18nProvider },
] as const
describe.each(PROVIDERS)('I18nProvider 비동기 안전성 ($name)', ({ Provider }) => {
const unhandledReasons: unknown[] = []
const onUnhandled = (reason: unknown): void => {
unhandledReasons.push(reason)
}
beforeEach(() => {
unhandledReasons.length = 0
process.on('unhandledRejection', onUnhandled)
})
afterEach(() => {
reactHarness.reset()
process.off('unhandledRejection', onUnhandled)
})
it('storage_load_언마운트이후완료되면_setState를호출하지않는다', async () => {
const deferred = createDeferred<string | null>()
const storage: I18nStorage = {
load: () => deferred.promise,
save: () => {},
}
reactHarness.mount(() => Provider({ initialLocale: 'ko', storage, children: null }))
reactHarness.unmount()
deferred.resolve('en')
await flushAsyncTurns()
expect(reactHarness.state.unmountedSetStateCalls).toBe(0)
expect(unhandledReasons).toEqual([])
})
it('setLocale_저장소로드완료전사용자변경시_지연된로드가덮어쓰지않는다', async () => {
const deferred = createDeferred<string | null>()
const saved: string[] = []
const storage: I18nStorage = {
load: () => deferred.promise,
save: (next) => {
saved.push(next)
},
}
reactHarness.mount(() => Provider({ initialLocale: 'ko', storage, children: null }))
const ctxBefore = reactHarness.state.lastContextValue as I18nContextValue
expect(ctxBefore.locale).toBe('ko')
ctxBefore.setLocale('ja')
const ctxAfterSet = reactHarness.state.lastContextValue as I18nContextValue
expect(ctxAfterSet.locale).toBe('ja')
// 사용자가 언어를 바꾼 뒤 늦게 도착한 저장소 값은 무시되어야 한다
deferred.resolve('en')
await flushAsyncTurns()
const ctxAfterLoad = reactHarness.state.lastContextValue as I18nContextValue
expect(ctxAfterLoad.locale).toBe('ja')
expect(saved).toEqual(['ja'])
})
it('setLocale_인라인storage객체재렌더후로드가재실행되어도_사용자선택을유지한다', async () => {
const firstLoad = createDeferred<string | null>()
const secondLoad = createDeferred<string | null>()
let loadCount = 0
reactHarness.mount(() =>
Provider({
initialLocale: 'ko',
storage: {
load: () => {
loadCount += 1
return loadCount === 1 ? firstLoad.promise : secondLoad.promise
},
save: () => {},
},
children: null,
}),
)
const ctx = reactHarness.state.lastContextValue as I18nContextValue
ctx.setLocale('fr')
// 부모가 인라인 storage 객체로 재렌더링하더라도 사용자 선택('fr')이 유지되어야 한다
reactHarness.rerender(() =>
Provider({
initialLocale: 'ko',
storage: {
load: () => secondLoad.promise,
save: () => {},
},
children: null,
}),
)
firstLoad.resolve('en')
secondLoad.resolve('de')
await flushAsyncTurns()
const finalCtx = reactHarness.state.lastContextValue as I18nContextValue
expect(finalCtx.locale).toBe('fr')
})
it('storage_load와save가동기또는비동기로실패해도_unhandledRejection을발생시키지않는다', async () => {
const failingAsyncStorage: I18nStorage = {
load: () => Promise.reject(new Error('storage load failed')),
save: () => Promise.reject(new Error('storage save failed')),
}
reactHarness.mount(() =>
Provider({ initialLocale: 'ko', storage: failingAsyncStorage, children: null }),
)
const ctx = reactHarness.state.lastContextValue as I18nContextValue
ctx.setLocale('en')
await flushAsyncTurns()
expect((reactHarness.state.lastContextValue as I18nContextValue).locale).toBe('en')
expect(unhandledReasons).toEqual([])
const throwingSyncStorage: I18nStorage = {
load: () => {
throw new Error('sync load failure')
},
save: () => {
throw new Error('sync save failure')
},
}
reactHarness.mount(() =>
Provider({ initialLocale: 'en', storage: throwingSyncStorage, children: null }),
)
const syncCtx = reactHarness.state.lastContextValue as I18nContextValue
syncCtx.setLocale('de')
await flushAsyncTurns()
expect((reactHarness.state.lastContextValue as I18nContextValue).locale).toBe('de')
expect(unhandledReasons).toEqual([])
})
})
describe('loadLocaleCatalog 및 날짜 포맷 방어 (packages/i18n)', () => {
it('loadLocaleCatalog_동시호출시_중복로드를방지하고정상카탈로그를반환한다', async () => {
const [first, second] = await Promise.all([
loadLocaleCatalog('ja'),
loadLocaleCatalog('ja'),
])
expect(first['login.subtitle']).toBe('AI音声アシスタント')
expect(second).toBe(first)
})
it('I18nProvider_유효하지않은타임스탬프와날짜를전달해도_예외없이빈문자열을반환한다', () => {
reactHarness.mount(() => WebI18nProvider({ initialLocale: 'en', children: null }))
const ctx = reactHarness.state.lastContextValue as I18nContextValue
expect(ctx.formatDate(Number.NaN)).toBe('')
expect(ctx.formatTime(Number.POSITIVE_INFINITY)).toBe('')
expect(ctx.formatRelativeDate(Number.NaN)).toBe('')
expect(ctx.formatDate(new Date('invalid-date'))).toBe('')
expect(ctx.formatDate(1_700_000_000_000, { year: 'numeric' })).toBe('2023')
})
})

View file

@ -0,0 +1,80 @@
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
import { LOCALE_CODES, LOCALE_META, isValidLocale, resolveTranslationWithFallback, toBcp47 } from '../src/shared'
const LOCALES_DIR = path.resolve(__dirname, '../src/locales')
function extractPlaceholders(value: string): string[] {
const matches = [...value.matchAll(/\{\{([a-zA-Z0-9_]+)\}\}/g)]
return [...new Set(matches.map((m) => m[1]))].sort()
}
describe('@d3ro/i18n 12개 로케일 계약 테스트 (G5 / GAP-I18N-03)', () => {
const ko = JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, 'ko.json'), 'utf8')) as Record<string, string>
const en = JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, 'en.json'), 'utf8')) as Record<string, string>
const masterKeys = Object.keys(ko)
it('LOCALE_META_12개지원언어코드와순서가LOCALE_CODES와일치한다', () => {
expect(LOCALE_CODES).toHaveLength(12)
expect(LOCALE_META.map((item) => item.code)).toEqual([...LOCALE_CODES])
for (const code of LOCALE_CODES) {
expect(isValidLocale(code)).toBe(true)
}
expect(isValidLocale('invalid-locale')).toBe(false)
})
it.each(LOCALE_CODES)(
'로케일사전_%s_마스터키집합과동일하고빈문자열이없다',
(localeCode) => {
const catalog = JSON.parse(
fs.readFileSync(path.join(LOCALES_DIR, `${localeCode}.json`), 'utf8'),
) as Record<string, string>
const keys = Object.keys(catalog)
const missing = masterKeys.filter((k) => !(k in catalog))
const extra = keys.filter((k) => !(k in ko))
const empty = masterKeys.filter((k) => typeof catalog[k] !== 'string' || catalog[k].trim().length === 0)
expect(missing).toEqual([])
expect(extra).toEqual([])
expect(empty).toEqual([])
},
)
it('플레이스홀더정합성_영어번역의치환변수목록이한국어마스터와일치한다', () => {
const mismatches: string[] = []
for (const key of masterKeys) {
const koTokens = extractPlaceholders(ko[key] ?? '')
const enTokens = extractPlaceholders(en[key] ?? '')
if (koTokens.join(',') !== enTokens.join(',')) {
mismatches.push(`${key}: ko=[${koTokens.join(',')}] vs en=[${enTokens.join(',')}]`)
}
}
expect(mismatches).toEqual([])
})
it('resolveTranslationWithFallback_누락키발생시_영어한국어키순으로안전하게폴백한다', () => {
expect(
resolveTranslationWithFallback(
'greeting',
{ greeting: 'こんにちは {{name}}' },
{ greeting: 'Hello {{name}}' },
{ greeting: '안녕 {{name}}' },
{ name: 'D3RO' },
),
).toBe('こんにちは D3RO')
expect(
resolveTranslationWithFallback(
'missing.in.primary',
{},
{ 'missing.in.primary': 'Fallback EN' },
{ 'missing.in.primary': '폴백 KO' },
),
).toBe('Fallback EN')
expect(toBcp47('zh')).toBe('zh-CN')
expect(toBcp47('zh-TW')).toBe('zh-TW')
expect(toBcp47('ko')).toBe('ko')
})
})