# InsuRo PWA 캐시 근본 해결 — 업데이트 즉시 반영

## 작업 레벨: Lv.2

## 프로젝트
- InsuRo: `/home/jay/projects/InsuRo`

## 문제
배포 후 모바일/PC에서 구버전이 캐시되어 업데이트가 반영 안 되는 문제 빈번 발생.
현재 `registerType: "autoUpdate"` 설정만 있고, 실제 SW 업데이트 감지/적용 클라이언트 코드 없음.

## 수정 사항

### 1. Service Worker 업데이트 감지 + 알림 토스트
`src/main.tsx` 또는 별도 `src/sw-register.ts`:

```typescript
import { registerSW } from 'virtual:pwa-register';

const updateSW = registerSW({
  onNeedRefresh() {
    // 새 버전 감지 시 토스트 표시
    if (confirm('새 버전이 있습니다. 지금 업데이트하시겠습니까?')) {
      updateSW(true); // SW 즉시 활성화 + 페이지 새로고침
    }
  },
  onOfflineReady() {
    console.log('오프라인 사용 준비 완료');
  },
});
```

또는 toast UI로 구현 (confirm 대신):
```tsx
// 토스트 컴포넌트로 "업데이트 가능" 알림
// "지금 업데이트" 버튼 클릭 시 updateSW(true)
```

### 2. vite.config.ts — SW 설정 강화
```typescript
VitePWA({
  registerType: "autoUpdate",  // 유지
  workbox: {
    // 기존 설정 유지 +
    skipWaiting: true,        // 새 SW 즉시 활성화
    clientsClaim: true,       // 기존 클라이언트도 새 SW 제어
    cleanupOutdatedCaches: true,  // 구버전 캐시 자동 정리
  },
})
```

### 3. Cloudflare Pages `_headers` 파일
`public/_headers` (신규):
```
/index.html
  Cache-Control: no-cache, must-revalidate
  
/sw.js
  Cache-Control: no-cache, must-revalidate

/workbox-*.js
  Cache-Control: no-cache, must-revalidate

/*.js
  Cache-Control: public, max-age=31536000, immutable

/*.css
  Cache-Control: public, max-age=31536000, immutable
```

핵심: `index.html`과 `sw.js`는 **항상 서버에서 최신 확인**, JS/CSS는 해시 파일명이므로 장기 캐시.

### 4. 업데이트 토스트 UI (선택)
전체 화면 하단에 슬라이드업 토스트:
- "새 버전이 출시되었습니다"
- [지금 업데이트] 버튼 → `updateSW(true)` → 자동 새로고침
- [나중에] 버튼 → 토스트 닫기 (다음 방문 시 다시 표시)

## affected_files
- `src/main.tsx` (수정 — registerSW 등록)
- `vite.config.ts` (수정 — skipWaiting, clientsClaim, cleanupOutdatedCaches)
- `public/_headers` (신규 — Cloudflare Cache-Control)

## 검증 시나리오
1. 배포 후 → 기존 사용자 접속 시 "새 버전" 토스트 표시
2. "지금 업데이트" 클릭 → 즉시 최신 버전 로드
3. `sw.js` 요청 시 `Cache-Control: no-cache` 헤더 확인
4. `index.html` 요청 시 `Cache-Control: no-cache` 헤더 확인
5. JS/CSS 파일은 장기 캐시 (해시 파일명)
6. npm run build 성공