# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

AutoShopee Kit is a browser extension for e-commerce automation on Shopee, Lazada, TikTok, and Tiki.

- Current version: `3.4.3`
- Browser support: Chrome 88+, Firefox 78+
- Manifest: V3 (Chrome), V2 (Firefox)
- Frontend architecture: Vue 2 Options API only (do NOT use Composition API)

## Commands

```bash
npm run dev              # Development with HMR (Vite dev server, auto-opens Chrome)
npm run dev:firefox      # Development for Firefox
npm run dev:tool         # Development with Vue DevTools
npm run build:chrome     # Build for Chrome (MV3)
npm run build:firefox    # Build for Firefox (MV2)
npm run build:prod       # Production build (Chrome)
npm run zip:chrome       # Build + zip Chrome extension
npm run zip:firefox      # Build + zip Firefox extension
npm run zip:s3           # Upload zip to S3
npm run lint             # ESLint check
npm run lint:fix         # ESLint autofix
npm run format           # Prettier + ESLint fix combined
npm run pretty           # Prettier only
```

## E2E Testing with CloakBrowser

For end-to-end testing of the extension against live Shopee (which aggressively blocks
automated browsers), the project uses **CloakBrowser** — a stealth Chromium that passes
fingerprint/captcha checks. Installed as a dev dependency.

- **Dev deps**: `cloakbrowser` + `playwright-core` (install with `--legacy-peer-deps`; the
  repo has a pre-existing axios peer-dep conflict unrelated to these).
- **Stealth binary**: auto-downloaded to `~/.cloakbrowser/` (~200MB) on first launch, or
  pre-fetch with `npx cloakbrowser install`.
- **Persistent profile**: `.cloak-profile/` (git-ignored). Log in to Shopee ONCE in the
  headed window — cookies persist across runs, so subsequent runs are already logged in.
- **Start browser** (khi user nói "khởi động browser" / "start browser" / "mở browser test"):
  run `node scripts/start-browser.mjs` — launches CloakBrowser with the unpacked extension
  from `dist/chrome-mv3-dev`, persistent profile `.cloak-profile/`, maximized window, and
  opens `https://shopee.vn/`. The window stays open until Ctrl+C, so run it in the
  background (`run_in_background`), do NOT block waiting for it to exit. Make sure
  `dist/chrome-mv3-dev` exists (run `npm run build:dev` first if missing/stale).
- **Launcher**: `scripts/cloak-shopee-test.mjs`
  - `node scripts/cloak-shopee-test.mjs` — open `search?keyword=ipad`, auto-verify spy boxes
  - `node scripts/cloak-shopee-test.mjs "<keyword>"` — custom keyword
  - `node scripts/cloak-shopee-test.mjs --login` — just open Shopee to log in the profile
  - Loads the unpacked extension from `dist/chrome-mv3-dev` via `launchPersistentContext({ extensionPaths })`,
    mirrors content-script `[ASDBG]`/`CRAWLER` logs to the terminal, and reports how many
    spy boxes show real data vs the `???` empty state. Window stays open until Ctrl+C
    (graceful SIGINT closes the context and persists the profile).
- **Build first**: the launcher loads `dist/chrome-mv3-dev`, so run `npm run build:dev`
  (mode=development, keeps `console.log`, unminified) before testing. NOTE: `build:prod`/
  `build:chrome` strip nothing by config, but always rebuild after editing source — WXT
  outputs dev to `dist/chrome-mv3-dev` and prod to `dist/chrome-mv3`.

### Extension login account (test profile)

Tài khoản đăng nhập extension AutoShopee trong profile test: **`toannguyen` / `zxc123`**.
Dùng khi cần login lại extension (không phải login Shopee — Shopee login tự persist trong
`.cloak-profile/`). Login Shopee account là account cá nhân của user, đã lưu sẵn trong profile.

### Workflow tự phát triển + tự test (QUAN TRỌNG — áp dụng mặc định)

