@jetthai/cuora 1.1.483 → 1.1.485-dev.1

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.
Files changed (34) hide show
  1. package/.claude/commands/sync-ai-prompts.md +88 -1
  2. package/.claude/settings.local.json +3 -1
  3. package/.github/copilot-instructions.md +80 -37
  4. package/.husky/post-checkout +3 -3
  5. package/.husky/pre-push +1 -1
  6. package/.prettierignore +2 -1
  7. package/AGENTS.md +80 -37
  8. package/AI_PROMPT_SOURCE.md +80 -37
  9. package/CHANGELOG.md +393 -23
  10. package/CLAUDE.md +80 -37
  11. package/GEMINI.md +80 -37
  12. package/docs/my-claude/feat-sharon-JT-1790247240-socket/branch-transfer.md +14 -0
  13. package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-preparation.json +40 -0
  14. package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-verification.md +41 -0
  15. package/docs/my-claude/feat-sharon-JT-1790247240-socket/implementation-ledger.md +87 -0
  16. package/docs/my-claude/feat-sharon-JT-1790247240-socket/module-report.md +73 -0
  17. package/docs/my-claude/feat-sharon-JT-1790247240-socket/plan.md +309 -0
  18. package/docs/my-claude/feat-sharon-JT-1790247240-socket/test-cases.md +245 -0
  19. package/docs/my-claude/feat-sharon-JT-1791180540-onesignal/transfer.md +9 -0
  20. package/package.json +1 -1
  21. package/scripts/auto-version.js +1 -0
  22. package/scripts/branch-auto-npm-publish.js +9 -2
  23. package/src/api/payment.js +1 -0
  24. package/src/machine/auth_otp_v3.js +59 -20
  25. package/src/machine/honor_board_cash.js +15 -18
  26. package/src/machine/reward_cash.js +2 -2
  27. package/src/machine/user_sign_up.js +3 -0
  28. package/src/machine/websocket.js +380 -311
  29. package/src/machine/withdraw/withdraw_manual_cash.js +7 -4
  30. package/src/util/constant.js +6 -1
  31. package/src/util/socketPolicy.js +57 -0
  32. package/test/auth_otp_v3.test.js +323 -0
  33. package/test/withdraw_manual_cash.test.js +149 -0
  34. package/tests/websocket.test.mjs +779 -0
@@ -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, sentry } = request.config
6
- const maxReconnectCount = 3
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, // 0: 未連線, 1: 連線中, 2: 連線成功,
30
+ connectStatus: 0,
15
31
  connectError: null,
16
32
  analytics: null,
