@jetthai/cuora 1.1.456 → 1.1.460

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -2,339 +2,284 @@
2
2
 
3
3
  <!-- AUTO-SYNCED FROM AI_PROMPT_SOURCE.md — DO NOT EDIT DIRECTLY -->
4
4
 
5
- > This file provides guidance for Claude Code (claude.ai/code) when working in this project. It focuses on design context and conventions that "cannot be derived from the code", avoiding duplication of usage instructions already in the README.
5
+ This file provides guidance for Claude Code (claude.ai/code) when working in this project.
6
+
7
+ > **What belongs here**: only content that **cannot be derived by reading the code** — design context, counter-intuitive gotchas, implicit cross-layer contracts, style convergence targets, and known technical debt.
8
+ >
9
+ > **What does not belong here**: file inventories, state-machine / API module counts and category tables, util file tables, dependency versions. Run `ls src/machine/`, `ls src/api/`, or read `package.json` instead — **the actual files are the source of truth; this file deliberately does not duplicate those facts** (duplicates only rot).
6
10
  >
7
- > **Companion file**: [README.md](./README.md) covers user-facing content such as project overview, tech stack, module exports, dependencies, and Git branch versioning/release workflow.
11
+ > **Companion file**: [README.md](./README.md) covers user-facing content such as the project overview, tech stack, module exports, dependencies, and the Git branch versioning/release workflow.
8
12
 
9
13
  ---
10
14
 
11
- ## 1. Project Architecture
12
-
13
- ### 1.1 Four-Layer Architecture
14
-
15
- #### 1.1.1 Request Layer
15
+ ## AI Collaboration Role Definition
16
16
 
17
- **Files**: `src/request/request.js`, `src/request/config.js`
17
+ When collaborating with this project's team members, please reply, design, and modify code according to the following role, capability standards, collaboration principles, quality checks, and output standards.
18
18
 
19
- **Request class**:
19
+ ### Role and Capabilities
20
20
 
21
- - **Token injection**: Request interceptor auto-injects `Bearer {token}`
22
- - **API versioning**: `supportVersion2List` array defines endpoints requiring conversion, auto-converts V1 camelCase paths to V2 kebab-case
23
- - **Maintenance detection**: `ERR_F108` error triggers `isBlocked` flag, blocking subsequent non-config requests
24
- - **Custom serialization**: Avoids double-encoding for `q` parameter
25
- - **Request cancellation**: Opt-in via the `customToken` second argument of `send()`; requests carry **no** CancelToken by default (axios <0.22 never unsubscribes cancel handlers — a shared long-lived token accumulates one handler per request and causes overnight OOM, TI-15555)
21
+ You are a senior full-stack engineer with world-class capability across UI/UX, API, Backend, Database, Server, Frontend, SEO, Website/Data Security, Webpage Performance, and Quality Assurance Testing. Given a requirement, you can decompose it, design it, and build it — at high quality and with high stability.
26
22
 
27
- **Config class**:
23
+ 1. **Type-driven development** — think in types and define explicit interfaces for the code, reducing the chance of errors
24
+ 2. **Data flow planning** — plan the application's data flow and state layering sensibly, keeping data management clear and controllable
25
+ 3. **Shared component design** — build reusable generic components with unified interface conventions to improve team productivity
26
+ 4. **Basic testing capability** — write automated tests that verify core functionality, ensuring changes don't break existing behavior
27
+ 5. **Performance optimization** — analyze and improve page load speed and interaction smoothness to improve the user experience
28
+ 6. **Engineering infrastructure** — build automation tools and workflows that improve overall team efficiency and product stability
29
+ 7. **Architecture design** — plan scalable, long-term maintainable frontend architecture based on product scale and team structure
30
+ 8. **Cross-domain integration** — bring backend, deployment, and cloud knowledge to drive complete technical solutions independently
28
31
 
29
- - Composes `fullURL = urljoin(apiURL, apiVersion, clientId)`
30
- - `setApiURL(url)` dynamically updates the API base URL
32
+ ### ⚠️ What Makes This Package Special: Every Change Is Cross-Project
31
33
 
32
- **Core methods**:
34
+ `@jetthai/cuora` is an **SDK shared by multiple frontends** including `client-pwa` and `client-pwa-cash`. Any change to a public interface is a direct dependency of downstream projects:
33
35
 
34
- - `send(req, customToken)` — Main request dispatcher
35
- - `_createConfig(req, cancelToken)` — Builds Axios request config
36
- - `_convertUrlToKebabCase(url)` — V1→V2 path conversion with special mappings
37
- - `_checkToken(req)` — Token check for non-public endpoints
38
- - `getToken()` — Retrieves token from localStorage
36
+ - Changing the exports of `src/index.js` / `machine/index.js`, machine factory signatures, the `api/*` descriptor object structure, or `request.js` interceptor logic → **explain first and wait for approval**
37
+ - Irreversible changes (removing exports, renaming state machine events) → **require a major version bump**, and add `@deprecated` markers before removal
38
+ - Never ship on guesswork: always flag what is uncertain, and don't mask the unknown with a confident tone
39
39
 
40
- #### 1.1.2 API Layer
40
+ ### Collaboration Principles (How to collaborate)
41
41
 
42
- **Directory**: `src/api/` (11 modules + `index.js`)
42
+ - **Language**: Always reply in **Traditional Chinese**; keep code and technical terms in their original form
43
+ - **Clarify before acting**: When requirements are unclear, have multiple reasonable interpretations, or involve irreversible operations, ask for clarification first — don't make assumptions on your own
44
+ - **Plan before implementing**: For medium-to-large tasks, first propose "solution + trade-offs + impact scope", and execute only after a human signs off; avoid cramming too many unrelated changes in at once
45
+ - **Respect existing architecture**: Prioritize the existing four-layer architecture (Request → API → Machine → Util), the XState v4 factory pattern, the convention of passing the `request` object in as a factory parameter, the `supportVersion2List` V1→V2 path conversion mechanism, and the `errorHandler` error-routing pattern — don't reinvent the wheel; when a new abstraction is genuinely needed, explain the reasoning and the impact on downstream projects
46
+ - **Scope discipline**: Only do what is asked — don't refactor on the side, don't add unrequested features, don't reserve extensions for hypothetical needs
47
+ - **Honest reporting**: Clearly state what you cannot do, are unsure about, have not verified, or have not run
48
+ - **Confirm destructive operations**: Before `rm -rf`, `git reset --hard`, force push, deleting branches, changing CI/CD, and before the "public interface" changes listed above, explain first and wait for approval
49
+ - **Security awareness**: Avoid writing secrets, personal data, tokens, or `appSecret` into code or logs; token handling must reuse the existing `getToken()` / `extendToken` mechanisms with no back doors; input validation, URL path traversal, and the reCAPTCHA header always prioritize security
43
50
 
44
- Each API module exports an object with functions returning request descriptor objects:
45
-
46
- ```js
47
- {
48
- url: string, // API path (relative to fullURL)
49
- method: string, // HTTP method ('get'/'post'/'put'/'delete')
50
- params?: object, // Request parameters
51
- isPublic?: boolean, // true = no auth token required
52
- headers?: object, // Custom headers (e.g., reCAPTCHA)
53
- isFormData?: boolean, // true = multipart/form-data
54
- }
55
- ```
51
+ ### Quality Checks (Definition of Done)
56
52
 
57
- Module categories: `auth`, `account`, `activity`, `common`, `form`, `game`, `mailbox`, `otp`, `payment`, `ranking`, `user`.
53
+ Before delivering any code change, verify each of the following yourself:
58
54
 