Khi user yêu cầu **fix bug** hoặc **bổ sung tính năng** cho extension, TỰ chạy trọn vòng
develop → build → test → verify → báo kết quả, KHÔNG dừng lại hỏi user test hộ:

1. **Debug/dev** — sửa source trong `src/`. Với bug fetch/parse Shopee, luôn dump shape API
   thật trước khi code (đừng đoán field).
2. **Build** — `npm run build:dev` (ra `dist/chrome-mv3-dev`). BẮT BUỘC rebuild sau mỗi lần
   sửa source; content script không HMR.
3. **Test tự động bằng CloakBrowser probe** — viết script tạm `scripts/.tmp-*.mjs` dùng
   `launchPersistentContext({ userDataDir: '.cloak-profile', extensionPaths: ['dist/chrome-mv3-dev'], headless:false, args:['--start-maximized'] })`,
   `page.goto('https://shopee.vn/search?keyword=...')`, chờ ~15s, rồi `page.evaluate` đọc DOM
   spy box (`[id^="autoshopee_product_search"]`) + `page.on('response')` bắt body
   `/api/v4/search/search_items` để so field. In REPORT + VERDICT PASS/FAIL. Xoá script
   `.tmp-*` sau khi xong.
4. **Verify** — chỉ báo "done" khi probe PASS. Nếu cần user nhìn bằng mắt thì
   `node scripts/start-browser.mjs` (mở cửa sổ, chạy `run_in_background`, Ctrl+C tắt).
5. **Dọn + commit** — xoá file `.tmp-*`, gỡ debug (alert/console.log/probeLog), lint file đã
   sửa, commit chọn lọc (chỉ file mình động tới).

**Lưu ý CloakBrowser đã rút ra (2026-07):**
- `.cloak-profile` chỉ **1 instance** dùng được cùng lúc. Launch báo *"Opening in existing
  browser session"* → kill CloakBrowser cũ trước:
  `Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | ? { $_.CommandLine -like '*cloak-profile*' } | % { Stop-Process $_.ProcessId -Force }`.
- Playwright `page.on('console')` **KHÔNG bắt được** `console.log` của content script
  (isolated world). Muốn đọc log content script phải ghi ra DOM element rồi `page.evaluate`
  đọc, hoặc `page.on('response')` cho data fetch.
- **KHÔNG dùng `alert()` để debug** trong content script — `observeUrlChange` interval 1s có
  thể bắn alert liên tục → dialog storm chặn page. Dùng `console.log` + đọc qua DOM.
- Mục cũ *"anti-crawler error 90309999 → CloakBrowser là false negative"* **đã lỗi thời**:
  phiên 2026-07 profile `.cloak-profile` đã được Shopee trust, `search_items` trả
  `error:null` + items thật. CloakBrowser giờ là **ground truth dùng được** cho search spy —
  nhưng vẫn check `body.error` khi nghi ngờ, đừng tin mù. Nếu bị flag lại thì mới fallback
  sang real Chrome (claude-in-chrome MCP).
- **Nhánh inject của `excuteFetchUrl`** (`src/app/api/shopee/fetch.js`) bị **CSP Shopee chặn**
  trên trang search (`Executing inline script violates CSP`) → primary fetch chết, data về
  nhờ fallback replay headers (webRequest listener). Đừng ngạc nhiên khi thấy CSP error.

## Architecture

### Entry Points (WXT file-based)
- **Popup**: `entrypoints/popup/main.js` — extension popup UI
- **Options**: `entrypoints/options/main.js` — full options/settings page
- **Background**: `entrypoints/background.js` — wraps `src/background/index.js`
- **Content Scripts**: `entrypoints/*.content.js` — wrappers that import logic from `src/content/`

### Path Aliases
- `@` → `src/app/`
- `@content` → `src/content/`
- `@background` → `src/background/`
- `@type` → `src/app/types/`

