@jetthai/cuora 1.1.485-dev.1 → 1.1.485
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/commands/sync-ai-prompts.md +1 -88
- package/.claude/settings.local.json +1 -3
- package/.github/copilot-instructions.md +27 -61
- package/.husky/post-checkout +3 -3
- package/.husky/pre-push +1 -1
- package/.prettierignore +1 -2
- package/AGENTS.md +27 -61
- package/AI_PROMPT_SOURCE.md +27 -61
- package/CHANGELOG.md +23 -380
- package/CLAUDE.md +27 -61
- package/GEMINI.md +27 -61
- package/package.json +1 -1
- package/scripts/auto-version.js +0 -1
- package/scripts/branch-auto-npm-publish.js +2 -9
- package/src/api/payment.js +0 -1
- package/src/machine/reward_cash.js +2 -2
- package/src/machine/user_sign_up.js +0 -3
- package/src/machine/withdraw/withdraw_manual_cash.js +4 -7
- package/src/util/constant.js +1 -2
- package/test/withdraw_manual_cash.test.js +0 -149
package/CLAUDE.md
CHANGED
|
@@ -59,7 +59,7 @@ Before delivering any code change, verify each of the following yourself:
|
|
|
59
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
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
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
|
|
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
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
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
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`
|
|
@@ -200,8 +200,6 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
|
|
|
200
200
|
|
|
201
201
|
**OTP / bind-bank flow**: after a successful login it enters `otpChecking`; `OTP_VERIFIED` or `OTP_SKIP` moves it to `bindBankChecking`, and only `BIND_BANK_DONE` or `BIND_BANK_SKIP` proceeds to `loginSuccess` (either gate accepts `LOGOUT` to abort). Whether binding is required is decided by the downstream frontend; the machine only waits — **downstream must send one of these events in `bindBankChecking`, or the session stalls there**. The `tokenAuthenticated` path skips both gates.
|
|
202
202
|
|
|
203
|
-
**OTP auto-verification** (`auth_otp_v3.js`): when `verify` / `sendPhone` / `sendEmail` respond with `needAcknowledge === false`, the machine skips OTP input and goes to `autoVerifying`. But **`needAcknowledge: false` by itself does not count as verified** — the `phone_verification_status` / `email_verification_status` from `/self` is always the basis, and the contact data must be non-empty (phone accepts `phone` or `tel`; when the data is empty, input is required even if the status is truthy). There is a delay between the backend writing the verification status and `/self` reflecting it; when the machine's own `/self` call does not pass, it enters `autoVerifyWaiting` — **the machine does not poll by itself**; instead it waits for downstream to forward the `/self` results of auth's routine polling as `USER_INFO_UPDATED` (`data` is the userInfo), for at most 2 updates or 5 seconds (`AUTO_VERIFY_*` in `util/constant.js`; receiving a stale value does not reset the timer), and if still not verified → `fail`. **When downstream does not forward this event, auto-verification simply falls to `fail` after 5 seconds.** The 5 seconds is sized against auth's `tick: 2000` so that two polls can come back in time; changing `tick` requires adjusting it in lockstep.
|
|
204
|
-
|
|
205
203
|
**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.** However, `pruneRememberedAccounts`, which runs after `fetchSiteConfig` succeeds, **compares against `siteConfig.loginMethods` and clears the leftover account for any disabled login method** (`phone` clears the country code along with it) — fetching configuration, an apparently read-only action, carries the side effect of deleting from localStorage. The purpose is to prevent downstream frontends from back-filling a stale value into an input whose type has since changed after the backend disables a login method. When `loginMethods` is missing entirely, nothing is cleared, to avoid wiping everything by mistake.
|
|
206
204
|
|
|
207
205
|
### 2.2 Canonical Deposit Pattern
|
|
@@ -300,62 +298,29 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
|
|
|
300
298
|
|
|
301
299
|
### 2.6 Real-Time Communication (WebSocket)
|
|
302
300
|
|
|
303
|
-
**
|
|
304
|
-
|
|
305
|
-
**Host selection**: `selectSocket` fetches multiple hosts from `target/target.json` on GCS and hits `/ping/status` on all of them simultaneously with `Promise.any()` — the fastest responder wins; when the list can't be fetched or every host fails, it falls back to `request.config.socketURL`. **Without a token, no host is selected and no connection is created.**
|
|
301
|
+
**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.
|
|
306
302
|
|
|
307
303
|
```js
|
|
308
|
-
io(
|
|
304
|
+
io(`${socketURL}/frontend`, {
|
|
309
305
|
withCredentials: true,
|
|
310
306
|
forceNew: true,
|
|
311
|
-
transports: ['websocket'], //
|
|
312
|
-
auth:
|
|
307
|
+
transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
|
|
308
|
+
auth: { Authorization: authToken },
|
|
313
309
|
})
|
|
314
310
|
```
|
|
315
311
|
|
|
316
|
-
**
|
|
317
|
-
|
|
318
|
-
| Result | Trigger | Behavior |
|
|
319
|
-
| ---------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
320
|
-
| `socketio` | A `disconnect` not initiated by the server, or a `connect_error` while the socket is still `active` | Stay on the same instance and leave it to Socket.IO's built-in reconnect; not recovered within 120 seconds of the first loss → `exhausted` |
|
|
321
|
-
| `retry` | Every other failure (including `io server disconnect` **before the session is ready**) | Re-select a host; at most 3 times beyond the initial attempt, 1 / 2 / 4 second exponential backoff × 0.5–1.5 jitter, with the server-provided `retryAfterMs` as the floor; budget used up → `exhausted` |
|
|
322
|
-
| `renew` | `SESSION_TOKEN_INVALID` / `session rejected` | Reconnect immediately once (only one allowance before becoming ready), then treated as `retry` |
|
|
323
|
-
| `kicked` | The `kicked` event, `MAX_CONNECTIONS`, or `io server disconnect` **after the session is ready** | Stop |
|
|
324
|
-
| `stop` | A rejection carrying `retryable: false` | Stop |
|
|
325
|
-
| `none` | `io client disconnect` (disconnected by ourselves) | Ignored |
|
|
326
|
-
|
|
327
|
-
**`io server disconnect` no longer means "reconnect"**: being disconnected by the server after the session is ready is treated as being kicked, with no automatic reconnect. After stopping, `context.blocked` decides who may resume (`canResume`): `kicked` only accepts `source: 'user'`; `exhausted` accepts user at any time and `auto` only once ≥ 15 seconds have passed since the last attempt; `stop` has to wait for a token change. A `DISCONNECT_SOCKET` without `preserveSession` clears `blocked`.
|
|
328
|
-
|
|
329
|
-
**Downstream contracts** (the other end of these events and context fields lives in the downstream frontends; there is no caller inside this package):
|
|
330
|
-
|
|
331
|
-
| Interface | Contract |
|
|
332
|
-
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
333
|
-
| `CONNECT` / `CHECK_SOCKET` | May carry `source: 'user' \| 'auto'` (default `user`), which decides whether it can resume after `blocked` |
|
|
334
|
-
| `AUTH_CHECKED` | `{ token, uidSite }`; may only come from a successful `/self`, and `token` must equal the current `getToken()`; for the obligation after sending it once, see below |
|
|
335
|
-
| `DISCONNECT_SOCKET` | Default = logout / destroy, clearing the session, dedupe records, and retry state; `{ preserveSession: true }` = background release, keeping all of them |
|
|
336
|
-
| `SESSION_READY` | `{ resync, generation }`. **Readiness is based on the server's `session-ready` (or `socket.recovered === true`), not on `connect`** — `SET_CONNECTED` only means the transport is up. `resync: true` means a session was ready before and this one is a fresh, non-recovered session, so downstream must catch up via REST |
|
|
337
|
-
| `ACTIVITY_INFO` | `{ data, eventName, generation }`; `payment-info` is **no longer limited to `windowType === 'toast'`** — any filtering is up to downstream |
|
|
338
|
-
| `context.generation` | Incremented when the connection is invalidated, on a new attempt, and on the first loss; downstream can use it to discard REST responses from an older generation |
|
|
339
|
-
| `context.claimPaymentEvent(event, orderData)` | GA dedupe shared by REST and socket: `true` = first time, may report; `false` = duplicate, or the current session can't be trusted. `purchase` and `first_deposit` are counted separately, and `applyId` / `transactionId` are treated as aliases of the same order; with no ID at all it returns `true` |
|
|
340
|
-
|
|
341
|
-
**Once `AUTH_CHECKED` has been sent, it must be sent again after every token rotation**: when a verified session switches directly to another token, until the `AUTH_CHECKED` for the new token arrives, `CONNECT` / `CHECK_SOCKET` are only recorded and do not connect, and `claimPaymentEvent` always returns `false`; the dedupe records are restored only when the UID is the same as before. Downstreams that have never sent `AUTH_CHECKED` are unaffected.
|
|
342
|
-
|
|
343
|
-
**Push dedupe**: the four push events are deduplicated before being forwarded (`createPushDedupe`) — `_meta.messageId` is preferred; without it, only `payment-info` is keyed by "business event + `applyId` / `transactionId`"; with neither, no dedupe is applied.
|
|
312
|
+
**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).
|
|
344
313
|
|
|
345
314
|
**Event forwarding map**:
|
|
346
315
|
|
|
347
|
-
| Socket event
|
|
348
|
-
|
|
|
349
|
-
| `activity-info`
|
|
350
|
-
| `activity-reward-info` / `message-notice-info`
|
|
351
|
-
| `
|
|
352
|
-
| `
|
|
353
|
-
| `connect_error` / `disconnect` | `CONNECT_ERROR` / `DISCONNECT` (carrying `internalSocket: true`, after going through the failure decision) |
|
|
354
|
-
| `auth-rejected` / `kicked` | Not forwarded; they only enter the failure decision |
|
|
355
|
-
|
|
356
|
-
A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internalSocket`, is treated as a failure report and enters the failure decision as well.
|
|
316
|
+
| Socket event | State machine event |
|
|
317
|
+
| ---------------------------------------------- | ----------------------------------------------------------------------------------- |
|
|
318
|
+
| `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
|
|
319
|
+
| `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
|
|
320
|
+
| `payment-info` | Conditional: sends `ACTIVITY_INFO` + `PUSH_ANALYTICS` when `windowType === 'toast'` |
|
|
321
|
+
| `connect` / `connect_error` / `disconnect` | `SET_CONNECTED` / `CONNECT_ERROR` / `DISCONNECT` |
|
|
357
322
|
|
|
358
|
-
**First-deposit detection**:
|
|
323
|
+
**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).
|
|
359
324
|
|
|
360
325
|
### 2.7 Configuration & Live Info (Common Machine)
|
|
361
326
|
|
|
@@ -410,19 +375,19 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
|
|
|
410
375
|
|
|
411
376
|
> 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).
|
|
412
377
|
|
|
413
|
-
| Item | Current state
|
|
414
|
-
| ------------------------- |
|
|
415
|
-
| HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected)
|
|
416
|
-
| Import paths | Some files self-reference via the `@jetthai/cuora` package name
|
|
417
|
-
| lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist
|
|
418
|
-
| URL leading slash | A few APIs carry a leading slash
|
|
419
|
-
| Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization
|
|
420
|
-
| Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably
|
|
421
|
-
| Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around
|
|
422
|
-
| Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry
|
|
423
|
-
| Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear
|
|
424
|
-
| Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL)
|
|
425
|
-
| Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment
|
|
378
|
+
| Item | Current state | Target |
|
|
379
|
+
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
380
|
+
| HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
|
|
381
|
+
| Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
|
|
382
|
+
| lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
|
|
383
|
+
| URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
|
|
384
|
+
| Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
|
|
385
|
+
| Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
|
|
386
|
+
| Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around; `util/constant.js` currently holds **only** `GAME_SEARCH` / `GAME_TYPE_LIST`, two game-category constants | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
|
|
387
|
+
| 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 |
|
|
388
|
+
| Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
|
|
389
|
+
| Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
|
|
390
|
+
| Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
|
|
426
391
|
|
|
427
392
|
---
|
|
428
393
|
|
|
@@ -430,6 +395,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
|
|
|
430
395
|
|
|
431
396
|
> 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.
|
|
432
397
|
|
|
398
|
+
- **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).**
|
|
433
399
|
- **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`.
|
|
434
400
|
- **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
|
|
435
401
|
- **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
|
package/GEMINI.md
CHANGED
|
@@ -59,7 +59,7 @@ Before delivering any code change, verify each of the following yourself:
|
|
|
59
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
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
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
|
|
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
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
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
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`
|
|
@@ -200,8 +200,6 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
|
|
|
200
200
|
|
|
201
201
|
**OTP / bind-bank flow**: after a successful login it enters `otpChecking`; `OTP_VERIFIED` or `OTP_SKIP` moves it to `bindBankChecking`, and only `BIND_BANK_DONE` or `BIND_BANK_SKIP` proceeds to `loginSuccess` (either gate accepts `LOGOUT` to abort). Whether binding is required is decided by the downstream frontend; the machine only waits — **downstream must send one of these events in `bindBankChecking`, or the session stalls there**. The `tokenAuthenticated` path skips both gates.
|
|
202
202
|
|
|
203
|
-
**OTP auto-verification** (`auth_otp_v3.js`): when `verify` / `sendPhone` / `sendEmail` respond with `needAcknowledge === false`, the machine skips OTP input and goes to `autoVerifying`. But **`needAcknowledge: false` by itself does not count as verified** — the `phone_verification_status` / `email_verification_status` from `/self` is always the basis, and the contact data must be non-empty (phone accepts `phone` or `tel`; when the data is empty, input is required even if the status is truthy). There is a delay between the backend writing the verification status and `/self` reflecting it; when the machine's own `/self` call does not pass, it enters `autoVerifyWaiting` — **the machine does not poll by itself**; instead it waits for downstream to forward the `/self` results of auth's routine polling as `USER_INFO_UPDATED` (`data` is the userInfo), for at most 2 updates or 5 seconds (`AUTO_VERIFY_*` in `util/constant.js`; receiving a stale value does not reset the timer), and if still not verified → `fail`. **When downstream does not forward this event, auto-verification simply falls to `fail` after 5 seconds.** The 5 seconds is sized against auth's `tick: 2000` so that two polls can come back in time; changing `tick` requires adjusting it in lockstep.
|
|
204
|
-
|
|
205
203
|
**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.** However, `pruneRememberedAccounts`, which runs after `fetchSiteConfig` succeeds, **compares against `siteConfig.loginMethods` and clears the leftover account for any disabled login method** (`phone` clears the country code along with it) — fetching configuration, an apparently read-only action, carries the side effect of deleting from localStorage. The purpose is to prevent downstream frontends from back-filling a stale value into an input whose type has since changed after the backend disables a login method. When `loginMethods` is missing entirely, nothing is cleared, to avoid wiping everything by mistake.
|
|
206
204
|
|
|
207
205
|
### 2.2 Canonical Deposit Pattern
|
|
@@ -300,62 +298,29 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
|
|
|
300
298
|
|
|
301
299
|
### 2.6 Real-Time Communication (WebSocket)
|
|
302
300
|
|
|
303
|
-
**
|
|
304
|
-
|
|
305
|
-
**Host selection**: `selectSocket` fetches multiple hosts from `target/target.json` on GCS and hits `/ping/status` on all of them simultaneously with `Promise.any()` — the fastest responder wins; when the list can't be fetched or every host fails, it falls back to `request.config.socketURL`. **Without a token, no host is selected and no connection is created.**
|
|
301
|
+
**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.
|
|
306
302
|
|
|
307
303
|
```js
|
|
308
|
-
io(
|
|
304
|
+
io(`${socketURL}/frontend`, {
|
|
309
305
|
withCredentials: true,
|
|
310
306
|
forceNew: true,
|
|
311
|
-
transports: ['websocket'], //
|
|
312
|
-
auth:
|
|
307
|
+
transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
|
|
308
|
+
auth: { Authorization: authToken },
|
|
313
309
|
})
|
|
314
310
|
```
|
|
315
311
|
|
|
316
|
-
**
|
|
317
|
-
|
|
318
|
-
| Result | Trigger | Behavior |
|
|
319
|
-
| ---------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
320
|
-
| `socketio` | A `disconnect` not initiated by the server, or a `connect_error` while the socket is still `active` | Stay on the same instance and leave it to Socket.IO's built-in reconnect; not recovered within 120 seconds of the first loss → `exhausted` |
|
|
321
|
-
| `retry` | Every other failure (including `io server disconnect` **before the session is ready**) | Re-select a host; at most 3 times beyond the initial attempt, 1 / 2 / 4 second exponential backoff × 0.5–1.5 jitter, with the server-provided `retryAfterMs` as the floor; budget used up → `exhausted` |
|
|
322
|
-
| `renew` | `SESSION_TOKEN_INVALID` / `session rejected` | Reconnect immediately once (only one allowance before becoming ready), then treated as `retry` |
|
|
323
|
-
| `kicked` | The `kicked` event, `MAX_CONNECTIONS`, or `io server disconnect` **after the session is ready** | Stop |
|
|
324
|
-
| `stop` | A rejection carrying `retryable: false` | Stop |
|
|
325
|
-
| `none` | `io client disconnect` (disconnected by ourselves) | Ignored |
|
|
326
|
-
|
|
327
|
-
**`io server disconnect` no longer means "reconnect"**: being disconnected by the server after the session is ready is treated as being kicked, with no automatic reconnect. After stopping, `context.blocked` decides who may resume (`canResume`): `kicked` only accepts `source: 'user'`; `exhausted` accepts user at any time and `auto` only once ≥ 15 seconds have passed since the last attempt; `stop` has to wait for a token change. A `DISCONNECT_SOCKET` without `preserveSession` clears `blocked`.
|
|
328
|
-
|
|
329
|
-
**Downstream contracts** (the other end of these events and context fields lives in the downstream frontends; there is no caller inside this package):
|
|
330
|
-
|
|
331
|
-
| Interface | Contract |
|
|
332
|
-
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
333
|
-
| `CONNECT` / `CHECK_SOCKET` | May carry `source: 'user' \| 'auto'` (default `user`), which decides whether it can resume after `blocked` |
|
|
334
|
-
| `AUTH_CHECKED` | `{ token, uidSite }`; may only come from a successful `/self`, and `token` must equal the current `getToken()`; for the obligation after sending it once, see below |
|
|
335
|
-
| `DISCONNECT_SOCKET` | Default = logout / destroy, clearing the session, dedupe records, and retry state; `{ preserveSession: true }` = background release, keeping all of them |
|
|
336
|
-
| `SESSION_READY` | `{ resync, generation }`. **Readiness is based on the server's `session-ready` (or `socket.recovered === true`), not on `connect`** — `SET_CONNECTED` only means the transport is up. `resync: true` means a session was ready before and this one is a fresh, non-recovered session, so downstream must catch up via REST |
|
|
337
|
-
| `ACTIVITY_INFO` | `{ data, eventName, generation }`; `payment-info` is **no longer limited to `windowType === 'toast'`** — any filtering is up to downstream |
|
|
338
|
-
| `context.generation` | Incremented when the connection is invalidated, on a new attempt, and on the first loss; downstream can use it to discard REST responses from an older generation |
|
|
339
|
-
| `context.claimPaymentEvent(event, orderData)` | GA dedupe shared by REST and socket: `true` = first time, may report; `false` = duplicate, or the current session can't be trusted. `purchase` and `first_deposit` are counted separately, and `applyId` / `transactionId` are treated as aliases of the same order; with no ID at all it returns `true` |
|
|
340
|
-
|
|
341
|
-
**Once `AUTH_CHECKED` has been sent, it must be sent again after every token rotation**: when a verified session switches directly to another token, until the `AUTH_CHECKED` for the new token arrives, `CONNECT` / `CHECK_SOCKET` are only recorded and do not connect, and `claimPaymentEvent` always returns `false`; the dedupe records are restored only when the UID is the same as before. Downstreams that have never sent `AUTH_CHECKED` are unaffected.
|
|
342
|
-
|
|
343
|
-
**Push dedupe**: the four push events are deduplicated before being forwarded (`createPushDedupe`) — `_meta.messageId` is preferred; without it, only `payment-info` is keyed by "business event + `applyId` / `transactionId`"; with neither, no dedupe is applied.
|
|
312
|
+
**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).
|
|
344
313
|
|
|
345
314
|
**Event forwarding map**:
|
|
346
315
|
|
|
347
|
-
| Socket event
|
|
348
|
-
|
|
|
349
|
-
| `activity-info`
|
|
350
|
-
| `activity-reward-info` / `message-notice-info`
|
|
351
|
-
| `
|
|
352
|
-
| `
|
|
353
|
-
| `connect_error` / `disconnect` | `CONNECT_ERROR` / `DISCONNECT` (carrying `internalSocket: true`, after going through the failure decision) |
|
|
354
|
-
| `auth-rejected` / `kicked` | Not forwarded; they only enter the failure decision |
|
|
355
|
-
|
|
356
|
-
A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internalSocket`, is treated as a failure report and enters the failure decision as well.
|
|
316
|
+
| Socket event | State machine event |
|
|
317
|
+
| ---------------------------------------------- | ----------------------------------------------------------------------------------- |
|
|
318
|
+
| `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
|
|
319
|
+
| `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
|
|
320
|
+
| `payment-info` | Conditional: sends `ACTIVITY_INFO` + `PUSH_ANALYTICS` when `windowType === 'toast'` |
|
|
321
|
+
| `connect` / `connect_error` / `disconnect` | `SET_CONNECTED` / `CONNECT_ERROR` / `DISCONNECT` |
|
|
357
322
|
|
|
358
|
-
**First-deposit detection**:
|
|
323
|
+
**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).
|
|
359
324
|
|
|
360
325
|
### 2.7 Configuration & Live Info (Common Machine)
|
|
361
326
|
|
|
@@ -410,19 +375,19 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
|
|
|
410
375
|
|
|
411
376
|
> 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).
|
|
412
377
|
|
|
413
|
-
| Item | Current state
|
|
414
|
-
| ------------------------- |
|
|
415
|
-
| HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected)
|
|
416
|
-
| Import paths | Some files self-reference via the `@jetthai/cuora` package name
|
|
417
|
-
| lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist
|
|
418
|
-
| URL leading slash | A few APIs carry a leading slash
|
|
419
|
-
| Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization
|
|
420
|
-
| Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably
|
|
421
|
-
| Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around
|
|
422
|
-
| Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry
|
|
423
|
-
| Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear
|
|
424
|
-
| Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL)
|
|
425
|
-
| Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment
|
|
378
|
+
| Item | Current state | Target |
|
|
379
|
+
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
380
|
+
| HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
|
|
381
|
+
| Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
|
|
382
|
+
| lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
|
|
383
|
+
| URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
|
|
384
|
+
| Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
|
|
385
|
+
| Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
|
|
386
|
+
| Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around; `util/constant.js` currently holds **only** `GAME_SEARCH` / `GAME_TYPE_LIST`, two game-category constants | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
|
|
387
|
+
| 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 |
|
|
388
|
+
| Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
|
|
389
|
+
| Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
|
|
390
|
+
| Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
|
|
426
391
|
|
|
427
392
|
---
|
|
428
393
|
|
|
@@ -430,6 +395,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
|
|
|
430
395
|
|
|
431
396
|
> 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.
|
|
432
397
|
|
|
398
|
+
- **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).**
|
|
433
399
|
- **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`.
|
|
434
400
|
- **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
|
|
435
401
|
- **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
|
package/package.json
CHANGED
package/scripts/auto-version.js
CHANGED
|
@@ -14,15 +14,8 @@ const { version } = JSON.parse(readFileSync('package.json', 'utf8'))
|
|
|
14
14
|
console.log(`Branch: ${branch}`)
|
|
15
15
|
console.log(`Version: ${version}`)
|
|
16
16
|
|
|
17
|
-
// 推送 commit 到遠端(--no-verify 避免觸發 pre-push hook 造成無限迴圈)
|
|
18
|
-
execSync(`git push --no-verify ${remote} ${branch}`, { stdio: 'inherit' })
|
|
19
|
-
|
|
20
|
-
// 單獨推送 tag;tag 已存在於 remote 時視為成功(不中斷 npm publish)
|
|
21
|
-
try {
|
|
22
|
-
execSync(`git push --no-verify ${remote} refs/tags/v${version}`, { stdio: 'inherit' })
|
|
23
|
-
} catch {
|
|
24
|
-
console.warn(`⚠ tag v${version} push 失敗(可能已存在),繼續 npm publish`)
|
|
25
|
-
}
|
|
17
|
+
// 推送 commit 與 tag 到遠端(--no-verify 避免觸發 pre-push hook 造成無限迴圈)
|
|
18
|
+
execSync(`git push --no-verify --follow-tags ${remote} ${branch}`, { stdio: 'inherit' })
|
|
26
19
|
|
|
27
20
|
// 發布到 npm,使用分支名稱作為 dist-tag(例如 npm install @jetthai/cuora@dev)
|
|
28
21
|
try {
|
package/src/api/payment.js
CHANGED
|
@@ -197,7 +197,7 @@ export default function (request, context) {
|
|
|
197
197
|
)
|
|
198
198
|
const getOtherRewardAPI = request.send(
|
|
199
199
|
activity.getRewardList({
|
|
200
|
-
rewardType: 'CASH,FREE,PRIZE
|
|
200
|
+
rewardType: 'CASH,FREE,PRIZE',
|
|
201
201
|
count: 30,
|
|
202
202
|
appSecret,
|
|
203
203
|
orderColumn,
|
|
@@ -212,7 +212,7 @@ export default function (request, context) {
|
|
|
212
212
|
const lang = context.lang
|
|
213
213
|
const getOtherRewardAPI = request.send(
|
|
214
214
|
activity.getRewardList({
|
|
215
|
-
rewardType: 'CASH,FREE,PRIZE
|
|
215
|
+
rewardType: 'CASH,FREE,PRIZE',
|
|
216
216
|
count: 30,
|
|
217
217
|
appSecret,
|
|
218
218
|
orderColumn,
|
|
@@ -107,7 +107,6 @@ export default function (request) {
|
|
|
107
107
|
return {
|
|
108
108
|
signUpData: {
|
|
109
109
|
provider: 'local',
|
|
110
|
-
birthday,
|
|
111
110
|
...pickBindData(event.data),
|
|
112
111
|
birthday,
|
|
113
112
|
email,
|
|
@@ -131,7 +130,6 @@ export default function (request) {
|
|
|
131
130
|
return {
|
|
132
131
|
signUpData: {
|
|
133
132
|
provider: 'phone',
|
|
134
|
-
birthday,
|
|
135
133
|
...pickBindData(event.data),
|
|
136
134
|
birthday,
|
|
137
135
|
email,
|
|
@@ -154,7 +152,6 @@ export default function (request) {
|
|
|
154
152
|
return {
|
|
155
153
|
signUpData: {
|
|
156
154
|
provider: 'email',
|
|
157
|
-
birthday,
|
|
158
155
|
...pickBindData(event.data),
|
|
159
156
|
birthday,
|
|
160
157
|
email,
|
|
@@ -36,8 +36,9 @@ export default function (request, context) {
|
|
|
36
36
|
target: 'checking',
|
|
37
37
|
actions: 'setInitData',
|
|
38
38
|
},
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
onError: {
|
|
40
|
+
target: 'loaded',
|
|
41
|
+
},
|
|
41
42
|
},
|
|
42
43
|
},
|
|
43
44
|
checking: {
|
|
@@ -95,11 +96,7 @@ export default function (request, context) {
|
|
|
95
96
|
},
|
|
96
97
|
},
|
|
97
98
|
},
|
|
98
|
-
submitted: {
|
|
99
|
-
on: {
|
|
100
|
-
REFRESH: { target: 'loading', internal: false },
|
|
101
|
-
},
|
|
102
|
-
},
|
|
99
|
+
submitted: {},
|
|
103
100
|
otp: {
|
|
104
101
|
type: 'parallel',
|
|
105
102
|
states: {
|
package/src/util/constant.js
CHANGED
|
@@ -11,12 +11,11 @@ export const GAME_TYPE_LIST = [
|
|
|
11
11
|
{ typeId: 'SCRATCHCARDS', name: 'Scratch Cards', gameTypeMappingId: 9 },
|
|
12
12
|
{ typeId: 'EGAME', name: 'E-Game', gameTypeMappingId: 10 },
|
|
13
13
|
{ typeId: 'BONUS', name: 'Bonus', gameTypeMappingId: 11 },
|
|
14
|
-
|
|
14
|
+
{ typeId: 'BALL', name: 'Ball', gameTypeMappingId: 12 },
|
|
15
15
|
{ typeId: 'PACHINKO', name: 'Pachinko', gameTypeMappingId: 13 },
|
|
16
16
|
{ typeId: 'GRAPH', name: 'Graph', gameTypeMappingId: 14 },
|
|
17
17
|
{ typeId: 'TURBO', name: 'Turbo', gameTypeMappingId: 15 },
|
|
18
18
|
{ typeId: 'SPORT', name: 'Sports', gameTypeMappingId: 16 },
|
|
19
|
-
{ typeId: 'PREDICTION', name: 'Prediction', gameTypeMappingId: 12 },
|
|
20
19
|
]
|
|
21
20
|
|
|
22
21
|
// OTP 自動驗證:主動打的 /self 未通過後,最多再等幾次 auth 例行輪詢的 /self、等待上限多久
|