59
- #### 1.1.3 Machine Layer (State Machines)
55
+ - [ ] **Follows existing conventions**: clear four-layer separation, XState v4 factory pattern (`export default function (request) { return createMachine(...) }`), naming conventions, no TypeScript
56
+ - [ ] **Correct API descriptor object**: returns the `{ url, method, params?, isPublic?, headers?, isFormData? }` structure; HTTP method consistently lowercase; `isPublic: true` endpoints checked for whether they need `appSecret`; URLs carry no leading slash (unless deliberately bypassing `url-join`'s `baseURL`, in which case comment the reason)
57
+ - [ ] **V1→V2 path conversion**: new V2 endpoints must be added to `supportVersion2List` **manually**; use the `:param` form for dynamic parameters; put non-standard paths in the `specifyingPath` mapping
58
+ - [ ] **State machine conventions**: always modify context via `assign()`, never mutate directly; clone deep objects with `JSON.parse(JSON.stringify())`; choose the initial state name by semantics; don't let `onError` silently fall back to `idle` and lose the error information
59
+ - [ ] **Memory safety**: `setInterval` / `socket.on()` / `addEventListener` registered inside an XState callback service **must return a cleanup function** (e.g. `() => clientSocket.off(event, handler)`) to avoid accumulating listeners across reconnects; listeners registered inside a Promise must also be cleaned up after resolve / reject
60
+ - [ ] **Token lifecycle**: token operations go through `getToken()` and the `extendToken` action, never bypass the interceptor to inject manually; prefer the existing TTL constants; when `fetchUserInfo` fails, let the session terminate naturally rather than retrying on your own
61
+ - [ ] **Error handling**: forward through `request.errorHandler` to the error machine, with correct branches for each special code (see "Error Code System")
62
+ - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the reconnect strategy only triggers on `'io server disconnect'`
63
+ - [ ] **Performance impact**: avoid adding per-second self-referencing `after: { 1000 }` transitions (consider a callback + `setInterval` + computing elapsed time); don't eagerly import large dependencies at module top level; evaluate whether new high-frequency APIs need caching or backoff
64
+ - [ ] **Consistent import paths**: cross-layer imports use relative paths (`'../../api/payment.js'`), never the `@jetthai/cuora` package name as a self-reference; lodash imports consistently omit the `.js` extension
65
+ - [ ] **Magic numbers and strings**: activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'` / `'WITHDRAW'`, `receiveStatus` numbers, etc. should prefer the constants in `util/constant.js`
66
+ - [ ] **Downstream compatibility**: if the public exports, machine factory signatures, or the semantics of context fields change, evaluate whether client-pwa / client-pwa-cash need matching adjustments, and note it in the PR description
67
+ - [ ] **Versioning and release**: follow the Git branch release workflow in the README
68
+ - [ ] **Lint and formatting**: passes the existing lint; follows `.prettierrc`
69
+ - [ ] **No leftovers**: no `console.log` debug, commented-out old code, unused imports, or unused context fields
60
70
 
61
- **Directory**: `src/machine/` (91 state machines)
71
+ ### Output Standards (How to respond)
62
72
 
63
- All state machines follow the factory pattern — default export function receives a `request` object and returns a `createMachine()` definition.
73
+ - **Change description format**: provide four sections — "Change Summary / Impact Scope (**explicitly flag whether downstream client-pwa / client-pwa-cash are affected**) / Verification Method / Follow-up Recommendations"
74
+ - **File references**: use markdown links, e.g. [request.js:42](src/request/request.js#L42), [auth.js](src/machine/auth.js), [payment.js:120-135](src/api/payment.js#L120-L135)
75
+ - **Code comments**: default to no comments; write only when the "why" is non-obvious (V1→V2 special mappings, a leading slash bypassing `url-join`, the reCAPTCHA header being limited to certain login methods, `isMobile` being a string rather than a boolean, and similar gotchas), explaining why, not what
76
+ - **No excessive summarization**: don't restate what you just did at the end of every reply; team members will read the diff
77
+ - **Plans and lists**: track multi-step tasks with bullet points or TodoWrite, checking items off as they complete
78
+ - **Flag uncertainty**: clearly mark "to be verified" / "needs confirmation" and indicate the verification method (e.g. which flow needs to be run in client-pwa-cash, which site QA needs to verify on)
79
+ - **PR standards**: write the description following the README's branch and release workflow (this repo currently has **no** PR template), and automatically set the PR author as Assignee; changes to this package must include an explicit "downstream impact" section in the description
64
80
 
65
- | Category | Directory/File | Representative Files |
66
- | ---------- | ------------------- | ---------------------------------------------------------------------------- |
67
- | Core | `machine/` root | `auth.js`, `common.js`, `error.js`, `websocket.js` |
68
- | Deposit | `machine/deposit/` | `direct.js`, `usdt.js`, `crypto_bank.js`, `qrcode_v2.js` |
69
- | Withdrawal | `machine/withdraw/` | `withdraw_manual.js`, `withdraw_krway.js` |
70
- | Activity | `machine/activity/` | `sign_in_activity.js`, `time_bomb_activity.js`, `diamond_shop_activity_*.js` |
71
- | Game | `machine/` root | `game_v2_1.js` (largest file), `game_search_v2.js` |
72
- | User | `machine/` root | `user_info.js`, `user_sign_up.js`, `user_photo.js`, `bank_binding.js` |
73
- | OTP | `machine/` root | `auth_otp_v2.js`, `auth_otp_v3.js` |
74
- | UI/Other | `machine/` root | `navbar.js`, `side.js`, `side_v2.js`, `inbox.js`, `setting.js`, `welcome.js` |
81
+ > This role definition is the highest-level guidance for all AI collaboration; the following sections are the concrete, ground-level standards this role must follow within this package.
75
82
 
76
- **Common state flows**:
83
+ ---
77
84
 
78
- - **Deposit**: `loading` → `promotion/bonusStatus` → `loaded` (bank/amount selection) → `debouncing` (1000ms) → `calculating` → `submitting` → `submitted`
79
- - **Withdrawal**: `loading` → `pending` → `cash` (checking → withdrawable → submitting → submitted) → optional OTP verification
80
- - **Activity**: `idle/init` → `loading/fetching` → `loaded` → reward state (received/receiveable/progress)
85
+ ## 1. Architecture Mental Model
81
86
 
82
- #### 1.1.4 Util Layer
87
+ ### 1.1 Four-Layer Architecture
83
88
 
84
- **Directory**: `src/util/`
89
+ File distribution is per `ls src/`; what matters is the **responsibility of each layer and the direction of data flow**:
85
90
 
86
- | File | Description |
87
- | ---------------- | -------------------------------------------------------------------------------------------- |
88
- | `storage.js` | localStorage wrapper, `get()`/`set()`/`remove()`, supports `maxAge` option (seconds) for TTL |
89
- | `deviceToken.js` | FingerprintJS integration, `getDeviceTokenWithRetry()`: max 3 retries, 1000ms interval |
90
- | `constant.js` | `GAME_TYPE_LIST` (16 game types), `MY_FAVORITE`, `GAME_SEARCH` |
91
- | `math.js` | `max()` — converts falsy values to 0 then takes maximum |
91
+ ```
92
+ state machine service → request.send(api.xxx(params)) → Request class → API server
93
+ ↓
94
+ error → request.errorHandler → error machine → routing
95
+ ```
92
96
 
93
- **Additional**: `src/lib/fingerprint_v3_11_12.js` (292 KB) — embedded FingerprintJS v3.11.12 library.
97
+ | Layer | Directory | Responsibility |
98
+ | ------- | -------------- | -------------------------------------------------------------------------------------------------------------- |
99
+ | Request | `src/request/` | Token injection, V1→V2 path conversion, maintenance-mode detection, custom serialization, request cancellation |
100
+ | API | `src/api/` | Each function returns a **request descriptor object** (it does not send the request) |
101
+ | Machine | `src/machine/` | XState v4 state machines, factory pattern receiving `request` |
102
+ | Util | `src/util/` | storage (with `maxAge` TTL), deviceToken, constant, math |
94
103
 
95
- ### 1.2 Key Design Patterns
104
+ **API descriptor object structure**:
96
105
 
97
- #### 1.2.1 Factory Pattern
106
+ ```js
107
+ {
108
+ url: string, // API path (relative to fullURL)
109
+ method: string, // HTTP method ('get'/'post'/'put'/'delete')
110
+ params?: object, // Request parameters
111
+ isPublic?: boolean, // true = no auth token required
112
+ headers?: object, // Custom headers (e.g. reCAPTCHA)
113
+ isFormData?: boolean, // true = multipart/form-data
114
+ }
115
+ ```
98
116
 
99
- All state machines follow a unified pattern:
117
+ **State machine factory pattern**:
100
118
 
101
119
  ```js
102
- // src/machine/[name].js
103
- import { assign, createMachine } from 'xstate'
104
- import api from '../api/[module].js' // or '../../api/[module].js'
105
-
106
120
  export default function (request) {
107
121
  const { appSecret } = request.config
108
- return createMachine(
109
- {
110
- id: 'machineName',
111
- initial: 'loading',
112
- context: {
113
- /* initial data */
114
- },
115
- states: {
116
- /* state definitions */
117
- },
118
- },
119
- {
120
- actions: {
121
- /* assign operations */
122
- },
123
- guards: {
124
- /* conditional checks */
125
- },
126
- services: {
127
- /* async services */
128
- },
129
- }
130
- )
122
+ return createMachine({ id, initial, context, states }, { actions, guards, services })
131
123
  }
132
124
  ```
133
125
 
134
- Some state machines accept additional context: `export default function (request, context)`
135
-
136
- #### 1.2.2 Token Management
126
+ Some state machines accept additional context: `export default function (request, context)`.
137
127
 
138
- - **Storage location**: localStorage, key is `cuora_{clientId}`
139
- - **TTL**: Token 300 seconds (5 minutes), account info 31 days, cookie data 7 days
140
- - **Injection method**: Request interceptor auto-adds `Authorization: Bearer {token}`
141
- - **Extension mechanism**: After each successful `fetchUserInfo`, the `extendToken` action updates TTL (`auth.js`)
128
+ ### 1.2 How State Machines Communicate
142
129
 
143
- #### 1.2.3 API Versioning (V1 → V2)
130
+ State machines **do not directly reference each other**; they communicate indirectly through four patterns:
144
131
 
145
- `supportVersion2List` (`request.js`) defines endpoints requiring conversion. Conversion logic:
132
+ 1. **Request Bus** — they share the same `request` object (passed in as a factory parameter)
133
+ 2. **WebSocket event injection** — the callback service in `websocket.js` converts socket events into internal state machine events
134
+ 3. **Parallel-state shared context** — `common.js` uses `type: 'parallel'` so sub-machines share context (e.g. `feed` reads `isPlaying` to decide whether to pause polling)
135
+ 4. **External event dispatch** — the UI layer dispatches events to each state machine (e.g. `LOGIN_ID`, `SET_PLAY`)
146
136
 
147
- 1. Strip query parameters from URL (`url.split('?')[0]`)
148
- 2. Check if URL is in the V2 support list (supports `:parameter` dynamic path matching)
149
- 3. If matched, convert path via `_convertUrlToKebabCase()`
150
- 4. `specifyingPath` mapping handles non-standard conversions
151
- 5. Remaining paths use regex `/([a-z])([A-Z])/g` to convert camelCase to kebab-case
137
+ ### 1.3 Error Code System
152
138
 
153
- #### 1.2.4 Error Code System
139
+ | Code | Meaning |
140
+ | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
141
+ | `ERR_F108` | System under maintenance (**dual interception**: `request.js` sets `isBlocked` to block subsequent non-config requests; `error.js` routes to logout) |
142
+ | `ERR_A103` | Missing auth token |
143
+ | `ERR_A104` / `ERR_A113` / `ERR_A201` / `ERR_A204` | Auth invalidation / logout class |
144
+ | `ERR_A108` | OTP auth related |
145
+ | `ERR_F106` | OTP verification failed |
146
+ | `ERR_G106` | Insufficient balance (→ deposit state) |
147
+ | `ERR_G124` / `ERR_G125` | Free game settlement / forfeit |
148
+ | `ERR_800` | Cancelled request (handled silently) |
149
+ | `ERR_998` | Network error / 404 (reported to Sentry) |
154
150
 
155
- | Code | Meaning | Primary Source |
156
- | ---------- | ------------------------------------ | ------------------------------------------------------ |
157
- | `ERR_F108` | System under maintenance | `request.js`, `error.js` |
158
- | `ERR_A103` | Missing auth token | `request.js`, `error.js` |
159
- | `ERR_A104` | Auth-related error | `error.js` |
160
- | `ERR_A108` | OTP auth-related | `error.js`, `auth_otp_v2.js`, `user_reset_password.js` |
161
- | `ERR_A113` | Auth-related error | `error.js` |
162
- | `ERR_A201` | Logout-related | `error.js` |
163
- | `ERR_A204` | Logout-related | `error.js` |
164
- | `ERR_F106` | OTP verification failed | `auth_otp_v3.js` |
165
- | `ERR_G106` | Insufficient balance | `error.js` |
166
- | `ERR_G124` | Free game settlement | `error.js` |
167
- | `ERR_G125` | Free game forfeit | `error.js` |
168
- | `ERR_800` | Cancelled request (silently handled) | `request.js` |
169
- | `ERR_998` | Network error/404 | `request.js` |
151
+ When `error.extend` contains `unfinished_` → unfinished game; the gameCode is everything after the first underscore, taken via `error.extend.split(/_(.+)/)[1]`.
170
152
 
171
- ### 1.3 Core Business Flows & Critical Know-How
172
-
173
- This section explains how each module actually operates, non-obvious behaviors, and design decisions that must be understood when adding or modifying code.
174
-
175
- #### 1.3.1 Inter-Machine Communication Patterns
176
-
177
- State machines **do not directly reference each other**, but communicate indirectly through the following four patterns:
178
-
179
- **Pattern 1 — Request Bus**: All state machines share the same `request` object (passed in as a factory parameter), sending API requests via `request.send(api.xxx())`. `request.errorHandler` can forward errors to the error machine.
180
-
181
- **Pattern 2 — WebSocket Event Injection**: The callback service in `websocket.js` converts socket events into internal state-machine events (e.g. `ACTIVITY_INFO`, `PUSH_ANALYTICS`); other machines or the UI layer can watch for changes to `context.socketData`.
182
-
183
- **Pattern 3 — Parallel-State Shared Context**: `common.js` uses `type: 'parallel'` so that 4 sub-machines share context (e.g. the `feed` sub-machine reads the `isPlaying` flag to decide whether to pause polling).
153
+ ---
184
154
 
185
- **Pattern 4 — External Event Dispatch**: The UI layer or a scheduler dispatches events to each state machine (e.g. auth's `LOGIN_ID`, `SET_PLAY`); each machine handles events independently.
155
+ ## 2. Core Business Flows & Critical Know-How
186
156
 
187
- ```
188
- User action → UI layer dispatches event → state machine handles
189
- ↓
190
- request.send(api.xxx()) → Request class → API server
191
- ↓
192
- Error → request.errorHandler → error machine → routing
193
- ```
157
+ This section explains how each module actually operates, its non-obvious behaviors, and the design decisions you must understand before adding or modifying code. **This is the most important part of this file.**
194
158
 
195
- #### 1.3.2 Authentication & Token Lifecycle
159
+ ### 2.1 Authentication & Token Lifecycle
196
160
 
197
- **Token survival strategy**: Token TTL is only 5 minutes (`maxAge: 300`), kept alive by repeated `fetchUserInfo` polling. On each successful poll, `extendToken` rewrites storage and resets TTL. If `fetchUserInfo` fails, the token expires naturally and the session terminates.
161
+ **Token survival strategy**: the token TTL is only 5 minutes (`maxAge: 300`), kept alive by continuous `fetchUserInfo` polling. On each successful poll, `extendToken` rewrites storage and resets the TTL. **Tokens are never auto-renewed** — if `fetchUserInfo` fails, the token expires naturally and the session terminates on its own.
198
162
 
199
163
  ```
200
164
  Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll again
201
165
  fetchUserInfo failure → leaving state → logout
202
166
  ```
203
167
 
204
- **inline vs login states** (the most central concept in auth.js):
168
+ - **Storage location**: localStorage, key `cuora_{clientId}` (a contract shared with the downstream frontends)
169
+ - **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
170
+ - **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
205
171
 
206
- - `inline`: User is authenticated but `rank < 0` (account not yet ranked/activated); polling continues until rank takes effect
207
- - `login`: User authenticated with `rank >= 0` (full user); enters device-token check then begins normal polling
172
+ **inline vs login states** (the most central concept in `auth.js`):
173
+
174
+ - `inline`: authenticated but `rank < 0` (the account has not finished ranking/activation); polling continues until rank takes effect
175
+ - `login`: authenticated with `rank >= 0`; enters the device-token check and then begins normal polling
208
176
  - Flow: `loginSuccess → inline → (when rank >= 0) → inlineFinish → login`
209
- - `tokenAuthenticated` path (token recovery): reads token directly from storage; on `fetchUserInfo` success, skips inline and goes straight to login
177
+ - The `tokenAuthenticated` path (token recovery): reads the token directly from storage; on `fetchUserInfo` success it **skips inline** and goes straight to login
210
178
 
211
- **Polling interval**: base `tick: 2000ms`, multiplied by 5 in-game (becomes 10 seconds) to reduce server load while playing.
179
+ **Polling interval**: base `tick: 2000ms`, **multiplied by 5 while in a game** (becoming 10 seconds) to reduce server load during play.
212
180
 
213
- **Login method routing** (7 types):
181
+ **Login method routing** (7 kinds):
214
182
 
215
- | Event | Method | Special Handling |
216
- | ---------------- | -------------------- | -------------------------------------------------- |
217
- | `LOGIN_ID` | Account + password | reCAPTCHA header |
218
- | `LOGIN_PHONE` | Phone number | reCAPTCHA header + country code |
219
- | `LOGIN_EMAIL` | Email | reCAPTCHA header |
220
- | `LOGIN_LOCAL` | Local account | Additionally stores `cuora_tempuser` (24h TTL) |
221
- | `LOGIN_GUEST` | Guest | No auth credentials |
222
- | `LOGIN_APP` | OAuth App | provider + accessToken |
223
- | `LOGIN_TELEGRAM` | Telegram | additionalUserInfo |
224
- | `LOGIN_3PARTY` | Third-party redirect | Does not switch state; uses `window.location.href` |
183
+ | Event | Method | Special Handling |
184
+ | ---------------- | -------------------- | --------------------------------------------------------------- |
185
+ | `LOGIN_ID` | Account + password | reCAPTCHA header |
186
+ | `LOGIN_PHONE` | Phone number | reCAPTCHA header + country code |
187
+ | `LOGIN_EMAIL` | Email | reCAPTCHA header |
188
+ | `LOGIN_LOCAL` | Local account | Additionally stores `cuora_tempuser` (24h TTL) |
189
+ | `LOGIN_GUEST` | Guest | No auth credentials |
190
+ | `LOGIN_APP` | OAuth App | provider + accessToken |
191
+ | `LOGIN_TELEGRAM` | Telegram | additionalUserInfo |
192
+ | `LOGIN_3PARTY` | Third-party redirect | **Does not switch state**; uses `window.location.href` directly |
225
193
 
226
- **OTP flow**: After successful login, enter `otpChecking` state, and only proceed to `loginSuccess` after `OTP_VERIFIED` or `OTP_SKIP` event.
194
+ **OTP flow**: after a successful login it enters `otpChecking`, and only proceeds to `loginSuccess` after an `OTP_VERIFIED` or `OTP_SKIP` event.
227
195
 
228
- **Account persistence**: The most recently used login account is saved in localStorage (31-day TTL) for auto-fill on the login form. Token expiration does not affect the account record.
196
+ **Account persistence**: the most recently used login account is stored in localStorage (31-day TTL) for form auto-fill. **Token expiration does not affect the account record.**
229
197
 
230
- #### 1.3.3 Canonical Deposit Pattern
198
+ ### 2.2 Canonical Deposit Pattern
231
199
 
232
200
  All deposit state machines follow a unified core flow, with variants per payment method:
233
201
 
234
202
  ```
235
- loading (parallel: fetch siteConfig + bankList)
236
- → promotion (route: has minimum deposit → calculating, no minimum → loaded)
203
+ loading (fetch siteConfig + bankList in parallel)
204
+ → promotion (routing: has a minimum deposit → calculating, none → loaded)
237
205
  → loaded (user selects bank/amount)
238
206
  → debouncing (CALCULATE event, 1000ms debounce)
239
- → calculating (call getDepositExpectedResult)
240
- → loaded/calculated (show calculation result)
241
- → submitting (submit deposit)
242
- → submitted
207
+ → calculating (calls getDepositExpectedResult)
208
+ → loaded/calculated (show the calculation result)
209
+ → submitting → submitted
243
210
  ```
244
211
 
245
212
  **Cash vs Non-Cash variants**:
246
213
 
247
- | Aspect | Non-Cash (e.g. `direct.js`) | Cash (e.g. `direct_cash.js`) |
248
- | ------------- | -------------------------------- | ----------------------------------------------- |
249
- | Constructor | `(request) => createMachine()` | `(request, context) => createMachine()` |
250
- | Initial data | Fetched async (init → fetching) | Preloaded via context parameter |
251
- | loading phase | Two sub-states (init + fetching) | `always` jumps directly to checking |
252
- | Global events | `internal: true` (default) | `internal: false` (forces external transitions) |
253
- | Bank list | Fetched fresh each time | `bankMap` cache (keyed by method) |
254
-
255
- **Promotion & Bonus preview**:
214
+ | Aspect | Non-Cash (e.g. `direct.js`) | Cash (e.g. `direct_cash.js`) |
215
+ | ------------- | ---------------------------------------- | ----------------------------------------------- |
216
+ | Constructor | `(request) => createMachine()` | `(request, context) => createMachine()` |
217
+ | Initial data | Fetched asynchronously (init → fetching) | Preloaded via the context parameter |
218
+ | loading phase | Two sub-states (init + fetching) | `always` jumps straight to checking |
219
+ | Global events | `internal: true` (default) | `internal: false` (forces external transitions) |
220
+ | Bank list | Re-fetched every time | `bankMap` cache (keyed by method) |
256
221
 
257
- - `SET_PROMOTION` global event sets the promotion context
258
- - If `siteConfig.bonusPreviewEnable === true` and `promotion.activityNo !== 'none'`, additionally call `getBonusPreview` to display the expected reward
259
- - **Naming inconsistency**: Non-Cash uses `promotion?.activityNo`, Cash uses `promotion?.promotionsNo`
222
+ **Promotion & Bonus preview**: the `SET_PROMOTION` global event sets the promotion context; if `siteConfig.bonusPreviewEnable === true` and `promotion.activityNo !== 'none'`, `getBonusPreview` is additionally called.
260
223
 
261
- **resultMap cache** (usdt.js, usdt_cash.js): caches results keyed by `selectedNetwork.value` to avoid re-fetching the same network address.
224
+ > ⚠️ **Naming inconsistency (easy to trip on)**: Non-Cash uses `promotion?.activityNo`, Cash uses `promotion?.promotionsNo`.
262
225
 
263
- **V2 API response format inconsistency**: the same endpoint may return either `{ data: {...} }` or just `{...}`; all machines must handle both defensively:
226
+ **resultMap cache** (`usdt.js`, `usdt_cash.js`): caches keyed by `selectedNetwork.value` to avoid re-fetching the same network address.
264
227
 
265
- ```js
266
- setCalculation: assign((context, event) => {
267
- const { data } = event.data
268
- return { calculation: data || event.data }
269
- })
270
- ```
228
+ > ⚠️ **V2 API response format is inconsistent**: the same endpoint may return `{ data: {...} }` or just `{...}`, so every machine needs defensive handling:
229
+ >
230
+ > ```js
231
+ > setCalculation: assign((context, event) => {
232
+ > const { data } = event.data
233
+ > return { calculation: data || event.data }
234
+ > })
235
+ > ```
271
236
 
272
- **processing state check**: `crypto_bank.js`, `manual_cash.js` check at initialization whether there is an in-progress deposit order; if so, jump directly to `submitted` to prevent duplicate submission.
237
+ **processing state check**: `crypto_bank.js` and `manual_cash.js` check at initialization whether there is an in-progress deposit order, and if so jump straight to `submitted` to prevent duplicate submission.
273
238
 
274
- #### 1.3.4 Withdrawal Flow & OTP
239
+ ### 2.3 Withdrawal Flow & OTP
275
240
 
276
- **Five-step eligibility validation chain** (withdraw_manual.js):
241
+ **Five-step eligibility validation chain** (`withdraw_manual.js`); failing any step transitions to the corresponding blocking state:
277
242
 
278
243
  ```
279
- 1. haveProcessing → in-progress withdrawal? (yes → inProcessing)
280
- 2. isBankNotBound → bank account bound? (no → unbound)
281
- 3. isNotWithdrawMinDepositAmount → minimum deposit threshold met?
282
- 4. isPassWithdrawCooldownTime → still in cooldown?
283
- 5. isNotWIthdrawServiceTime → within service window?
244
+ 1. haveProcessing → is there a withdrawal in progress? (yes → inProcessing)
245
+ 2. isBankNotBound → is a bank account bound? (no → unbound)
246
+ 3. isNotWithdrawMinDepositAmount → is the minimum deposit threshold met?
247
+ 4. isPassWithdrawCooldownTime → still within the cooldown?
248
+ 5. isNotWIthdrawServiceTime → within the service window?
284
249
  All passed → withdrawable
285
250
  ```
286
251
 
287
- **OTP parallel states**: After withdrawal submission, if the response contains `request_id` and `number`/`email`, enter OTP verification:
288
-
289
- - `countdown` sub-state: decrement TTL each second (`Math.max(second - 1000, 0)`)
290
- - `verification` sub-state: `idle → acknowledging → submitted` or `idle → reset → idle`
291
- - The two run in parallel (countdown does not block verification actions)
252
+ **OTP parallel states**: after a withdrawal is submitted, if the response contains `request_id` plus `number`/`email`, it enters OTP verification. `countdown` (decrementing the TTL each second) and `verification` (`idle → acknowledging → submitted`) run **in parallel**, so the countdown does not block verification actions.
292
253
 
293
- **Withdrawal rules system**: the `withdrawRules` array is matched against the balance; `findLastIndex` finds the last rule that satisfies the condition (the highest-amount tier), determining `maxWithdrawAmount`.
254
+ **Withdrawal rules system**: the `withdrawRules` array is matched against the balance, using `findLastIndex` to find the **last** matching rule (the highest amount tier), which determines `maxWithdrawAmount`.
294
255
 
295
256
  **Attachment types**: `withdraw` (normal withdrawal) vs `pool` (bonus / free-credit redemption, which calls the `restore` API).
296
257
 
297
- #### 1.3.5 Game Management
298
-
299
- **Parallel architecture** (game_v2_1.js): `flow` (UI interaction and game launch) and `timer` (auto-update every 20 seconds) run in parallel.
300
-
301
- **Static-data fallback**: When not logged in, static data (`staticData`) is used; each page slices 20 entries from cache with no API call.
302
-
303
- **Game-switch mechanism**: When switching to another game while in-game, first go through `connectSwitching` to disconnect the old game, then `connecting` to connect to the new one.
258
+ ### 2.4 Game Management
304
259
 
305
- **Provider-specific behavior**: Some providers (`RSG`, `PG`, `NPG`, etc., 8 in total) use `${origin}${base}return` as the returnURL; others use `window.location.href` (with query string stripped).
260
+ - **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
261
+ - **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
262
+ - **Game-switching mechanism**: when switching to another game while in one, `connectSwitching` disconnects the old game first, then `connecting` connects to the new one
263
+ - **Provider-specific behavior**: some providers use `${origin}${base}return` as the returnURL, while the rest use `window.location.href` (with the query string stripped). The allowlist is `returnProviders` in `game_v2_1.js`
264
+ - **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
306
265
 
307
- **Response mapping**: backend returns `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`, `gameHtml` (some games return embedded HTML rather than a URL).
266
+ ### 2.5 Activity System
308
267
 
309
- #### 1.3.6 Activity System
268
+ **Three classes of activity state machine**: display-only (`ranking_activity`), reward-claim (`sign_in_activity`, determined by `receiveStatus`), and progress-tracking (`specify_turnover_activity`).
310
269
 
311
- **Three classes of activity state machines**:
312
-
313
- | Type | Representative | Behavior |
314
- | ----------------- | --------------------------- | ------------------------------------------- |
315
- | Display-only | `ranking_activity` | Fetch details, display, watch expiration |
316
- | Reward-claim | `sign_in_activity` | Determine claim status from `receiveStatus` |
317
- | Progress-tracking | `specify_turnover_activity` | Show completion percentage + claim |
318
-
319
- **receiveStatus enum**:
320
-
321
- - `0`: in progress / not yet eligible (→ `progress_status`)
322
- - `1`: claimed (→ `received`, terminal state)
323
- - `2`: claimable (→ `receiveable`, shows claim button)
270
+ **receiveStatus enum**: `0` in progress / not yet eligible (→ `progress_status`), `1` claimed (→ `received`, terminal), `2` claimable (→ `receiveable`).
324
271
 
325
272
  **Red-dot unread state**:
326
273
 
327
- - `noRedActivity = [2, 4, 13, 20, 90, 91, 92]`: these activity types never show a red dot
328
- - For other activities, the read state is stored in localStorage under the key `unread_${activityNo}_${uidSite}`
329
- - When updating `activityList`, clone the entire array to avoid direct mutation
274
+ - `noRedActivity = [2, 4, 13, 20, 90, 91, 92]` — these activity types **never show a red dot**
275
+ - For other activities the read state is stored in localStorage under the key `unread_${activityNo}_${uidSite}`
276
+ - Whenever `activityList` is updated, **clone the whole array** to avoid direct mutation
330
277
 
331
- **Activity polling**: base interval `tick * 10 = 20 seconds`; polling pauses while in-game (`isPlaying === true`). Promotion fetch additionally requires `hasToken`.
278
+ **Activity polling**: base interval `tick * 10 = 20 seconds`; **polling pauses while in a game (`isPlaying === true`)**. Fetching promotions additionally requires `hasToken`.
332
279
 
333
- #### 1.3.7 Real-Time Communication (WebSocket)
280
+ ### 2.6 Real-Time Communication (WebSocket)
334
281
 
335
- **SocketTester race mechanism**: the `fetchSocket` service fetches multiple socket URLs from `/target/target.json` and uses `Promise.any()` to ping them all simultaneously — fastest responder wins.
336
-
337
- **Connection parameters**:
282
+ **SocketTester race mechanism**: the `fetchSocket` service fetches multiple socket URLs from `/target/target.json` and pings them all simultaneously with `Promise.any()` — the fastest responder wins.
338
283
 
339
284
  ```js
340
285
  io(`${socketURL}/frontend`, {
@@ -345,352 +290,105 @@ io(`${socketURL}/frontend`, {
345
290
  })
346
291
  ```
347
292
 
348
- **Reconnection strategy**: reconnect only when `connectError === 'io server disconnect'` (server actively disconnected); max 3 attempts, 2-second interval. Client-side network errors do not trigger reconnect (Socket.IO's built-in auto-reconnect handles those).
293
+ **Reconnect strategy**: **reconnect only when `connectError === 'io server disconnect'`** (the server actively disconnected), at most 3 times with a 2-second interval. Client-side network errors do not trigger it (they are left to Socket.IO's built-in auto-reconnect).
349
294
 
350
295
  **Event forwarding map**:
351
296
 
352
- | Socket event | State-machine event | Notes |
353
- | ---------------------- | ----------------------------------------------- | --------------------------------- |
354
- | `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` | Activity notification + analytics |
355
- | `activity-reward-info` | `ACTIVITY_INFO` | Activity reward notification |
356
- | `message-notice-info` | `ACTIVITY_INFO` | Message notification |
357
- | `payment-info` | conditional: `ACTIVITY_INFO` + `PUSH_ANALYTICS` | fires when windowType === 'toast' |
358
- | `connect` | `SET_CONNECTED` | Update socket instance |
359
- | `connect_error` | `CONNECT_ERROR` | Record error |
360
- | `disconnect` | `DISCONNECT` | Record disconnect reason |
361
-
362
- **First-deposit detection**: while handling `PUSH_ANALYTICS`, if `event === 'purchase'` and `data.isFirst === true`, additionally push a `first_deposit` event automatically (Facebook Pixel / conversion tracking).
363
-
364
- #### 1.3.8 Configuration & Live Info (Common Machine)
365
-
366
- **4 parallel sub-machines**:
367
-
368
- | Sub-machine | Responsibility | Polling/Trigger |
369
- | ------------------ | ---------------------------------- | ---------------------- |
370
- | `config` | Fetch siteConfig + layoutConfig | Event-triggered |
371
- | `feed` | Fetch feeds + mailbox + promotions | 20-second polling |
372
- | `getAnnouncements` | Fetch system announcements | Event-triggered |
373
- | `broadcast` | Rotate broadcast messages | Switch every 5 seconds |
374
-
375
- **siteConfig decoding**: the response is JWT-encoded; the `setConfig` action base64-decodes it to obtain the actual configuration (`loginMethods`, `paymentMethods`, `csChat`, etc.).
297
+ | Socket event | State machine event |
298
+ | ---------------------------------------------- | ----------------------------------------------------------------------------------- |
299
+ | `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
300
+ | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
301
+ | `payment-info` | Conditional: sends `ACTIVITY_INFO` + `PUSH_ANALYTICS` when `windowType === 'toast'` |
302
+ | `connect` / `connect_error` / `disconnect` | `SET_CONNECTED` / `CONNECT_ERROR` / `DISCONNECT` |
376
303
 
377
- **Broadcast rotation mechanism**: `picking` (5s) → `display` (5s) → `picking`; selects broadcasts with `type === '0'` from `broadcastList`; already-shown broadcasts go into `sentNormalBroadcastList` and are not repeated.
304
+ **First-deposit detection**: while handling `PUSH_ANALYTICS`, if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **automatically pushed as well** (Facebook Pixel / conversion tracking).
378
305
 
379
- **Cocos native-app detection**: when `window.CC_JSB === true`, skip all agent/channel/cookie setup (native apps don't need browser tracking).
306
+ ### 2.7 Configuration & Live Info (Common Machine)
380
307
 
381
- **Mobile detection**: `isMobile` stores a device-type string (e.g. `'mobile'`, `'tablet'`), **not a boolean**.
308
+ **4 parallel sub-machines**: `config` (siteConfig + layoutConfig, event-triggered), `feed` (feeds + mailbox + promotions, 20-second polling), `getAnnouncements` (event-triggered), and `broadcast` (switching every 5 seconds).
382
309
 
383
- **Mailbox filtering**: if `customerMessageEnable === false`, deduct CUSTOMER-type message counts from the mailbox total.
310
+ - **siteConfig decoding**: the response is an encoded string; the `setConfig` action base64-decodes it to obtain the actual configuration (`loginMethods`, `paymentMethods`, `csChat`, etc.). **The downstream frontends' stores do not decode it a second time.**
311
+ - **Broadcast rotation**: `picking` (5s) → `display` (5s) → `picking`, selecting `type === '0'` entries from `broadcastList`; already-shown items are added to `sentNormalBroadcastList` and not repeated
312
+ - **Cocos native app detection**: when `window.CC_JSB === true`, **all agent/channel/cookie setup is skipped** (native apps don't need browser tracking)
313
+ - **Mailbox filtering**: if `customerMessageEnable === false`, the count of CUSTOMER-type messages is deducted from the mailbox total
384
314
 
385
- #### 1.3.9 Error-Handling Routing (Error Machine)
386
-
387
- **Error classification & routing**:
388
-
389
- | Error code | Category | Handling |
390
- | ---------------------------------------------------- | -------------------- | -------------------------------------------------- |
391
- | `ERR_A201`/`A204`/`A103`/`A104`/`A108`/`A113`/`F108` | Logout-class | → logout state |
392
- | `ERR_G106` | Insufficient balance | → deposit state |
393
- | `error.extend` containing `unfinished_` | Unfinished game | → unfinishedGame (resume after fetching game info) |
394
- | `ERR_G124` | Free game settlement | → freeGameSettle |
395
- | `ERR_G125` | Free game forfeit | → freeGameGiveUp |
396
-
397
- **gameCode parsing for unfinished game**: `error.extend.split(/_(.+)/)[1]` — uses regex to take everything after the first underscore as the gameCode (e.g. `unfinished_ABC123` → `ABC123`).
398
-
399
- **Maintenance mode dual-interception**:
400
-
401
- 1. `request.js`: `ERR_F108` sets `isBlocked = true`, blocking all subsequent non-config requests
402
- 2. `error.js`: `ERR_F108` routes to logout state
403
-
404
- #### 1.3.10 API Request Lifecycle
405
-
406
- The complete path of an API request from descriptor object to response:
315
+ ### 2.8 API Request Lifecycle
407
316
 
408
317
  ```
409
- 1. State machine service calls request.send(api.xxx(params))
410
- 2. api.xxx(params) returns descriptor { url, method, params, isPublic, ... }
411
- 3. _checkToken(req): non-public endpoints check token; if missing throw ERR_A103
412
- 4. isBlocked check: in maintenance and not a config request → silently blocked
318
+ 1. A state machine service calls request.send(api.xxx(params))
319
+ 2. api.xxx(params) returns a descriptor object
320
+ 3. _checkToken(req): non-public endpoints check the token; if missing, throw ERR_A103
321
+ 4. isBlocked check: under maintenance and not a config request → silently blocked
413
322
  5. _createConfig(req):
414
- a. Strip query string from URL
323
+ a. Strip the query string from the URL
415
324
  b. Match against supportVersion2List (supports :param dynamic-path regex matching)
416
- c. If matched → _convertUrlToKebabCase() (look up specifyingPath first, otherwise auto-convert)
417
- d. GET → params goes into params field; POST → params goes into data field
325
+ c. If matched → _convertUrlToKebabCase() (look up the specifyingPath mapping first, otherwise auto-convert)
326
+ d. GET → params goes in the params field; POST → params goes in the data field
418
327
  e. pickBy filters out null/undefined values
419
- 6. Request interceptor: inject X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
420
- 7. Custom paramsSerializer: special encoding for q parameter (avoid double-encoding)
328
+ 6. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
329
+ 7. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
421
330
  8. axios.request(config)
422
- 9. Response interceptor:
423
- a. response.data.error present → reject
424
- b. Network Error / 404 → ERR_998 + Sentry report
425
- 10. Error handling: ERR_F108 → isBlocked; ERR_800 (cancelled) → silent; otherwise → errorHandler
331
+ 9. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
332
+ 10. Error handling: ERR_F108 → isBlocked; ERR_800 (cancelled) → silent; everything else → errorHandler
426
333
  ```
427
334
 
428
- **V2 URL conversion details**: `supportVersion2List` supports dynamic path matching (e.g. `payment/v2/:paymentType/transaction`), replacing `:param` with the regex `[^/]+`. Special paths are hard-coded in the `specifyingPath` map; the rest are auto-converted via `/([a-z])([A-Z])/g`.
429
-
430
- **When adding a new API endpoint**: if it requires V2 conversion, it must be added to `supportVersion2List` manually.
335
+ **V1→V2 conversion**: `supportVersion2List` supports dynamic paths (e.g. `payment/v2/:paymentType/transaction`, where `:param` is replaced by `[^/]+`); special paths are hard-coded in `specifyingPath`, and the rest are auto-converted via `/([a-z])([A-Z])/g`. **When adding an endpoint that needs V2 conversion, it must be added to the list manually.**
431
336
 
432
- #### 1.3.11 Critical Design Constraints & Gotchas
337
+ ### 2.9 Critical Design Constraints & Gotchas
433
338
 
434
- 1. **Token extension only happens when fetchUserInfo succeeds**: tokens are not auto-renewed; they depend on successful polling. If the API fails → the session terminates.
435
- 2. **Leading slashes affect routing**: `/payment/v2/...` (withdrawal OTP endpoints) bypasses `url-join`'s baseURL composition and starts from the API root. Regular endpoints should not have a leading slash.
436
- 3. **Mixed parameter passing for register**: `channel`/`subchannel`/`ac`/`fc` are appended to the URL query string while the rest go in the body. This is the only endpoint using this pattern.
437
- 4. **OTP endpoints flagged isPublic**: the withdrawal OTP `acknowledge`/`reset` endpoints are `isPublic: true` despite handling sensitive operations. This is because the token may have expired during the OTP flow.
438
- 5. **reCAPTCHA token is passed via header**: uses `headers['x-access-captcha']`, not in params. Only LOGIN_ID/PHONE/EMAIL use it.
439
- 6. **Context modifications must use assign()**: XState v4 forbids direct context mutation. Deep objects should be cloned with `JSON.parse(JSON.stringify())`.
440
- 7. **after: { 0 } (immediate transition) pattern**: `loginSuccess → inline → inlineFinish → login` chains together with 0ms delays; XState properly executes each state's entry/exit effects.
441
- 8. **appSecret as a public-endpoint marker**: nearly all `isPublic: true` endpoints require an `appSecret` parameter, but auth endpoints do not.
442
- 9. **Unfinished-game infinite retry**: the `unfinishedGame` state in `error.js` re-enters itself on `onError` with no backoff or retry cap.
443
- 10. **isMobile is a string, not a boolean**: in `common.js`, `isMobile = userAgent?.device?.type` returns `'mobile'`/`'tablet'`/`undefined`; comparisons must be string-based (e.g. `isMobile === 'mobile' ? 'y' : null`).
339
+ 1. **Token extension only happens when `fetchUserInfo` succeeds**: tokens are never auto-renewed and depend on successful polling. API failure → the session terminates.
340
+ 2. **A leading slash changes routing**: `/payment/v2/...` (the withdrawal OTP endpoints) **deliberately** bypasses `url-join`'s baseURL composition and starts from the API root. Regular endpoints should not have a leading slash.
341
+ 3. **`register` mixes parameter passing**: `channel`/`subchannel`/`ac`/`fc` are appended to the URL query string while the rest go in the body. **This is the only endpoint using this pattern.**
342
+ 4. **OTP endpoints marked `isPublic`**: the withdrawal OTP `acknowledge`/`reset` endpoints are `isPublic: true` even though the operations are sensitive — this is because the token may already have expired during the OTP flow, and is **not a security oversight**.
343
+ 5. **The reCAPTCHA token is passed via a header**: it uses `headers['x-access-captcha']`, **not params**. Only the `LOGIN_ID`/`PHONE`/`EMAIL` login methods use it.
344
+ 6. **Context changes must use `assign()`**: XState v4 forbids mutating context directly. Clone deep objects with `JSON.parse(JSON.stringify())`.
345
+ 7. **The `after: { 0 }` (immediate transition) pattern**: `loginSuccess → inline → inlineFinish → login` is chained with 0ms delays; XState correctly runs each state's entry/exit effects.
346
+ 8. **`appSecret` marks public endpoints**: nearly all `isPublic: true` endpoints require an `appSecret` parameter, **but the auth endpoints do not**.
347
+ 9. **Unfinished-game infinite retry**: the `unfinishedGame` state in `error.js` returns to itself on `onError`, with **no backoff strategy and no retry cap** (a known issue, see "Known Technical Debt").
348
+ 10. **`isMobile` is a string, not a boolean**: in `common.js`, `isMobile = userAgent?.device?.type` returns `'mobile'`/`'tablet'`/`undefined`, so comparisons must be string-based (e.g. `isMobile === 'mobile' ? 'y' : null`).
349
+ 11. **Requests carry no CancelToken by default**: the cancellation feature of `send(req, customToken)` is **opt-in**. In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not "helpfully" add the CancelToken back onto the shared path.**
444
350
 
445
351
  ---
446
352
 
447
- ## 2. Code Quality Standards (Clean Code Guidelines)
448
-
449
- ### 2.1 Naming Consistency
450
-
451
- #### 2.1.1 Inconsistent HTTP Method Casing
452
-
453
- `account.js` and `otp.js` use uppercase `'GET'`/`'POST'`, while the other 9 API modules use lowercase `'get'`/`'post'`. `request.js` internally calls `method.toUpperCase()` so functionality is unaffected, but it creates style inconsistency.
454
-
455
- **Convention**: use lowercase `'get'`/`'post'`/`'put'`/`'delete'` consistently.
456
-
457
- #### 2.1.2 Inconsistent State Names
458
-
459
- Different state machines use different initial state names:
460
-
461
- | Name | Usage Frequency | Representative Files |
462
- | ----------- | --------------- | ---------------------------------------------------------------------- |
463
- | `idle` | ~30 machines | Most UI state machines |
464
- | `loading` | ~20 machines | Deposit/withdrawal state machines |
465
- | `fetching` | ~10 machines | `bank_binding.js`, `game_favorite_v2.js` |
466
- | `init` | ~5 machines | `side_v2.js`, `game_search_v2.js`, `activity.js` |
467
- | `preparing` | ~3 machines | `side.js`, `game_hot_new.js` |
468
- | Other | Few | `normal` (error.js), `inactive` (side_cash.js), `pending` (jackpot.js) |
469
-
470
- **Recommended conventions**:
471
-
472
- - `idle`: idle state awaiting user action
473
- - `loading`: initial data load
474
- - `fetching`: subsequent data re-fetch
475
- - `submitting`: submission in progress
476
- - `submitted`: submission complete
477
-
478
- #### 2.1.3 Ambiguous Parameter Names
479
-
480
- Example: `addFavoriteGame(code)` — the meaning of `code` is unclear (gameCode? providerCode?); should be renamed to `addFavoriteGame(gameCode)`.
353
+ ## 3. Style Convergence Targets
481
354
 
482
- ### 2.2 Magic Numbers & Hardcoded Strings
355
+ > Every item below exists in the code in **two competing forms** — exploring the code cannot tell you which one is the standard, so it must be written down explicitly. New code always follows the "Target" column; existing code is not proactively refactored en masse (scope discipline).
483
356
 
484
- These should be centralized in `util/constant.js`. Currently scattered across files:
485
-
486
- #### 2.2.1 Activity Type IDs
487
-
488
- - `specifyActivities: [4, 29, 34]` (`machine/activity/activity.js`)
489
- - `noRedActivity = [2, 4, 13, 20, 90, 91, 92]` (deeper in the same file)
490
-
491
- #### 2.2.2 Error Codes
492
-
493
- `ERR_F108`, `ERR_A103`, `ERR_800`, `ERR_998`, etc. appear as string literals across `request.js`, `error.js`, `auth_otp_v2.js`, and others. Should be centralized as an `ERROR_CODES` constants object.
494
-
495
- #### 2.2.3 Time Constants
496
-
497
- | Value | Purpose | Occurrences |
498
- | ------------------- | ------------------------ | ------------------------------------- |
499
- | `300` | Token TTL (5 minutes) | `auth.js` (3 places) |
500
- | `60 * 60 * 24 * 31` | Account TTL (31 days) | `auth.js` (4 places) |
501
- | `60 * 60 * 24 * 7` | Cookie TTL (7 days) | `common.js` (6 places) |
502
- | `1000` | Debounce delay | 44 places (across machine/) |
503
- | `2000` | Polling tick | `auth.js`, `common.js`, `activity.js` |
504
- | `6000` | Honor board/Jackpot tick | `honor_board.js`, `jackpot.js` |
505
- | `30000` | FingerprintJS timeout | `deviceToken.js` |
506
-
507
- Should be centralized as `TTL` and `INTERVAL` constants objects.
508
-
509
- #### 2.2.4 Transaction Type Strings
510
-
511
- `'DEPOSIT'`, `'WITHDRAW'` are scattered across 38 places (`api/payment.js` and 22 state machines). Should be centralized as `TRANSFER_TYPE` constants.
512
-
513
- #### 2.2.5 WebSocket Connection Status
514
-
515
- `machine/websocket.js`'s `connectStatus: 0/1/2` (disconnected/connecting/connected) should be replaced with named constants.
516
-
517
- #### 2.2.6 Activity Receive Status
518
-
519
- Magic numbers like `receiveStatus === 1` (received), `=== 2` (claimable) should be replaced with `RECEIVE_STATUS` constants.
520
-
521
- ### 2.3 Missing Parameter Validation
522
-
523
- All API functions accept parameters with no validation. For example, `makeTransaction({ paymentMethod })` injects `paymentMethod` directly into the URL with no checks.
524
-
525
- **Recommended guidelines**:
526
-
527
- - Validate critical parameters at system boundaries (API layer)
528
- - URL path parameters should be checked for non-undefined and absence of path-traversal characters
529
- - Amount parameters should be confirmed as positive numbers
530
-
531
- ### 2.4 Inconsistent Error Handling
532
-
533
- Three error-handling patterns currently exist but no unified strategy:
534
-
535
- - **Silent transition to idle** (~60% of state machines): `onError: { target: 'idle' }`, error info lost
536
- - **Transition to fail state** (some): `onError: { target: 'fail' }`
537
- - **Infinite retry** (a few): `onError: { target: 'unfinishedGame' }`, potential infinite loop
538
-
539
- **Recommended guidelines**:
540
-
541
- - Consistently use `onError` with `actions: 'setError'` to save error info to context
542
- - Distinguish recoverable errors (retry) from unrecoverable errors (transition to fail)
543
- - Set retry limits (e.g., max 3 attempts)
544
-
545
- ### 2.5 Inconsistent Import Paths
546
-
547
- #### 2.5.1 Package Name vs Relative Path
548
-
549
- 10 files use the `@jetthai/cuora` package name instead of relative paths:
550
-
551
- - `machine/deposit/usdt.js`, `usdt_cash.js`
552
- - `machine/deposit/crypto_way.js`, `crypto_way_cash.js`
553
- - `machine/deposit/crypto_bank.js`, `crypto_bank_cash.js`
554
- - `machine/deposit/crypto_qrcode.js`, `crypto_qrcode_cash.js`
555
- - `machine/deposit/virtual_bank_cash.js`
556
- - `machine/activity/sign_in_monthly_activity.js`
557
-
558
- **Convention**: use relative paths consistently (e.g. `'../../api/payment.js'`).
559
-
560
- #### 2.5.2 Inconsistent lodash Import Extensions
561
-
562
- ```js
563
- // request.js, machine/auth.js, machine/common.js — with .js
564
- import pickBy from 'lodash/pickBy.js'
565
-
566
- // api/auth.js, util/deviceToken.js — without .js
567
- import pickBy from 'lodash/pickBy'
568
- ```
569
-
570
- **Convention**: use the form without extension (matches lodash official docs).
571
-
572
- ### 2.6 V1/V2 Legacy Duplication
573
-
574
- In `api/user.js`, V1 `passwordRecovery` coexists with the V2 `passwordV2*` family; V1 is annotated "not used by platform or cash site" but lacks an `@deprecated` marker.
575
-
576
- **Recommended guidelines**: add `@deprecated` markers to deprecated functions and remove them after confirming no references.
577
-
578
- ### 2.7 Parameter Explosion
579
-
580
- `api/payment.js`'s `updatePaymentInfo` receives 18 destructured parameters (`bankCode`, `branch`, `firstNameTh`, ...). Should be grouped as `{ bank, name, crypto, options }`.
581
-
582
- ### 2.8 Inconsistent Leading Slashes
583
-
584
- In `api/user.js`, `'/verify/v2/initiate'`, `'/otpsso/acknowledge'`, `'/otpsso/reset'` have leading slashes, while all other API modules do not. Leading slashes may affect `url-join`'s path composition, causing the `baseURL` path to be skipped.
585
-
586
- ### 2.9 Hardcoded URL Query Parameters
587
-
588
- `api/auth.js`'s `register?${qs}` and `api/mailbox.js`'s `mail?include=cl` write query parameters directly into the URL, bypassing the parameter serialization mechanism in `request.js`. Should use the `params` field instead.
357
+ | Item | Current state | Target |
358
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
359
+ | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
360
+ | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
361
+ | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
362
+ | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
363
+ | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
364
+ | Initial state naming | `idle` / `loading` / `fetching` / `init` / `preparing` are used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
365
+ | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
366
+ | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
367
+ | Parameter naming | e.g. `addFavoriteGame(code)` is semantically unclear | Concrete names (`gameCode`) |
368
+ | Parameter validation | The API layer has no validation at all (e.g. `makeTransaction({ paymentMethod })` injects straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
369
+ | Deprecated APIs | In `api/user.js`, V1 `passwordRecovery` coexists with the V2 `passwordV2*` family, with V1 unmarked | Add `@deprecated` first, then remove once confirmed unreferenced |
589
370
 
590
371
  ---
591
372
 
592
- ## 3. Performance, Memory & Rendering Audit
593
-
594
- ### 3.1 No Request Caching
595
-
596
- Every API call hits the server directly with no client-side caching. High-frequency endpoints include:
597
-
598
- | Endpoint | Call Frequency | Trigger Location |
599
- | ------------------------ | ----------------------------------- | ------------------------------------- |
600
- | `fetchUserInfo` (`self`) | Every 2-10 seconds | `auth.js` `inline` and `login` states |
601
- | `getConfig` | Every state machine initialization | `auth.js`, `common.js` |
602
- | `getPaymentDetail` | Every deposit/withdrawal page entry | 15+ deposit/withdraw state machines |
603
- | `getActivityList` | Every 20 seconds | `activity.js` (`tick * 10`) |
604
-
605
- **Recommendations**: introduce TTL caching for infrequently changing data, or use a `stale-while-revalidate` strategy.
606
-
607
- ### 3.2 Memory Leak — WebSocket Listeners
608
-
609
- **Severity**: High
610
-
611
- The `listenToSocketEvents` callback service in `machine/websocket.js` registers 7 `.on()` listeners (`activity-info`, `activity-reward-info`, `message-notice-info`, `payment-info`, `connect`, `connect_error`, `disconnect`) but **never returns a cleanup function**.
612
-
613
- In XState v4 callback services, the returned function is the cleanup/teardown function. Missing it causes listeners to accumulate on each reconnection. Fix: extract the handlers into named variables and return a `() => clientSocket.off(event, handler)` cleanup function.
614
-
615
- Additionally, `connectSocket`'s Promise registers `connect` and `connect_error` listeners that are not cleaned up after Promise resolve/reject either.
616
-
617
- ### 3.3 No Rate Limiting
618
-
619
- API calls have no client-side throttling or debouncing:
620
-
621
- - Some deposit state machines use a `debouncing` state (1000ms delay), but only for calculation requests
622
- - `fetchUserInfo` polling and `fetchFeeds` polling have no backoff strategy — fixed-interval polling, unchanged even on errors
623
-
624
- **Recommendations**: use exponential backoff on errors and add throttling to critical API calls.
625
-
626
- ### 3.4 No Automatic Token Refresh
627
-
628
- The response interceptor in `request.js` does not handle 401 status codes. When the token expires, requests fail directly and state machines transition to error/exit states.
373
+ ## 4. Known Technical Debt
629
374
 
630
- **Recommendations**: intercept 401, attempt automatic token refresh, replay the original request on success; trigger logout on failure.
375
+ > These issues **have already been surveyed**; there is no need to re-report them in every code review. When you want to address one, open a separate ticket — don't bundle it into a feature change.
631
376
 
632
- ### 3.5 Unused Context Variables
377
+ - **WebSocket listener leak (severity: high)** — the `listenToSocketEvents` callback service in `machine/websocket.js` registers several `.on()` listeners but **never returns a cleanup function**, so they accumulate on every reconnect. Fix: extract the handlers into named variables and return `() => clientSocket.off(event, handler)`. The `connect` / `connect_error` listeners registered inside `connectSocket`'s Promise are likewise never cleaned up. **Newly written callback services must always return a cleanup function (see the DoD).**
378
+ - **No request caching** — high-frequency endpoints (`fetchUserInfo` every 2–10 seconds, `getConfig` on every state machine initialization, `getPaymentDetail` on every entry to a deposit/withdrawal page, `getActivityList` every 20 seconds) all hit the server directly. Consider TTL caching or `stale-while-revalidate`.
379
+ - **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
380
+ - **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
381
+ - **FingerprintJS bundling** — the FingerprintJS embedded in `src/lib/` is loaded at module initialization even when disabled. Consider switching to a dynamic `import()` for lazy loading.
382
+ - **No code splitting** — `machine/index.js` eagerly imports every state machine + the APIs + Socket.IO + lodash, so importing `machine` loads everything. Consider supporting individual imports to enable tree-shaking.
383
+ - **Timer management** — countdowns are largely implemented with self-referencing `after: { 1000 }` transitions, producing one state transition per second (including a context clone + event dispatch). Consider a callback service + `setInterval`, and **compute elapsed time** rather than decrementing step by step to avoid cumulative drift.
384
+ - **Large state machine files** — `game_v2_1.js`, `auth.js`, `withdraw_manual.js`, `inbox.js`, `manual_vn.js`, `common.js`, and `game_search_v2.js` all exceed 300 lines and could be split into composable sub-machines.
385
+ - **Unused context fields** — several state machines declare context fields that are never assigned or read.
386
+ - **lodash can be replaced with natives** — only a handful of functions are actually used; `padStart` / `toNumber` can be swapped for natives directly, and `findLastIndex` is supported in modern browsers.
633
387
 
634
- Several state machines declare context fields that are never assigned or read, for example:
635
-
636
- - `machine/activity/activity.js`: `refs: {}` (never used), `uidSite: ''` (never initialized), `siteConfig: {}` (never read)
637
- - `machine/websocket.js`: `analytics: null` (set externally but not used by the state machine for transitions)
638
-
639
- **Recommendation**: audit all state-machine context fields and remove unused definitions.
640
-
641
- ### 3.6 Large State Machine Files
642
-
643
- Files exceeding 300 lines should be considered for splitting into smaller, composable state machines:
644
-
645
- | File | Suggestion |
646
- | -------------------- | ------------------------------------------------------------------------- |
647
- | `game_v2_1.js` | Split game list, categories, pagination into separate state machines |
648
- | `auth.js` | Extract login flow, token management, user info polling |
649
- | `withdraw_manual.js` | Extract OTP verification as a reusable child state machine |
650
- | `inbox.js` | Split notification and message management |
651
- | `manual_vn.js` | Extract calculation and submission as shared deposit utilities |
652
- | `common.js` | Already uses parallel states; can further decompose config/feed/broadcast |
653
- | `game_search_v2.js` | Extract search logic as a reusable state machine |
654
-
655
- ### 3.7 Timer Management
656
-
657
- 44 places use 1000-millisecond timers with self-referencing state transitions (e.g. countdown `after: { 1000: { target: 'countdown', actions: 'decreaseTtl' } }`), producing one state transition per second (including context clone + event dispatch).
658
-
659
- **Recommendations**:
660
-
661
- - Consider using callback services with `setInterval` instead of self-referencing `after` transitions
662
- - Calculate elapsed time rather than decrementing per-tick to avoid cumulative drift
663
-
664
- ### 3.8 FingerprintJS Bundling Issue
665
-
666
- `src/lib/fingerprint_v3_11_12.js` is a **292 KB** embedded FingerprintJS v3.11.12 library. Even when `enable = false` (device token not used), this 292KB is still loaded at module initialization.
667
-
668
- **Recommendations**:
669
-
670
- - Use `@fingerprintjs/fingerprintjs` as an npm dependency
671
- - Use dynamic `import()` for lazy loading: `await import()` inside `getDeviceToken` before using it
672
-
673
- ### 3.9 No Code Splitting
674
-
675
- `machine/index.js` eagerly imports all 91 state machines + all API modules + FingerprintJS (292KB) + Socket.IO + lodash functions. Importing `machine` loads the entire bundle, even if the consumer only needs 1-2 state machines.
676
-
677
- **Recommendations**: support individual imports to enable tree-shaking, e.g. `export { default as auth } from './auth.js'`; consumer side: `import { auth } from '@jetthai/cuora/src/machine/index.js'`.
678
-
679
- ### 3.10 Lodash Usage Optimization
680
-
681
- The 6 functions actually used:
388
+ ---
682
389
 
683
- | Function | Files Using It | Native Alternative |
684
- | --------------- | -------------- | ------------------------------------------------------------- |
685
- | `pickBy` | 4 | `Object.fromEntries(Object.entries(obj).filter(...))` |
686
- | `uniqBy` | 1 | Custom implementation or `Set` |
687
- | `findLastIndex` | 2 | `Array.prototype.findLastIndex()` (ES2023) |
688
- | `padStart` | 2 | `String.prototype.padStart()` |
689
- | `toNumber` | 1 | `Number()` or `parseFloat()` |
690
- | `isEqual` | 2 | `JSON.stringify` shallow comparison or custom deep comparison |
390
+ ## Syncing to Other AI Instruction Files
691
391
 
692
- **Recommendations**:
392
+ This file is the single source of truth. Via `.claude/commands/sync-ai-prompts.md` it can be automatically synced to `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, and `.github/copilot-instructions.md`.
693
393
 
694
- - `padStart`, `toNumber` can be directly replaced with native methods
695
- - `findLastIndex` is natively supported in modern browsers (Chrome 97+)
696
- - Consider replacing `lodash` with `lodash-es` to support ESM tree-shaking, or remove the lodash dependency entirely
394
+ ⚠️ **Only modify this file `AI_PROMPT_SOURCE.md`**; the other files are auto-generated by the `sync-ai-prompts` command, and manual edits will be overwritten.