17
- url: `https://storage.googleapis.com/${bucketName}/site_resources/${clientId}/target/target.json`,
18
- socketURL: 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
- states: {
22
- idle: {},
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
- SET_CONNECTED: {
77
- actions: 'setSocket',
78
- },
79
- CONNECT_ERROR: {
80
- actions: 'setConnectError',
81
- },
82
- DISCONNECT: {
83
- actions: 'setDisconnected',
84
- },
85
- DISCONNECT_SOCKET: {
86
- actions: 'disconnectSocket',
87
- target: 'idle',
88
- },
89
- CHECK_SOCKET: {
90
- target: 'checkSocketConnect',
91
- cond: 'isNeedConnect',
92
- },
93
- ACTIVITY_INFO: {
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
- saveSocketURL: assign((context, event) => {
110
- const { socketURL } = event.data
111
- return { socketURL }
112
- }),
113
- setSocket: assign((context, event) => {
114
- console.log('[socket][setSocket] clientSocket:', event.data.id)
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
- setConnectError: assign((context, event) => {
121
- const error = event.data
122
- return {
123
- connectError: error,
124
- connectStatus: 0, // 0: 未連線, 1: 連線中, 2: 連線成功
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
- setConnecting: assign((context, event) => {
128
- return {
129
- connectStatus: 1, // 0: 未連線, 1: 連線中, 2: 連線成功
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
- disconnectSocket: assign((context, event) => {
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
- return { clientSocket }
141
- }),
142
- setDisconnected: assign((context, event) => {
143
- const { reason } = event
144
- const { analytics } = context
145
- if (reason !== 'io client disconnect') {
146
- analytics?.push({
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
- return {
152
- connectStatus: 0, // 0: 未連線, 1: 連線中, 2: 連線成功
143
+ const clearSession = () => {
144
+ verifiedUid = null
145
+ archive = null
146
+ hadSession = false
147
+ dedupe = createPushDedupe()
148
+ claims = new Map()
153
149
  }
154
- }),
155
- setActivityInfo: assign((context, event) => {
156
- const { data } = event
157
- return { socketData: data }
158
- }),
159
- clearSocketData: assign({
160
- socketData: (_, event) => {},
161
- }),
162
- setAnalytics: assign({
163
- analytics: (_, event) => event.data,
164
- }),
165
- pushEvent: assign((context, value) => {
166
- const { analytics } = context
167
- const { data, event, isTracking } = value.data
168
- if (isTracking) {
169
- analytics?.push(
170
- {
171
- event: event,
172
- paymentMethod: data.paymentMethod,
173
- transaction_id: data.transactionId,
174
- currency: data.currency,
175
- value: data.value,
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
- if (event === 'purchase' && data?.isFirst === true && isTracking) {
183
- analytics?.push(
184
- {
185
- event: 'first_deposit',
186
- paymentMethod: data.paymentMethod,
187
- transaction_id: data.transactionId,
188
- currency: data.currency,
189
- value: data.value,
190
- app_value: data.value,
191
- },
192
- { eventID: data.transactionId }
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
- setReconnectCount: assign((context, event) => {
197
- let { reconnectCount } = context
198
- reconnectCount++
199
- return { reconnectCount }
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
- isReconnect: (context, event) => {
213
- const { reconnectCount, connectError } = context
214
- return reconnectCount < maxReconnectCount && connectError === 'io server disconnect'
215
- },
216
- },
217
- services: {
218
- fetchSocket: async (context, event) => {
219
- // 取得 Socket 連線資訊及選線
220
- const { url } = context
221
- const socketTester = new SocketTester(url, context.socketURL)
222
- const socketURL = await socketTester.test()
223
- console.log('[socket][fetchSocket] socketURL:', socketURL)
224
- return { socketURL }
225
- },
226
- connectSocket: async (context, event) => {
227
- // 連接 Socket
228
- const { socketURL } = context
229
- const authToken = request.getToken()
230
- console.log('[socket][connectSocket] socketURL:', socketURL)
231
- const clientSocket = io(`${socketURL}/frontend`, {
232
- withCredentials: true,
233
- forceNew: true,
234
- transports: ['websocket', 'polling'],
235
- auth: {
236
- Authorization: authToken,
237
- },
238
- })
239
- return new Promise((resolve, reject) => {
240
- clientSocket.on('connect', () => {
241
- console.log('[socket][connect] success', clientSocket.id)
242
- resolve(clientSocket) // 成功後返回 socket 實例
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
- clientSocket.on('connect_error', (error) => {
246
- console.log('[socket][connect_error] error', error.message)
247
- reject(error.message) // 連接錯誤
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
- listenToSocketEvents: (context) => (callback) => {
252
- // 監聽事件
253
- const { clientSocket } = context
254
-
255
- if (!clientSocket) {
256
- console.log('[socket][listenToSocketEvents] Socket is not connected')
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
- // 監聽 activity-info 事件
260
- clientSocket.on('activity-info', (data) => {
261
- console.log('[socket][activity-info]:', data)
262
- callback({ type: 'ACTIVITY_INFO', data })
263
- callback({ type: 'PUSH_ANALYTICS', data })
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
- callback({ type: 'PUSH_ANALYTICS', data })
286
- })
287
-
288
- // 監聽 'connect' 事件
289
- clientSocket.on('connect', () => {
290
- callback({ type: 'SET_CONNECTED', data: clientSocket })
291
- })
292
-
293
- // 連線錯誤時觸發此事件'connect_error'
294
- clientSocket.on('connect_error', (error) => {
295
- callback({ type: 'CONNECT_ERROR', data: error.message })
296
- })
297
-
298
- // 斷開連線時觸發此事件'disconnect'
299
- clientSocket.on('disconnect', (data) => {
300
- callback({ type: 'DISCONNECT', reason: data })
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
- class SocketTester {
309
- constructor(url, fallbackUrl) {
310
- this.url = url
311
- this.socket = []
312
- this.fallbackUrl = fallbackUrl
313
- }
314
-
315
- async init() {
316
- const target = await fetch(this.url)
317
- const { socket } = await target.json()
318
- this.socket = socket
319
- console.log(`[socket] this.socket:`, this.socket)
320
- }
321
-
322
- async test() {
323
- try {
324
- if (this.socket.length === 0) {
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
  }