### Source Structure (`src/app/`)
- `api/` — HTTP clients per platform (Shopee, Lazada, TikTok, AutoShopee internal API). Uses Axios.
- `bridge/` — webext-bridge wrappers for messaging between background, content scripts, and popup/options
- `store/` — Vuex store (primary state management)
- `pinia/` — Pinia stores (supplementary, for shop/seller/usage/settings)
- `components/` — Vue components organized by platform (Shopee/, Lazada/, Tiktok/) and function (Layout/, Plugin/, Widget/)
- `views/` — Vue pages/views organized by platform
- `router/` — Vue Router configuration
- `plugins/` — Vue plugins: i18n, logger, KV storage, settings
- `models/` — Data models for products, orders, shops
- `service/` — Business logic services
- `adapter/` — Platform adapters (Shopee, TikTok)
- `types/` — JSDoc type definitions (all types go here, not inline)
- `validator/` — Joi validation schemas
- `socket/` — Socket.io real-time communication
- `lib/` — Utility functions
- `mixin/` — Vue mixins
- `constant/` — Constants and enums
- `data/` — Static data and templates

### Extension Communication
- **Background ↔ Content/Popup**: `webext-bridge` (`sendMessage`/`onMessage`)
- **Real-time sync**: Socket.io
- **Local DB**: PouchDB (syncs with CouchDB remote)
- **State persistence**: `vuex-persistedstate`, `pinia-plugin-persistedstate`

### Build System
- WXT 0.20.20 (Vite-based browser extension framework)
- `wxt.config.ts` defines manifest, aliases, and Vite plugins
- Content scripts are file-based entrypoints (`entrypoints/*.content.js`) — auto-detected by WXT
- HMR for popup/options pages, auto-reload for content scripts and background
- MV3 (Chrome) / MV2 (Firefox) handled automatically by WXT
- CI/CD via Drone (`.drone.yml`) — triggers on push to `dev` branch

## Code Conventions

- **Vue 2 Options API only** — no Composition API
- **JSDoc types only** — define all types in `src/app/types/`, use `@param {import('@/types/...')}` syntax. No inline type descriptions.
- **No inline comments** describing what code does
- **Braces required** for all `if` statements
- **No ternary operators** — use full `if/else` blocks
- **Each condition on its own line**
- **Do not split files** when refactoring — keep code in existing files
- **PascalCase** for component names, **camelCase** for props
- **UI framework**: View Design (iView for Vue 2)
- **CSS**: Tailwind CSS + SASS

## Design / Styling

**Before writing or changing ANY UI, read `docs/core/DESIGN.md`** — it is the authoritative style/CSS convention. Reference implementation: the Shopee Video cluster (`src/app/vue/views/Shopee/Video/*`).

Key rules (full detail in `docs/core/DESIGN.md`):
- **Component styles live in the SFC** under `<style lang="scss" scoped>`. Do NOT add to `src/app/vue/styles/app.css` unless it is a truly global utility/override.
- **BEM naming with a feature prefix** (e.g. `sv-` for Shopee Video): `block__element--modifier`. Dynamic state uses `is-*` classes (`is-active`, `is-done`, `is-error`, `is-pending`).
- **Color tokens = iView + Shopee brand palette** (Shopee `#ee4d2d`, link `#2d8cf0`, done `#19be6b`, error `#ed4014`, pending `#ff9900`, text `#1f2329`/`#515a6e`/`#8a8f99`/`#b0b4bb`). Do NOT invent hex values or use the legacy Element-UI palette in `app.css` (`#409EFF`, `#67C23A`…) for new UI.
- **Tokens**: radius `8px` (item) / `12px` (card) / `999px` (pill); card shadow `0 4px 16px rgba(17,24,39,0.06)`, hover `0 8px 22px rgba(17,24,39,0.08)`; spacing in multiples of 2/4; transitions `0.15–0.18s ease`.
- **Layout**: flexbox + `gap` (no floats). Card = `#fff` + radius 12px + standard shadow + 16px padding. Use `min-width:0` + ellipsis/line-clamp for long text.
- **i18n required**: all UI text via `$t('KEY')` (no hardcoded strings); money/numbers via `toLocaleString('vi-VN')`.
- **Override iView components** by chaining the `.ivu-*` class for specificity — do NOT use `!important`.
- Always provide empty / loading (`<Spin />`) / error states for lists; user feedback via `this.$Message.*`.

