@jetthai/cuora 1.1.483 → 1.1.485-dev.0
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 +88 -1
- package/.claude/settings.local.json +3 -1
- package/.github/copilot-instructions.md +19 -10
- package/.husky/post-checkout +3 -3
- package/.husky/pre-push +1 -1
- package/.prettierignore +2 -1
- package/AGENTS.md +19 -10
- package/AI_PROMPT_SOURCE.md +19 -10
- package/CHANGELOG.md +386 -23
- package/CLAUDE.md +19 -10
- package/GEMINI.md +19 -10
- package/docs/my-claude/feat-sharon-JT-1790247240-socket/branch-transfer.md +14 -0
- package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-preparation.json +40 -0
- package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-verification.md +41 -0
- package/docs/my-claude/feat-sharon-JT-1790247240-socket/implementation-ledger.md +87 -0
- package/docs/my-claude/feat-sharon-JT-1790247240-socket/module-report.md +73 -0
- package/docs/my-claude/feat-sharon-JT-1790247240-socket/plan.md +309 -0
- package/docs/my-claude/feat-sharon-JT-1790247240-socket/test-cases.md +245 -0
- package/docs/my-claude/feat-sharon-JT-1791180540-onesignal/transfer.md +9 -0
- package/e2e/feature-map.md +61 -0
- package/package.json +1 -1
- package/prepare-for-pr/JT-1776243420.md +85 -0
- package/prepare-for-pr/TI-16026/STATE.md +17 -0
- package/prepare-for-pr/TI-16026/after-prepare-authorization.md +3 -0
- package/prepare-for-pr/TI-16026/analysis.md +38 -0
- package/prepare-for-pr/TI-16026/answer-analyze-01.md +1 -0
- package/prepare-for-pr/TI-16026/answer-commit-01.md +2 -0
- package/prepare-for-pr/TI-16026/answer-commit-02.md +1 -0
- package/prepare-for-pr/TI-16026/bundle.json +18 -0
- package/prepare-for-pr/TI-16026/checklist.md +39 -0
- package/prepare-for-pr/TI-16026/claude-after-model +1 -0
- package/prepare-for-pr/TI-16026/claude-commit-session +1 -0
- package/prepare-for-pr/TI-16026/claude-harvest-session +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/01-analyze.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/01-analyze.out +2 -0
- package/prepare-for-pr/TI-16026/claude-hops/02-analyze.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/02-analyze.out +4 -0
- package/prepare-for-pr/TI-16026/claude-hops/03-dev.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/03-dev.out +4 -0
- package/prepare-for-pr/TI-16026/claude-hops/04-dev.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/04-dev.out +4 -0
- package/prepare-for-pr/TI-16026/claude-hops/05-dev.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/05-dev.out +3 -0
- package/prepare-for-pr/TI-16026/claude-hops/06-after.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/06-after.out +2 -0
- package/prepare-for-pr/TI-16026/claude-hops/07-commit.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/07-commit.out +2 -0
- package/prepare-for-pr/TI-16026/claude-hops/08-commit.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/08-commit.out +2 -0
- package/prepare-for-pr/TI-16026/claude-hops/09-commit.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/09-commit.out +8 -0
- package/prepare-for-pr/TI-16026/claude-hops/10-harvest.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/10-harvest.out +3 -0
- package/prepare-for-pr/TI-16026/commit-note.md +5 -0
- package/prepare-for-pr/TI-16026/feature-map.before.md +61 -0
- package/prepare-for-pr/TI-16026/harvest-redaction.out +1 -0
- package/prepare-for-pr/TI-16026/harvest.md +37 -0
- package/prepare-for-pr/TI-16026/lessons.md +5 -0
- package/prepare-for-pr/TI-16026/open-questions.md +6 -0
- package/prepare-for-pr/TI-16026/publish.md +28 -0
- package/prepare-for-pr/TI-16026/review-convergence-response.md +3 -0
- package/prepare-for-pr/TI-16026/review-input/scope.md +18 -0
- package/prepare-for-pr/TI-16026/review-log.md +57 -0
- package/prepare-for-pr/TI-16026/review-notes.md +97 -0
- package/prepare-for-pr/TI-16026/review-response-r1.md +7 -0
- package/prepare-for-pr/TI-16026/spec-proposal.md +34 -0
- package/prepare-for-pr/TI-16026/spec-snapshot.md +291 -0
- package/prepare-for-pr/TI-16026/state-log.md +35 -0
- package/prepare-for-pr/TI-16026/user-messages/01.md +12 -0
- package/prepare-for-pr/TI-16026/user-messages/02.md +20 -0
- package/prepare-for-pr/TI-16026/user-messages/03.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/04.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/05.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/06.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/07.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/08.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/09.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/10.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/11.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/12.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/13.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/14.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/15.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/16.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/17.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/18.md +10 -0
- package/prepare-for-pr/TI-16026/user-messages/19.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/20.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/21.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/22.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/23.md +8 -0
- package/prepare-for-pr/TI-16026/user-question.md +24 -0
- package/prepare-for-pr/TI-16026/verify-after.md +15 -0
- package/prepare-for-pr/TI-16026.md +408 -0
- package/scripts/auto-version.js +1 -0
- package/scripts/branch-auto-npm-publish.js +9 -2
- package/src/api/payment.js +1 -0
- package/src/machine/auth_otp_v3.js +59 -20
- package/src/machine/honor_board_cash.js +15 -18
- package/src/machine/reward_cash.js +2 -2
- package/src/machine/user_sign_up.js +3 -0
- package/src/machine/websocket.js +380 -311
- package/src/machine/withdraw/withdraw_manual_cash.js +7 -4
- package/src/util/constant.js +4 -0
- package/src/util/socketPolicy.js +57 -0
- package/test/auth_otp_v3.test.js +323 -0
- package/test/withdraw_manual_cash.test.js +149 -0
- package/tests/websocket.test.mjs +779 -0
package/src/machine/websocket.js
CHANGED
|
@@ -1,9 +1,25 @@
|
|
|
1
|
-
import { assign, createMachine } from 'xstate'
|
|
1
|
+
import { assign, createMachine, send } from 'xstate'
|
|
2
2
|
import { io } from 'socket.io-client'
|
|
3
|
+
import { canResume, createPushDedupe, decideNextStep, nextRetryDelay } from '../util/socketPolicy.js'
|
|
4
|
+
|
|
5
|
+
const MAX_RETRIES = 3
|
|
6
|
+
const GIVEUP_MS = 120000
|
|
7
|
+
const CLAIM_TTL_MS = 600000
|
|
8
|
+
const CLAIM_MAX = 500
|
|
9
|
+
const hasId = (id) => id !== undefined && id !== null && id !== ''
|
|
10
|
+
const frontendURL = (host) =>
|
|
11
|
+
`${String(host)
|
|
12
|
+
.replace(/\/+$/, '')
|
|
13
|
+
.replace(/(?:\/frontend)+$/, '')}/frontend`
|
|
3
14
|
|
|
4
15
|
export default function (request) {
|
|
5
|
-
const { socketURL, bucketName, clientId
|
|
6
|
-
const
|
|
16
|
+
const { socketURL, bucketName, clientId } = request.config
|
|
17
|
+
const url = `https://storage.googleapis.com/${bucketName}/site_resources/${clientId}/target/target.json`
|
|
18
|
+
let owner = null
|
|
19
|
+
let generation = 0
|
|
20
|
+
const claimPaymentEvent = (event, data) => owner?.claim(event, data) ?? false
|
|
21
|
+
const forward = send((_, event) => event, { to: 'socketLifecycle' })
|
|
22
|
+
|
|
7
23
|
return createMachine(
|
|
8
24
|
{
|
|
9
25
|
id: 'socket',
|
|
@@ -11,343 +27,396 @@ export default function (request) {
|
|
|
11
27
|
context: {
|
|
12
28
|
clientSocket: null,
|
|
13
29
|
reconnectCount: 0,
|
|
14
|
-
connectStatus: 0,
|
|
30
|
+
connectStatus: 0,
|
|
15
31
|
connectError: null,
|
|
16
32
|
analytics: null,
|
|
17
|
-
url
|
|
18
|
-
socketURL
|
|
33
|
+
url,
|
|
34
|
+
socketURL,
|
|
19
35
|
socketData: {},
|
|
36
|
+
generation: 0,
|
|
37
|
+
ready: false,
|
|
38
|
+
blocked: null,
|
|
39
|
+
lastAttemptAt: 0,
|
|
40
|
+
claimPaymentEvent,
|
|
20
41
|
},
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
fetchSocket: {
|
|
24
|
-
invoke: {
|
|
25
|
-
src: 'fetchSocket',
|
|
26
|
-
onDone: {
|
|
27
|
-
target: 'connecting',
|
|
28
|
-
actions: 'saveSocketURL',
|
|
29
|
-
},
|
|
30
|
-
onError: {
|
|
31
|
-
target: 'idle',
|
|
32
|
-
},
|
|
33
|
-
},
|
|
34
|
-
},
|
|
35
|
-
connecting: {
|
|
36
|
-
entry: 'setConnecting',
|
|
37
|
-
invoke: {
|
|
38
|
-
src: 'connectSocket',
|
|
39
|
-
onDone: {
|
|
40
|
-
actions: 'setSocket',
|
|
41
|
-
target: 'connected',
|
|
42
|
-
},
|
|
43
|
-
onError: {
|
|
44
|
-
target: 'disconnected',
|
|
45
|
-
actions: 'setConnectError',
|
|
46
|
-
},
|
|
47
|
-
},
|
|
48
|
-
},
|
|
49
|
-
connected: {
|
|
50
|
-
invoke: {
|
|
51
|
-
src: 'listenToSocketEvents', // 監聽事件
|
|
52
|
-
},
|
|
53
|
-
},
|
|
54
|
-
disconnected: {
|
|
55
|
-
after: {
|
|
56
|
-
0: {
|
|
57
|
-
target: 'reconnect',
|
|
58
|
-
cond: 'isReconnect',
|
|
59
|
-
},
|
|
60
|
-
},
|
|
61
|
-
},
|
|
62
|
-
reconnect: {
|
|
63
|
-
after: {
|
|
64
|
-
2000: {
|
|
65
|
-
actions: 'setReconnectCount',
|
|
66
|
-
target: 'connecting',
|
|
67
|
-
cond: 'isNeedConnect',
|
|
68
|
-
},
|
|
69
|
-
},
|
|
70
|
-
},
|
|
71
|
-
checkSocketConnect: {
|
|
72
|
-
always: [{ target: 'fetchSocket' }, { target: 'connected' }],
|
|
73
|
-
},
|
|
74
|
-
},
|
|
42
|
+
invoke: { id: 'socketLifecycle', src: 'socketLifecycle' },
|
|
43
|
+
states: { idle: {}, fetchSocket: {}, connecting: {}, connected: {}, disconnected: {}, reconnect: {}, checkSocketConnect: {} },
|
|
75
44
|
on: {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
},
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
actions: '
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
},
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
},
|
|
93
|
-
|
|
94
|
-
actions: 'setActivityInfo',
|
|
95
|
-
},
|
|
96
|
-
CLEAR_SOCKET_DATA: {
|
|
97
|
-
actions: 'clearSocketData',
|
|
98
|
-
},
|
|
99
|
-
SET_ANALYTICS: {
|
|
100
|
-
actions: 'setAnalytics',
|
|
101
|
-
},
|
|
102
|
-
PUSH_ANALYTICS: {
|
|
103
|
-
actions: 'pushEvent',
|
|
104
|
-
},
|
|
45
|
+
CONNECT: { actions: forward },
|
|
46
|
+
CHECK_SOCKET: { actions: forward },
|
|
47
|
+
AUTH_CHECKED: { actions: forward },
|
|
48
|
+
DISCONNECT_SOCKET: { target: '.idle', actions: forward },
|
|
49
|
+
_SOCKET_STATUS: [
|
|
50
|
+
{ target: '.fetchSocket', cond: (_, event) => event.phase === 'selecting', actions: 'setStatus' },
|
|
51
|
+
{ target: '.connecting', cond: (_, event) => event.phase === 'connecting', actions: 'setStatus' },
|
|
52
|
+
{ target: '.idle', cond: (_, event) => event.phase === 'idle', actions: 'setStatus' },
|
|
53
|
+
{ actions: 'setStatus' },
|
|
54
|
+
],
|
|
55
|
+
SET_CONNECTED: { target: '.connected', actions: 'setSocket' },
|
|
56
|
+
CONNECT_ERROR: { actions: ['setConnectError', forward] },
|
|
57
|
+
DISCONNECT: { actions: ['setDisconnected', forward] },
|
|
58
|
+
SESSION_READY: { actions: assign((_, event) => ({ ready: true, generation: event.generation })) },
|
|
59
|
+
ACTIVITY_INFO: { actions: assign((_, event) => ({ socketData: event.data })) },
|
|
60
|
+
CLEAR_SOCKET_DATA: { actions: assign({ socketData: () => ({}) }) },
|
|
61
|
+
SET_ANALYTICS: { actions: assign({ analytics: (_, event) => event.data }) },
|
|
62
|
+
PUSH_ANALYTICS: { actions: 'pushEvent' },
|
|
105
63
|
},
|
|
106
64
|
},
|
|
107
65
|
{
|
|
108
66
|
actions: {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
return {
|
|
116
|
-
clientSocket: event.data,
|
|
117
|
-
connectStatus: 2, // 0: 未連線, 1: 連線中, 2: 連線成功
|
|
118
|
-
}
|
|
67
|
+
setStatus: assign((_, event) => event.data),
|
|
68
|
+
setSocket: assign((_, event) => ({ clientSocket: event.data, connectStatus: 2, connectError: null })),
|
|
69
|
+
setConnectError: assign((_, event) => (event.internalSocket ? {} : { connectError: event.error || event.data, connectStatus: 0 })),
|
|
70
|
+
setDisconnected: assign((context, event) => {
|
|
71
|
+
if (event.reason !== 'io client disconnect') context.analytics?.push({ event: 'socket_disconnect', message: event.reason })
|
|
72
|
+
return event.internalSocket ? {} : { connectStatus: 0 }
|
|
119
73
|
}),
|
|
120
|
-
|
|
121
|
-
const
|
|
122
|
-
return
|
|
123
|
-
|
|
124
|
-
|
|
74
|
+
pushEvent: (context, event) => {
|
|
75
|
+
const { data = {}, event: name, isTracking } = event.data || {}
|
|
76
|
+
if (!isTracking) return
|
|
77
|
+
const capturedToken = request.getToken()
|
|
78
|
+
const capturedGeneration = generation
|
|
79
|
+
const payload = {
|
|
80
|
+
paymentMethod: data.paymentMethod,
|
|
81
|
+
transaction_id: data.transactionId,
|
|
82
|
+
currency: data.currency,
|
|
83
|
+
value: data.value,
|
|
84
|
+
app_value: data.value,
|
|
125
85
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
86
|
+
if (claimPaymentEvent(name, data)) context.analytics?.push({ event: name, ...payload }, { eventID: data.transactionId })
|
|
87
|
+
if (capturedToken !== request.getToken() || capturedGeneration !== generation) return
|
|
88
|
+
if (name === 'purchase' && data.isFirst === true && claimPaymentEvent('first_deposit', data))
|
|
89
|
+
context.analytics?.push({ event: 'first_deposit', ...payload }, { eventID: data.transactionId })
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
services: {
|
|
93
|
+
socketLifecycle: () => (callback, receive) => {
|
|
94
|
+
let alive = true
|
|
95
|
+
let token = ''
|
|
96
|
+
let verifiedUid = null
|
|
97
|
+
let archive = null
|
|
98
|
+
let pendingIntent = null
|
|
99
|
+
let clientSocket = null
|
|
100
|
+
let handlers = []
|
|
101
|
+
let selection = null
|
|
102
|
+
let epoch = 0
|
|
103
|
+
let retryTimer = null
|
|
104
|
+
let retryAt = 0
|
|
105
|
+
let giveupTimer = null
|
|
106
|
+
let attempts = 0
|
|
107
|
+
let renewUsed = false
|
|
108
|
+
let blocked = null
|
|
109
|
+
let lastAttemptAt = 0
|
|
110
|
+
let ready = false
|
|
111
|
+
let instanceReady = false
|
|
112
|
+
let hadSession = false
|
|
113
|
+
let dedupe = createPushDedupe()
|
|
114
|
+
let claims = new Map()
|
|
115
|
+
|
|
116
|
+
const status = (phase, extra = {}) =>
|
|
117
|
+
callback({
|
|
118
|
+
type: '_SOCKET_STATUS',
|
|
119
|
+
phase,
|
|
120
|
+
data: { clientSocket, generation, blocked, ready, reconnectCount: attempts, lastAttemptAt, ...extra },
|
|
121
|
+
})
|
|
122
|
+
const clearTimers = () => {
|
|
123
|
+
clearTimeout(retryTimer)
|
|
124
|
+
clearTimeout(giveupTimer)
|
|
125
|
+
retryTimer = giveupTimer = null
|
|
130
126
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
// 主動觸發斷開socket連接
|
|
134
|
-
let { clientSocket } = context
|
|
135
|
-
console.log('[socket][disconnectSocket]')
|
|
136
|
-
if (clientSocket) {
|
|
137
|
-
clientSocket.disconnect()
|
|
127
|
+
const closeSocket = () => {
|
|
128
|
+
const old = clientSocket
|
|
138
129
|
clientSocket = null
|
|
130
|
+
for (const [event, handler] of handlers) old?.off(event, handler)
|
|
131
|
+
handlers = []
|
|
132
|
+
old?.disconnect()
|
|
133
|
+
ready = instanceReady = false
|
|
139
134
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
event: 'socket_disconnect',
|
|
148
|
-
message: reason,
|
|
149
|
-
})
|
|
135
|
+
const invalidate = () => {
|
|
136
|
+
epoch++
|
|
137
|
+
generation++
|
|
138
|
+
selection?.abort()
|
|
139
|
+
selection = null
|
|
140
|
+
clearTimers()
|
|
141
|
+
closeSocket()
|
|
150
142
|
}
|
|
151
|
-
|
|
152
|
-
|
|
143
|
+
const clearSession = () => {
|
|
144
|
+
verifiedUid = null
|
|
145
|
+
archive = null
|
|
146
|
+
hadSession = false
|
|
147
|
+
dedupe = createPushDedupe()
|
|
148
|
+
claims = new Map()
|
|
153
149
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
app_value: data.value,
|
|
177
|
-
},
|
|
178
|
-
{ eventID: data.transactionId }
|
|
179
|
-
)
|
|
150
|
+
const observeToken = () => {
|
|
151
|
+
const current = request.getToken() || ''
|
|
152
|
+
if (current === token) return false
|
|
153
|
+
if (current && token && verifiedUid !== null) archive = { verifiedUid, hadSession, dedupe, claims }
|
|
154
|
+
else if (!current) archive = null
|
|
155
|
+
invalidate()
|
|
156
|
+
token = current
|
|
157
|
+
verifiedUid = null
|
|
158
|
+
hadSession = false
|
|
159
|
+
dedupe = createPushDedupe()
|
|
160
|
+
claims = new Map()
|
|
161
|
+
blocked = null
|
|
162
|
+
attempts = 0
|
|
163
|
+
renewUsed = false
|
|
164
|
+
retryAt = 0
|
|
165
|
+
lastAttemptAt = 0
|
|
166
|
+
if (!token) {
|
|
167
|
+
clearSession()
|
|
168
|
+
pendingIntent = null
|
|
169
|
+
}
|
|
170
|
+
status('idle', { connectStatus: 0, connectError: null, socketData: {} })
|
|
171
|
+
return true
|
|
180
172
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
)
|
|
173
|
+
const claim = (event, data = {}) => {
|
|
174
|
+
observeToken()
|
|
175
|
+
if (!alive || !token || archive) return false
|
|
176
|
+
const now = Date.now()
|
|
177
|
+
for (const [key, entry] of claims) if (now - entry.at >= CLAIM_TTL_MS) claims.delete(key)
|
|
178
|
+
const aliases = [...new Set([data.applyId, data.transactionId, data.data?.applyId, data.data?.transactionId].filter(hasId).map(String))]
|
|
179
|
+
if (!aliases.length) return true
|
|
180
|
+
const entries = aliases.map((id) => claims.get(id)).filter(Boolean)
|
|
181
|
+
const events = new Set(entries.flatMap((entry) => [...entry.events]))
|
|
182
|
+
const duplicate = events.has(event)
|
|
183
|
+
events.add(event)
|
|
184
|
+
const entry = { at: now, events }
|
|
185
|
+
for (const [id, previous] of claims) if (entries.includes(previous)) claims.set(id, entry)
|
|
186
|
+
for (const id of aliases) claims.set(id, entry)
|
|
187
|
+
while (claims.size > CLAIM_MAX) claims.delete(claims.keys().next().value)
|
|
188
|
+
return !duplicate
|
|
194
189
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
}),
|
|
201
|
-
},
|
|
202
|
-
guards: {
|
|
203
|
-
isNeedConnect: (context, event) => {
|
|
204
|
-
const { connectStatus, clientSocket } = context
|
|
205
|
-
// 檢查 Socket 是否已連接
|
|
206
|
-
if (connectStatus == 1 || (clientSocket && clientSocket?.connected)) {
|
|
207
|
-
return false
|
|
208
|
-
} else {
|
|
209
|
-
return true
|
|
190
|
+
owner = { claim }
|
|
191
|
+
const valid = (socket, capturedEpoch, capturedToken) => {
|
|
192
|
+
if (!alive) return false
|
|
193
|
+
observeToken()
|
|
194
|
+
return alive && socket === clientSocket && capturedEpoch === epoch && capturedToken === token && !!token
|
|
210
195
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
196
|
+
const markReady = (socket, recovered = false) => {
|
|
197
|
+
const capturedEpoch = epoch
|
|
198
|
+
const capturedToken = token
|
|
199
|
+
if (!valid(socket, capturedEpoch, capturedToken)) return
|
|
200
|
+
clearTimers()
|
|
201
|
+
ready = true
|
|
202
|
+
attempts = 0
|
|
203
|
+
renewUsed = false
|
|
204
|
+
blocked = null
|
|
205
|
+
retryAt = 0
|
|
206
|
+
status()
|
|
207
|
+
if (!valid(socket, capturedEpoch, capturedToken)) return
|
|
208
|
+
if (instanceReady) return
|
|
209
|
+
instanceReady = true
|
|
210
|
+
const resync = hadSession && !recovered
|
|
211
|
+
hadSession = true
|
|
212
|
+
callback({ type: 'SESSION_READY', resync, generation })
|
|
213
|
+
}
|
|
214
|
+
const exhaust = () => {
|
|
215
|
+
invalidate()
|
|
216
|
+
blocked = 'exhausted'
|
|
217
|
+
status('idle', { connectStatus: 0 })
|
|
218
|
+
}
|
|
219
|
+
const startGiveup = () => {
|
|
220
|
+
if (giveupTimer !== null) return
|
|
221
|
+
generation++
|
|
222
|
+
const capturedEpoch = epoch
|
|
223
|
+
giveupTimer = setTimeout(() => {
|
|
224
|
+
giveupTimer = null
|
|
225
|
+
observeToken()
|
|
226
|
+
if (alive && capturedEpoch === epoch) exhaust()
|
|
227
|
+
}, GIVEUP_MS)
|
|
228
|
+
}
|
|
229
|
+
const handleFailure = (event, socket, err, reason, rejection) => {
|
|
230
|
+
const step = decideNextStep({ event, err, reason, rejection, active: !!socket?.active, ready })
|
|
231
|
+
if (step === 'none') return
|
|
232
|
+
if (step === 'socketio') {
|
|
233
|
+
ready = instanceReady = false
|
|
234
|
+
startGiveup()
|
|
235
|
+
status(undefined, { connectStatus: 1, connectError: err?.message || reason })
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
const info = rejection || err?.data || {}
|
|
239
|
+
const failure = step === 'kicked' ? { ...info, code: 'MAX_CONNECTIONS' } : Object.keys(info).length ? info : err?.message || reason || err
|
|
240
|
+
invalidate()
|
|
241
|
+
if (blocked === 'exhausted') {
|
|
242
|
+
status('idle', { connectStatus: 0, connectError: failure })
|
|
243
|
+
return
|
|
244
|
+
}
|
|
245
|
+
if (step === 'kicked' || step === 'stop') {
|
|
246
|
+
blocked = step
|
|
247
|
+
status('idle', { connectStatus: 0, connectError: failure })
|
|
248
|
+
return
|
|
249
|
+
}
|
|
250
|
+
if (step === 'renew' && !renewUsed) {
|
|
251
|
+
renewUsed = true
|
|
252
|
+
const capturedEpoch = epoch
|
|
253
|
+
const capturedToken = token
|
|
254
|
+
status('idle', { connectStatus: 0, connectError: failure })
|
|
255
|
+
if (alive && epoch === capturedEpoch && token === capturedToken && request.getToken() === capturedToken) attempt('auto', true)
|
|
256
|
+
return
|
|
257
|
+
}
|
|
258
|
+
if (attempts >= MAX_RETRIES) {
|
|
259
|
+
exhaust()
|
|
260
|
+
return
|
|
261
|
+
}
|
|
262
|
+
attempts++
|
|
263
|
+
const capturedEpoch = epoch
|
|
264
|
+
const delay = nextRetryDelay(attempts, info.retryAfterMs)
|
|
265
|
+
retryAt = Date.now() + delay
|
|
266
|
+
retryTimer = setTimeout(() => {
|
|
267
|
+
retryTimer = null
|
|
268
|
+
observeToken()
|
|
269
|
+
if (alive && epoch === capturedEpoch) attempt('auto', true)
|
|
270
|
+
}, delay)
|
|
271
|
+
status('idle', { connectStatus: 0, connectError: failure })
|
|
272
|
+
}
|
|
273
|
+
const bindSocket = (socket, capturedEpoch, capturedToken) => {
|
|
274
|
+
const on = (event, fn) => {
|
|
275
|
+
const handler = (...args) => {
|
|
276
|
+
if (valid(socket, capturedEpoch, capturedToken)) fn(...args)
|
|
277
|
+
}
|
|
278
|
+
handlers.push([event, handler])
|
|
279
|
+
socket.on(event, handler)
|
|
280
|
+
}
|
|
281
|
+
on('connect', () => {
|
|
282
|
+
callback({ type: 'SET_CONNECTED', data: socket })
|
|
283
|
+
if (socket.recovered === true) markReady(socket, true)
|
|
243
284
|
})
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
285
|
+
on('session-ready', () => markReady(socket, socket.recovered === true))
|
|
286
|
+
on('connect_error', (error) => {
|
|
287
|
+
handleFailure('connect_error', socket, error)
|
|
288
|
+
if (alive && capturedToken === request.getToken()) callback({ type: 'CONNECT_ERROR', error, internalSocket: true })
|
|
248
289
|
})
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
290
|
+
on('disconnect', (reason) => {
|
|
291
|
+
handleFailure('disconnect', socket, null, reason)
|
|
292
|
+
if (alive && capturedToken === request.getToken()) callback({ type: 'DISCONNECT', reason, internalSocket: true })
|
|
293
|
+
})
|
|
294
|
+
on('auth-rejected', (rejection) => handleFailure('auth-rejected', socket, null, null, rejection))
|
|
295
|
+
on('kicked', (rejection) => handleFailure('kicked', socket, null, null, rejection))
|
|
296
|
+
for (const eventName of ['activity-info', 'activity-reward-info', 'message-notice-info', 'payment-info']) {
|
|
297
|
+
on(eventName, (data) => {
|
|
298
|
+
if (dedupe(eventName, data)) return
|
|
299
|
+
callback({ type: 'ACTIVITY_INFO', data, eventName, generation })
|
|
300
|
+
if (!valid(socket, capturedEpoch, capturedToken)) return
|
|
301
|
+
if (eventName === 'activity-info' || eventName === 'payment-info') callback({ type: 'PUSH_ANALYTICS', data })
|
|
302
|
+
})
|
|
303
|
+
}
|
|
257
304
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
})
|
|
265
|
-
|
|
266
|
-
// 監聽 activity-reward-info 事件
|
|
267
|
-
clientSocket.on('activity-reward-info', (data) => {
|
|
268
|
-
console.log('[socket][activity-reward-info]:', data)
|
|
269
|
-
callback({ type: 'ACTIVITY_INFO', data })
|
|
270
|
-
})
|
|
271
|
-
|
|
272
|
-
// 監聽 message-notice-info 事件
|
|
273
|
-
clientSocket.on('message-notice-info', (data) => {
|
|
274
|
-
console.log('[socket][message-notice-info]:', data)
|
|
275
|
-
callback({ type: 'ACTIVITY_INFO', data })
|
|
276
|
-
})
|
|
277
|
-
|
|
278
|
-
// 監聽 payment-info 事件
|
|
279
|
-
clientSocket.on('payment-info', (data) => {
|
|
280
|
-
console.log('[socket][payment-info]:', data)
|
|
281
|
-
if (data.windowType === 'toast') {
|
|
282
|
-
callback({ type: 'ACTIVITY_INFO', data })
|
|
305
|
+
const attempt = async (source = 'user', scheduled = false) => {
|
|
306
|
+
observeToken()
|
|
307
|
+
if (!alive || !token) return
|
|
308
|
+
if (archive) {
|
|
309
|
+
if (!pendingIntent || source === 'user') pendingIntent = source
|
|
310
|
+
return
|
|
283
311
|
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
312
|
+
if (selection || retryTimer !== null || giveupTimer !== null || clientSocket?.active || clientSocket?.connected) return
|
|
313
|
+
if (!scheduled && !canResume({ lastToken: token, blocked, lastAttemptAt }, token, source)) return
|
|
314
|
+
if (Date.now() < retryAt) {
|
|
315
|
+
const capturedEpoch = epoch
|
|
316
|
+
retryTimer = setTimeout(() => {
|
|
317
|
+
retryTimer = null
|
|
318
|
+
observeToken()
|
|
319
|
+
if (alive && capturedEpoch === epoch) attempt(source, scheduled)
|
|
320
|
+
}, retryAt - Date.now())
|
|
321
|
+
return
|
|
322
|
+
}
|
|
323
|
+
closeSocket()
|
|
324
|
+
const controller = new AbortController()
|
|
325
|
+
selection = controller
|
|
326
|
+
const capturedEpoch = ++epoch
|
|
327
|
+
const capturedToken = token
|
|
328
|
+
lastAttemptAt = Date.now()
|
|
329
|
+
generation++
|
|
330
|
+
status('selecting', { connectStatus: 1 })
|
|
331
|
+
try {
|
|
332
|
+
const host = await selectSocket(url, socketURL, controller.signal)
|
|
333
|
+
if (!alive) return
|
|
334
|
+
observeToken()
|
|
335
|
+
if (!alive || capturedEpoch !== epoch || capturedToken !== token || controller.signal.aborted) return
|
|
336
|
+
selection = null
|
|
337
|
+
controller.abort()
|
|
338
|
+
closeSocket()
|
|
339
|
+
const socket = io(frontendURL(host), {
|
|
340
|
+
withCredentials: true,
|
|
341
|
+
forceNew: true,
|
|
342
|
+
transports: ['websocket'],
|
|
343
|
+
auth: (done) => done({ Authorization: request.getToken() }),
|
|
344
|
+
})
|
|
345
|
+
clientSocket = socket
|
|
346
|
+
bindSocket(socket, capturedEpoch, capturedToken)
|
|
347
|
+
status('connecting', { connectStatus: 1, socketURL: host })
|
|
348
|
+
} catch (error) {
|
|
349
|
+
if (!alive || capturedEpoch !== epoch) return
|
|
350
|
+
selection = null
|
|
351
|
+
controller.abort()
|
|
352
|
+
handleFailure('connect_error', null, error)
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
receive((event) => {
|
|
356
|
+
if (!alive) return
|
|
357
|
+
if (event.type === 'CONNECT' || event.type === 'CHECK_SOCKET') attempt(event.source || 'user')
|
|
358
|
+
else if (event.type === 'AUTH_CHECKED') {
|
|
359
|
+
observeToken()
|
|
360
|
+
if (!token || event.token !== token || !hasId(event.uidSite)) return
|
|
361
|
+
const uid = String(event.uidSite)
|
|
362
|
+
if (archive) {
|
|
363
|
+
if (String(archive.verifiedUid) === uid) ({ hadSession, dedupe, claims } = archive)
|
|
364
|
+
archive = null
|
|
365
|
+
} else if (verifiedUid !== null && verifiedUid !== uid) {
|
|
366
|
+
invalidate()
|
|
367
|
+
clearSession()
|
|
368
|
+
status('idle', { connectStatus: 0, socketData: {} })
|
|
369
|
+
}
|
|
370
|
+
verifiedUid = uid
|
|
371
|
+
const intent = pendingIntent
|
|
372
|
+
pendingIntent = null
|
|
373
|
+
if (intent) attempt(intent)
|
|
374
|
+
} else if (event.type === 'DISCONNECT_SOCKET') {
|
|
375
|
+
invalidate()
|
|
376
|
+
pendingIntent = null
|
|
377
|
+
if (!event.preserveSession) {
|
|
378
|
+
clearSession()
|
|
379
|
+
token = ''
|
|
380
|
+
blocked = null
|
|
381
|
+
attempts = 0
|
|
382
|
+
renewUsed = false
|
|
383
|
+
lastAttemptAt = 0
|
|
384
|
+
retryAt = 0
|
|
385
|
+
}
|
|
386
|
+
status('idle', { connectStatus: 0, connectError: null, socketData: {} })
|
|
387
|
+
} else if (!event.internalSocket && event.type === 'CONNECT_ERROR')
|
|
388
|
+
handleFailure('connect_error', clientSocket, event.error || { message: event.data })
|
|
389
|
+
else if (!event.internalSocket && event.type === 'DISCONNECT') handleFailure('disconnect', clientSocket, null, event.reason)
|
|
301
390
|
})
|
|
391
|
+
return () => {
|
|
392
|
+
alive = false
|
|
393
|
+
invalidate()
|
|
394
|
+
clearSession()
|
|
395
|
+
pendingIntent = null
|
|
396
|
+
owner = null
|
|
397
|
+
}
|
|
302
398
|
},
|
|
303
399
|
},
|
|
304
400
|
}
|
|
305
401
|
)
|
|
306
402
|
}
|
|
307
403
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
await this.init()
|
|
326
|
-
}
|
|
327
|
-
const { url, index } = await Promise.any(
|
|
328
|
-
this.socket.map((url, i) => {
|
|
329
|
-
return this.ping(url, i)
|
|
330
|
-
})
|
|
331
|
-
)
|
|
332
|
-
console.info(`[Socket] Host ${index} is chosen. (${url})`)
|
|
333
|
-
return url
|
|
334
|
-
} catch (error) {
|
|
335
|
-
console.error('[Socket] Socket Test Fail.', error)
|
|
336
|
-
return this.fallbackUrl
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
async ping(url, index) {
|
|
341
|
-
let ts, response
|
|
342
|
-
try {
|
|
343
|
-
ts = new Date().getTime()
|
|
344
|
-
response = await fetch(`${url}/ping/status`)
|
|
345
|
-
if (!response.ok) throw response
|
|
346
|
-
return { url, index }
|
|
347
|
-
} finally {
|
|
348
|
-
const speed = new Date().getTime() - ts
|
|
349
|
-
const status = !!response?.ok ? 'Success' : 'Failure'
|
|
350
|
-
console.info(`[Socket] Host: ${index}, URL: ${url}, Status: ${status}, Speed: ${speed}ms`)
|
|
351
|
-
}
|
|
404
|
+
async function selectSocket(url, fallback, signal) {
|
|
405
|
+
try {
|
|
406
|
+
const response = await fetch(url, { signal })
|
|
407
|
+
const { socket } = await response.json()
|
|
408
|
+
return await Promise.any(
|
|
409
|
+
(Array.isArray(socket) ? socket : []).map(async (host) => {
|
|
410
|
+
const target = String(host)
|
|
411
|
+
.replace(/\/+$/, '')
|
|
412
|
+
.replace(/(?:\/frontend)+$/, '')
|
|
413
|
+
const ping = await fetch(`${target}/ping/status`, { signal })
|
|
414
|
+
if (!ping.ok) throw new Error('Socket host unavailable')
|
|
415
|
+
return target
|
|
416
|
+
})
|
|
417
|
+
)
|
|
418
|
+
} catch (error) {
|
|
419
|
+
if (signal.aborted) throw error
|
|
420
|
+
return fallback
|
|
352
421
|
}
|
|
353
422
|
}
|