## Documentation

Project docs are organized in `docs/`:

### Index
- `docs/README.md` — project intro, current version, feature overview, full doc index
- `docs/core/DESIGN.md` — **authoritative UI/CSS design convention** (palette, BEM, tokens, layout) — read before any UI work

### Development (`docs/dev`)
- `docs/dev/README.md` — index of nested dev docs
- `docs/dev/overview/architecture.md` — extension architecture, data flow, messaging, state, database
- `docs/dev/overview/tech-stack.md` — framework/library versions and build tooling
- `docs/dev/overview/project-structure.md` — folder map, aliases, naming conventions, key files
- `docs/dev/workflow/development.md` — setup, build/package commands, env vars, workflow
- `docs/dev/workflow/codebase-rules.md` — ESLint, Prettier, Vue, JSDoc, CSS, build rules and naming conventions
- `docs/dev/workflow/screens.md` — all routes/views mapped with permissions
- `docs/dev/app/plugins.md` — Vue plugins, directives, filters, global mixins
- `docs/dev/app/stores.md` — Vuex modules + Pinia stores (state, getters, actions, persistence)
- `docs/dev/app/services.md` — business logic services (print, flash sale, shop, product)
- `docs/dev/app/settings.md` — settings system architecture, all setting groups
- `docs/dev/app/adapters.md` — platform data transformers (Shopee, TikTok, Lazada)
- `docs/dev/extension/background.md` — service worker init, events, shop detection, periodic tasks
- `docs/dev/extension/content-scripts.md` — lifecycle, injection, DOM patterns, IPC communication
- `docs/dev/extension/bridge.md` — webext-bridge message handlers and event flow
- `docs/dev/reference/constants.md` — constants, enums, storage keys, usage limits
- `docs/dev/reference/utilities.md` — utility functions (PDF, crypto, date, Excel, match)

### Business (`docs/business`)
- `docs/business/skills.md` — feature catalog organized by platform, plan, and status
- `docs/business/permissions.md` — plan-based access control and route matrix

### Shopee Features
- `docs/shopee/clone-product.md` — clone product from other shops, AI rewrite, watermark, cross-platform
- `docs/shopee/flash-sale.md` — bulk flash sale creation, scheduler, campaign, analytics
- `docs/shopee/send-message.md` — bulk messaging to customers (marketing automation)
- `docs/shopee/reply-rating.md` — auto-reply to customer ratings/reviews
- `docs/shopee/rating-order.md` — auto-rate completed orders with 5 stars
- `docs/shopee/ads.md` — ads campaign management and keyword optimization
- `docs/shopee/keyword.md` — keyword collection management for ads
- `docs/shopee/spy.md` — market research: spy products, shops, categories
- `docs/shopee/fetch-product-flow.md` — flow lấy sản phẩm Shopee (get_pc), bridge messaging, fetch qua content script
- `docs/shopee/fetch-data-flow.md` — cơ chế lấy dữ liệu Shopee qua webRequest listener (bắt headers thật) + webext-bridge (background/content/page)
- `docs/shopee/printer.md` — PDF order printing, template config, overlay
- `docs/shopee/push-product.md` — auto push product (coming soon)

### TikTok & Lazada
- `docs/tiktok/features.md` — TikTok clone, spy, print, content scripts
- `docs/lazada/features.md` — Lazada clone, print, affiliate, content scripts

### API Reference (`docs/dev/api`)
- `docs/dev/api/integrations.md` — external/internal APIs, socket, sync (overview)
- `docs/dev/api/shopee.md` — Shopee Seller/Client/Affiliate API endpoints
- `docs/dev/api/autoshopee.md` — AutoShopee REST API, Socket.io events, PouchDB/CouchDB sync
- `docs/dev/api/third-party.md` — TikTok, Lazada, GPT, Worker, KV Store APIs

### Plan
- `docs/plan/improvements.md` — prioritized improvement backlog (critical/high/medium/nice-to-have)
