@jetthai/cuora 1.2.0 → 2.0.0-beta.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 (166) hide show
  1. package/BREAKING_CHANGES.md +9 -0
  2. package/CHANGELOG.md +36 -0
  3. package/package.json +5 -2
  4. package/resetGitBranch.sh +16 -16
  5. package/src/api/account.js +8 -0
  6. package/src/api/auth.js +1 -1
  7. package/src/api/common.js +6 -1
  8. package/src/api/index.js +3 -1
  9. package/src/api/otp.js +5 -0
  10. package/src/api/user.js +1 -0
  11. package/src/machine/activity/activity.js +23 -19
  12. package/src/machine/activity/activity_cash.js +27 -22
  13. package/src/machine/activity/cash_rain_activity.js +1 -0
  14. package/src/machine/activity/continue_deposit_activity.js +1 -0
  15. package/src/machine/activity/deposit_activity.js +1 -0
  16. package/src/machine/activity/diamond_shop_activity_cash.js +7 -0
  17. package/src/machine/activity/diamond_shop_activity_fc.js +1 -0
  18. package/src/machine/activity/diamond_shop_activity_vn.js +1 -0
  19. package/src/machine/activity/fafafa_activity.js +1 -0
  20. package/src/machine/activity/friend_invite_friends_activity.js +7 -8
  21. package/src/machine/activity/instant_rebate_activity.js +1 -0
  22. package/src/machine/activity/invite_friends_activity.js +1 -0
  23. package/src/machine/activity/jackpot.js +1 -0
  24. package/src/machine/activity/mini_game_activity.js +1 -0
  25. package/src/machine/activity/otp_verified_activity.js +1 -0
  26. package/src/machine/activity/ranking_activity.js +1 -0
  27. package/src/machine/activity/return_bonus_activity.js +3 -1
  28. package/src/machine/activity/roulette_activity_v2.js +6 -0
  29. package/src/machine/activity/sign_in_activity.js +1 -0
  30. package/src/machine/activity/sign_in_monthly_activity.js +2 -1
  31. package/src/machine/activity/specify_bets_activity.js +1 -0
  32. package/src/machine/activity/specify_turnover_activity.js +1 -0
  33. package/src/machine/activity/time_bomb_activity.js +1 -0
  34. package/src/machine/activity/vip_card_activity.js +1 -0
  35. package/src/machine/auth.js +21 -8
  36. package/src/machine/auth_otp_v2.js +1 -0
  37. package/src/machine/auth_otp_v3.js +48 -11
  38. package/src/machine/bank_binding.js +1 -0
  39. package/src/machine/bank_binding_amb.js +1 -0
  40. package/src/machine/bonus.js +1 -0
  41. package/src/machine/common.js +41 -7
  42. package/src/machine/deposit/amb.js +1 -0
  43. package/src/machine/deposit/crypto_bank.js +20 -5
  44. package/src/machine/deposit/crypto_bank_cash.js +35 -9
  45. package/src/machine/deposit/crypto_qrcode.js +11 -1
  46. package/src/machine/deposit/crypto_qrcode_cash.js +24 -1
  47. package/src/machine/deposit/crypto_way.js +11 -5
  48. package/src/machine/deposit/crypto_way_cash.js +15 -6
  49. package/src/machine/deposit/deposit_fc.js +1 -0
  50. package/src/machine/deposit/direct.js +1 -0
  51. package/src/machine/deposit/direct_cash.js +1 -0
  52. package/src/machine/deposit/float.js +1 -0
  53. package/src/machine/deposit/krway.js +1 -0
  54. package/src/machine/deposit/loadcard_cash.js +2 -1
  55. package/src/machine/deposit/loadcard_vn.js +1 -0
  56. package/src/machine/deposit/manual_cash.js +18 -10
  57. package/src/machine/deposit/manual_vn.js +10 -5
  58. package/src/machine/deposit/qrcode_cash.js +6 -5
  59. package/src/machine/deposit/qrcode_v2.js +1 -0
  60. package/src/machine/deposit/usdt.js +23 -4
  61. package/src/machine/deposit/usdt_cash.js +15 -1
  62. package/src/machine/deposit/virtual_bank_cash.js +11 -9
  63. package/src/machine/deposit/virtual_bank_vn.js +1 -0
  64. package/src/machine/deposit/vpay.js +7 -0
  65. package/src/machine/error.js +1 -0
  66. package/src/machine/game_betslip.js +1 -0
  67. package/src/machine/game_favorite_v2.js +1 -0
  68. package/src/machine/game_hot_new.js +14 -2
  69. package/src/machine/game_info.js +5 -0
  70. package/src/machine/game_replay.js +1 -0
  71. package/src/machine/game_search_cash.js +13 -2
  72. package/src/machine/game_search_v2.js +1 -0
  73. package/src/machine/game_v2_1.js +129 -50
  74. package/src/machine/honor_board.js +19 -7
  75. package/src/machine/honor_board_cash.js +11 -8
  76. package/src/machine/inbox.js +93 -43
  77. package/src/machine/leaderboard.js +1 -0
  78. package/src/machine/merge.js +1 -0
  79. package/src/machine/navbar.js +3 -1
  80. package/src/machine/payment_data.js +1 -0
  81. package/src/machine/promotions.js +11 -18
  82. package/src/machine/ranking.js +5 -2
  83. package/src/machine/reward.js +1 -0
  84. package/src/machine/reward_cash.js +1 -0
  85. package/src/machine/reward_fc.js +1 -0
  86. package/src/machine/roulette_v2.js +18 -26
  87. package/src/machine/setting.js +1 -0
  88. package/src/machine/side.js +10 -4
  89. package/src/machine/side_cash.js +1 -0
  90. package/src/machine/side_v2.js +38 -24
  91. package/src/machine/user_info.js +1 -0
  92. package/src/machine/user_photo.js +1 -0
  93. package/src/machine/user_reset_password.js +5 -2
  94. package/src/machine/user_sign_up.js +1 -0
  95. package/src/machine/vip_table.js +1 -0
  96. package/src/machine/websocket.js +42 -14
  97. package/src/machine/welcome.js +1 -0
  98. package/src/machine/withdraw/withdraw_crypto_cash.js +1 -0
  99. package/src/machine/withdraw/withdraw_krway.js +1 -0
  100. package/src/machine/withdraw/withdraw_manual.js +16 -8
  101. package/src/machine/withdraw/withdraw_manual_cash.js +1 -0
  102. package/src/request/request.js +34 -30
  103. package/src/util/deviceToken.js +7 -6
  104. package/src/util/storage.js +4 -3
  105. package/test/api.behavior.test.js +69 -0
  106. package/test/api.contract.test.js +18 -0
  107. package/test/config.test.js +27 -0
  108. package/test/deviceToken.test.js +139 -0
  109. package/test/helpers.coverage.test.js +11 -0
  110. package/test/helpers.js +91 -0
  111. package/test/index.exports.test.js +14 -0
  112. package/test/machine.activity.core.coverage.test.js +337 -0
  113. package/test/machine.activity.gap.coverage.test.js +252 -0
  114. package/test/machine.activity.more.coverage.test.js +180 -0
  115. package/test/machine.activity_plus_and_binding_amb.coverage.test.js +201 -0
  116. package/test/machine.activity_timer_bonus.coverage.test.js +136 -0
  117. package/test/machine.activity_welcome.low.coverage.test.js +211 -0
  118. package/test/machine.amb_rewardfc_websocket.more.coverage.test.js +201 -0
  119. package/test/machine.auth.coverage.test.js +215 -0
  120. package/test/machine.bank_binding.test.js +143 -0
  121. package/test/machine.binding_otp_krway.coverage.test.js +223 -0
  122. package/test/machine.contract.test.js +50 -0
  123. package/test/machine.crypto_bank.coverage.test.js +270 -0
  124. package/test/machine.crypto_way.coverage.test.js +108 -0
  125. package/test/machine.crypto_way_cash.coverage.test.js +114 -0
  126. package/test/machine.definition.test.js +137 -0
  127. package/test/machine.deposit.manual.coverage.test.js +365 -0
  128. package/test/machine.deposit_fc.coverage.test.js +126 -0
  129. package/test/machine.direct.coverage.test.js +96 -0
  130. package/test/machine.direct_cash.coverage.test.js +108 -0
  131. package/test/machine.error.coverage.test.js +37 -0
  132. package/test/machine.events.test.js +126 -0
  133. package/test/machine.favorite_jackpot.coverage.test.js +82 -0
  134. package/test/machine.float.coverage.test.js +136 -0
  135. package/test/machine.flow.test.js +226 -0
  136. package/test/machine.game_hot_new_vip_table.coverage.test.js +105 -0
  137. package/test/machine.game_search_cash.coverage.test.js +195 -0
  138. package/test/machine.game_search_v2.test.js +199 -0
  139. package/test/machine.game_user_profile.coverage.test.js +100 -0
  140. package/test/machine.honor_board.test.js +148 -0
  141. package/test/machine.inbox.common.coverage.test.js +304 -0
  142. package/test/machine.loadcard_cash.coverage.test.js +101 -0
  143. package/test/machine.loadcard_vn.coverage.test.js +122 -0
  144. package/test/machine.misc.coverage.test.js +361 -0
  145. package/test/machine.more2.coverage.test.js +261 -0
  146. package/test/machine.options.execution.test.js +272 -0
  147. package/test/machine.priority.coverage.test.js +629 -0
  148. package/test/machine.qrcode_cash.coverage.test.js +107 -0
  149. package/test/machine.qrcode_v2.coverage.test.js +121 -0
  150. package/test/machine.regression.test.js +82 -0
  151. package/test/machine.roulette_v2.test.js +142 -0
  152. package/test/machine.side_reward_reset.coverage.test.js +220 -0
  153. package/test/machine.targeted.coverage.test.js +313 -0
  154. package/test/machine.usdt.coverage.test.js +95 -0
  155. package/test/machine.usdt_cash.coverage.test.js +73 -0
  156. package/test/machine.vip_card_activity.test.js +114 -0
  157. package/test/machine.virtual_bank_cash.coverage.test.js +105 -0
  158. package/test/machine.virtual_bank_vn.coverage.test.js +105 -0
  159. package/test/machine.vpay.coverage.test.js +142 -0
  160. package/test/machine.withdraw_crypto_cash.coverage.test.js +166 -0
  161. package/test/machine.withdraw_krway.coverage.test.js +123 -0
  162. package/test/machine.withdraw_manual.coverage.test.js +185 -0
  163. package/test/machine.withdraw_manual_cash.coverage.test.js +123 -0
  164. package/test/request.test.js +325 -0
  165. package/test/util.storage.errors.test.js +47 -0
  166. package/test/util.test.js +41 -0
@@ -140,7 +140,29 @@ const supportVersion2List = [
140
140
  'game/list/v3/gameInfo',
141
141
  'payment/v2/uploadCommonSlip',
142
142
  'game/history/options',
143
+ // 09/30
144
+ 'pixel',
145
+ // 10/09
146
+ 'account-binding/status',
147
+ 'account-binding/bind',
148
+ 'account-binding/acknowledge',
149
+ 'account-binding/bind-third-party',
150
+ 'account-binding/bind-password',
151
+ 'account-binding/reset-otp',
152
+ // 11/10
153
+ 'otp-verification-point/verify',
154
+ 'otp-verification-point/acknowledge',
155
+ 'otp-verification-point/reset-otp',
156
+ // 12/02
157
+ 'user-info/get-profile',
143
158
  ]
159
+ const supportVersion2Matchers = supportVersion2List.map((supportedUrl) => {
160
+ if (supportedUrl.includes(':')) {
161
+ const pattern = supportedUrl.replace(/:[^/]+/g, '[^/]+')
162
+ return new RegExp(`^${pattern}$`)
163
+ }
164
+ return supportedUrl
165
+ })
144
166
 
145
167
  function isValid(value) {
146
168
  return value !== undefined && value !== null
@@ -187,9 +209,10 @@ export default class Request {
187
209
  this.axios.interceptors.request.use((axiosConfig) => {
188
210
  axiosConfig.headers['X-TH1GAMES-VERSION'] = this.config.version
189
211
  axiosConfig.headers['X-TH1GAMES-PLATFORM'] = this.config.platform
190
- if (this.getToken()) {
212
+ const token = this.getToken()
213
+ if (token) {
191
214
  // 為了支援V2版本的API接口新增Bearer來進行身份驗證
192
- axiosConfig.headers.Authorization = `Bearer ${this.getToken()}`
215
+ axiosConfig.headers.Authorization = `Bearer ${token}`
193
216
  }
194
217
  return axiosConfig
195
218
  })
@@ -203,13 +226,6 @@ export default class Request {
203
226
  },
204
227
  (error) => {
205
228
  if (error.message === 'Network Error' || error.message === 'Request failed with status code 404') {
206
- const errData = (error || {}).response || {}
207
- const errorDetails = {
208
- data: errData.config?.data,
209
- params: errData.config?.params,
210
- url: errData.config?.url,
211
- status: errData.status,
212
- }
213
229
  this.sentry?.captureException(`ERR_998:${error.message}`)
214
230
  return Promise.reject({ code: 'ERR_998' })
215
231
  }
@@ -228,13 +244,11 @@ export default class Request {
228
244
  this._checkToken(req)
229
245
 
230
246
  const requestConfig = this._createConfig(req, cancelToken)
231
- // console.log('*請求資料Check', requestConfig)
232
247
  const configUrls = ['getConfig', 'get-config']
233
248
  if (this.isBlocked && !configUrls.includes(requestConfig.url)) {
234
- // 狀態是維護中&請求非siteConfig,終止所有的請求,除了維護頁需要的資料(siteConfig)
235
- // console.log('%c*禁止的請求目標', requestConfig)
249
+ // 狀態是維護中且請求非 site config,回傳明確錯誤避免呼叫端拿到 undefined
250
+ throw { code: 'ERR_MAINTENANCE_BLOCKED', url: requestConfig.url }
236
251
  } else {
237
- // console.log('%c*允許的請求目標', requestConfig)
238
252
  const { data } = await this.axios.request(requestConfig)
239
253
  return data
240
254
  }
@@ -267,28 +281,18 @@ export default class Request {
267
281
  const { method, url, params, isPublic, isFormData, headers } = req
268
282
  let fullURL = this.config.fullURL
269
283
  let urlName = url
284
+
270
285
  // 有些API會將參數(/?)直接帶在URL上,所以要將參數排除
271
286
  const cleanUrl = url.split('?')[0]
272
-
273
- const isV2Supported = supportVersion2List.some((supportedUrl) => {
274
- // 如果包含動態參數(:parameter),則使用模式匹配
275
- if (supportedUrl.includes(':')) {
276
- const pattern = supportedUrl.replace(/:[^/]+/g, '[^/]+')
277
- const regex = new RegExp(`^${pattern}$`)
278
- return regex.test(cleanUrl)
287
+ const isV2Supported = supportVersion2Matchers.some((matcher) => {
288
+ if (matcher instanceof RegExp) {
289
+ return matcher.test(cleanUrl)
279
290
  }
280
- return supportedUrl === cleanUrl
291
+ return matcher === cleanUrl
281
292
  })
282
-
283
- // 目前全站都支援V2,若有需要限制為V1的站點可以填入,此段等轉換全部完成之後就可以移除了
284
- const supportV2Toggle = [''].includes(this.config?.clientId)
285
-
286
- if (isV2Supported && !supportV2Toggle) {
287
- fullURL = fullURL.replace('/v1/', '/v2/')
293
+ // 符合轉換規則的API進行路徑調整
294
+ if (isV2Supported) {
288
295
  urlName = this._convertUrlToKebabCase(url)
289
- // console.log(`*[DEV_ONLY]V2`, 'url:', urlName)
290
- } else {
291
- // console.log(`*[DEV_ONLY]V2-不支援:`, 'url:', urlName)
292
296
  }
293
297
 
294
298
  if (isFormData) {
@@ -1,21 +1,22 @@
1
- import uniqBy from 'lodash/uniqBy'
1
+ import uniqBy from 'lodash/uniqBy.js'
2
2
  import { load, defaultEndpoint } from '../lib/fingerprint_v3_11_12.js'
3
3
 
4
4
  const reg = /fnapi\d*/
5
5
 
6
- const getDeviceToken = async ({ fpToken, sentry, hosts, enable = true }) => {
6
+ const getDeviceToken = async ({ fpToken, sentry, hosts, enable = true, loader = load }) => {
7
7
  if (!enable) {
8
8
  return
9
9
  }
10
10
 
11
11
  let dt, endpoints
12
12
  try {
13
+ const hostList = Array.isArray(hosts) ? hosts : []
13
14
  endpoints = uniqBy(
14
- hosts.map((host) => host.replace(reg, 'fp')),
15
+ hostList.map((host) => host.replace(reg, 'fp')),
15
16
  (url) => url
16
17
  )
17
18
 
18
- const fp = await load({ endpoint: [...endpoints, defaultEndpoint] })
19
+ const fp = await loader({ endpoint: [...endpoints, defaultEndpoint] })
19
20
  const result = await fp.get({ timeout: 30000 })
20
21
  dt = result.visitorId
21
22
 
@@ -33,7 +34,7 @@ const getDeviceToken = async ({ fpToken, sentry, hosts, enable = true }) => {
33
34
  }
34
35
 
35
36
  // 重試機制,最多嘗試 maxRetries 次,每次間隔 intervalMs 毫秒
36
- const getDeviceTokenWithRetry = async ({ fpToken, sentry, hosts, enable = true, maxRetries = 3, intervalMs = 1000 }) => {
37
+ const getDeviceTokenWithRetry = async ({ fpToken, sentry, hosts, enable = true, maxRetries = 3, intervalMs = 1000, loader = load }) => {
37
38
  if (!enable) {
38
39
  return
39
40
  }
@@ -42,7 +43,7 @@ const getDeviceTokenWithRetry = async ({ fpToken, sentry, hosts, enable = true,
42
43
  // 設定重試次數
43
44
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
44
45
  try {
45
- const deviceToken = await getDeviceToken({ fpToken, sentry, hosts, enable })
46
+ const deviceToken = await getDeviceToken({ fpToken, sentry, hosts, enable, loader })
46
47
  if (deviceToken) return deviceToken
47
48
  throw new Error('No device token received')
48
49
  } catch (error) {
@@ -13,7 +13,7 @@ export default {
13
13
  }
14
14
 
15
15
  const item = JSON.parse(itemStr)
16
- if (item.expiry && new Date().getTime() > item.expiry) {
16
+ if (Object.prototype.hasOwnProperty.call(item, 'expiry') && Date.now() >= item.expiry) {
17
17
  localStorage.removeItem(name)
18
18
  return null
19
19
  }
@@ -23,8 +23,9 @@ export default {
23
23
  set(name, value, options) {
24
24
  const item = { value }
25
25
 
26
- if (options?.maxAge) {
27
- item.expiry = new Date().getTime() + options.maxAge * 1000
26
+ const maxAge = Number(options?.maxAge)
27
+ if (Number.isFinite(maxAge)) {
28
+ item.expiry = Date.now() + maxAge * 1000
28
29
  }
29
30
  try {
30
31
  localStorage.setItem(name, JSON.stringify(item))
@@ -0,0 +1,69 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import api from '../src/api/index.js'
5
+
6
+ test('auth.register builds querystring and payload correctly', () => {
7
+ const req = api.auth.register({
8
+ channel: 'web',
9
+ subchannel: 'sub',
10
+ ac: 'ac1',
11
+ fc: null,
12
+ dt: 'dt1',
13
+ username: 'u1',
14
+ password: 'p1',
15
+ })
16
+
17
+ assert.equal(req.method, 'post')
18
+ assert.equal(req.url, 'register?channel=web&subchannel=sub&ac=ac1')
19
+ assert.equal(req.params.dt, 'dt1')
20
+ assert.equal(req.params.username, 'u1')
21
+ assert.equal(req.isPublic, true)
22
+ })
23
+
24
+ test('common API endpoints keep expected paths', () => {
25
+ assert.equal(api.common.getConfig({ appSecret: 's' }).url, 'getConfig')
26
+ assert.equal(api.common.broadcast({ appSecret: 's' }).url, 'broadcast')
27
+ assert.equal(api.common.sendPixel({ appSecret: 's' }).method, 'post')
28
+ })
29
+
30
+ test('game search trace and replay endpoints map params', () => {
31
+ const trace = api.game.setGameSearchTrace({
32
+ traceId: 't1',
33
+ tagId: 'tag',
34
+ gameCode: 'g1',
35
+ query: 'q',
36
+ })
37
+ assert.equal(trace.url, 'game/search/trace')
38
+ assert.equal(trace.method, 'post')
39
+ assert.equal(trace.params.traceId, 't1')
40
+
41
+ const replay = api.game.getGameReplayInfo({ providerId: 'P', seqNo: 'S', lang: 'en', appSecret: 'sec' })
42
+ assert.equal(replay.url, 'game/gameReplay')
43
+ assert.equal(replay.isPublic, true)
44
+ })
45
+
46
+ test('payment APIs build dynamic method paths', () => {
47
+ assert.equal(api.payment.getBankList('crypto').url, 'payment/v2/crypto/getBankList')
48
+ assert.equal(api.payment.checkTransaction('manual').url, 'payment/v2/manual/checkTransaction')
49
+ assert.equal(api.payment.getDepositExpectedResult({ method: 'manual', amount: 10 }).url, 'payment/v2/manual/expected/result')
50
+ })
51
+
52
+ test('user and otp APIs keep security-sensitive paths', () => {
53
+ assert.equal(api.user.passwordV2RecoveryInit({ provider: 'account', username: 'u', appSecret: 's' }).url, 'recovery/v2/initiate')
54
+ assert.equal(api.user.verifyV2Initiate({ strategy: 'phone' }).url, '/verify/v2/initiate')
55
+
56
+ const verify = api.otp.verification({ requestId: 'r1', code: '1234' })
57
+ assert.equal(verify.url, 'otp-verification-point/verify')
58
+ assert.equal(verify.method, 'POST')
59
+ })
60
+
61
+ test('activity APIs retain public/private intent', () => {
62
+ const list = api.activity.getActivityList({ appSecret: 's' })
63
+ assert.equal(list.url, 'activities/list')
64
+ assert.equal(list.isPublic, true)
65
+
66
+ const detail = api.activity.getActivityDetail({ activityNo: 1, appSecret: 's' })
67
+ assert.equal(detail.url, 'activities')
68
+ assert.equal(detail.isPublic, undefined)
69
+ })
@@ -0,0 +1,18 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import api from '../src/api/index.js'
5
+ import { callWithFallback } from './helpers.js'
6
+
7
+ for (const [moduleName, moduleApi] of Object.entries(api)) {
8
+ test(`api contract: ${moduleName} endpoints return request descriptor`, () => {
9
+ assert.equal(typeof moduleApi, 'object')
10
+
11
+ for (const [fnName, endpointFactory] of Object.entries(moduleApi)) {
12
+ assert.equal(typeof endpointFactory, 'function', `${moduleName}.${fnName} should be a function`)
13
+ const requestDescriptor = callWithFallback(endpointFactory)
14
+ assert.equal(typeof requestDescriptor.url, 'string', `${moduleName}.${fnName} should return url`)
15
+ assert.equal(typeof requestDescriptor.method, 'string', `${moduleName}.${fnName} should return method`)
16
+ }
17
+ })
18
+ }
@@ -0,0 +1,27 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import Config from '../src/request/config.js'
5
+
6
+ test('config builds fullURL and supports setApiURL', () => {
7
+ const config = new Config({
8
+ apiURL: 'https://api.example.com',
9
+ apiVersion: 'v2',
10
+ clientId: 'cid',
11
+ appSecret: 'secret',
12
+ platform: 'web',
13
+ version: '1.0.0',
14
+ fpToken: 'fp-token',
15
+ sentry: null,
16
+ defaultChannel: 'ch',
17
+ defaultSubchannel: 'sub',
18
+ socketURL: 'wss://socket.example.com',
19
+ bucketName: 'bucket',
20
+ })
21
+
22
+ assert.equal(config.fullURL, 'https://api.example.com/v2/cid')
23
+
24
+ config.setApiURL('https://api2.example.com/root')
25
+ assert.equal(config.apiURL, 'https://api2.example.com/root')
26
+ assert.equal(config.fullURL, 'https://api2.example.com/root/v2/cid')
27
+ })
@@ -0,0 +1,139 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { getDeviceToken, getDeviceTokenWithRetry } from '../src/util/deviceToken.js'
5
+
6
+ test('getDeviceToken returns undefined when disabled', async () => {
7
+ const result = await getDeviceToken({
8
+ enable: false,
9
+ fpToken: 'fp',
10
+ hosts: ['https://fnapi1.example.com'],
11
+ })
12
+ assert.equal(result, undefined)
13
+ })
14
+
15
+ test('getDeviceToken handles host/input errors and reports to sentry', async () => {
16
+ const sentryCalls = []
17
+ const sentry = {
18
+ setTag: (...args) => sentryCalls.push(['setTag', ...args]),
19
+ captureException: (...args) => sentryCalls.push(['captureException', ...args]),
20
+ }
21
+
22
+ const result = await getDeviceToken({
23
+ enable: true,
24
+ fpToken: 'fp',
25
+ hosts: null,
26
+ sentry,
27
+ })
28
+
29
+ assert.equal(result, undefined)
30
+ assert.equal(
31
+ sentryCalls.some((entry) => entry[0] === 'captureException'),
32
+ true
33
+ )
34
+ })
35
+
36
+ test('getDeviceTokenWithRetry returns undefined when disabled', async () => {
37
+ const result = await getDeviceTokenWithRetry({
38
+ enable: false,
39
+ fpToken: 'fp',
40
+ hosts: ['https://fnapi1.example.com'],
41
+ maxRetries: 2,
42
+ intervalMs: 1,
43
+ })
44
+ assert.equal(result, undefined)
45
+ })
46
+
47
+ test('getDeviceTokenWithRetry retries and throws after maxRetries', async () => {
48
+ await assert.rejects(
49
+ getDeviceTokenWithRetry({
50
+ enable: true,
51
+ fpToken: 'fp',
52
+ hosts: [],
53
+ maxRetries: 2,
54
+ intervalMs: 1,
55
+ })
56
+ )
57
+ })
58
+
59
+ test('getDeviceToken returns visitorId when loader succeeds', async () => {
60
+ const sentryCalls = []
61
+ const sentry = {
62
+ setTag: (...args) => sentryCalls.push(['setTag', ...args]),
63
+ captureException: (...args) => sentryCalls.push(['captureException', ...args]),
64
+ }
65
+ const loader = async () => ({
66
+ get: async () => ({ visitorId: 'dt-ok' }),
67
+ })
68
+
69
+ const result = await getDeviceToken({
70
+ enable: true,
71
+ fpToken: 'fp',
72
+ hosts: ['https://fnapi1.example.com'],
73
+ sentry,
74
+ loader,
75
+ })
76
+
77
+ assert.equal(result, 'dt-ok')
78
+ assert.equal(
79
+ sentryCalls.some((entry) => entry[0] === 'setTag' && entry[1] === 'dt' && entry[2] === 'dt-ok'),
80
+ true
81
+ )
82
+ })
83
+
84
+ test('getDeviceTokenWithRetry returns token when loader eventually succeeds', async () => {
85
+ let count = 0
86
+ const loader = async () => ({
87
+ get: async () => {
88
+ count += 1
89
+ return { visitorId: count >= 2 ? 'dt-retry' : null }
90
+ },
91
+ })
92
+
93
+ const result = await getDeviceTokenWithRetry({
94
+ enable: true,
95
+ fpToken: 'fp',
96
+ hosts: ['https://fnapi1.example.com'],
97
+ maxRetries: 3,
98
+ intervalMs: 1,
99
+ loader,
100
+ })
101
+
102
+ assert.equal(result, 'dt-retry')
103
+ })
104
+
105
+ test('getDeviceToken normalizes and deduplicates hosts before loader', async () => {
106
+ let capturedEndpoints = null
107
+ const loader = async ({ endpoint }) => {
108
+ capturedEndpoints = endpoint
109
+ return { get: async () => ({ visitorId: 'dt-hosts' }) }
110
+ }
111
+
112
+ const result = await getDeviceToken({
113
+ enable: true,
114
+ fpToken: 'fp',
115
+ hosts: ['https://fnapi1.example.com', 'https://fnapi2.example.com'],
116
+ loader,
117
+ })
118
+
119
+ assert.equal(result, 'dt-hosts')
120
+ assert.equal(Array.isArray(capturedEndpoints), true)
121
+ // fnapi* should be normalized to fp and then deduplicated into one host plus default endpoint
122
+ assert.equal(
123
+ capturedEndpoints.some((url) => String(url).includes('fp.example.com')),
124
+ true
125
+ )
126
+ assert.equal(capturedEndpoints.length >= 2, true)
127
+ })
128
+
129
+ test('getDeviceTokenWithRetry returns undefined when maxRetries is zero', async () => {
130
+ const result = await getDeviceTokenWithRetry({
131
+ enable: true,
132
+ fpToken: 'fp',
133
+ hosts: ['https://fnapi1.example.com'],
134
+ maxRetries: 0,
135
+ intervalMs: 1,
136
+ loader: async () => ({ get: async () => ({ visitorId: 'never-used' }) }),
137
+ })
138
+ assert.equal(result, undefined)
139
+ })
@@ -0,0 +1,11 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { callWithFallback } from './helpers.js'
5
+
6
+ test('callWithFallback throws default error when no candidate returns object', () => {
7
+ assert.throws(
8
+ () => callWithFallback(() => null),
9
+ (error) => error instanceof Error && error.message.includes('Function did not return an object')
10
+ )
11
+ })
@@ -0,0 +1,91 @@
1
+ export function createLocalStorageMock() {
2
+ const store = new Map()
3
+ return {
4
+ getItem(key) {
5
+ return store.has(key) ? store.get(key) : null
6
+ },
7
+ setItem(key, value) {
8
+ store.set(key, String(value))
9
+ },
10
+ removeItem(key) {
11
+ store.delete(key)
12
+ },
13
+ clear() {
14
+ store.clear()
15
+ },
16
+ }
17
+ }
18
+
19
+ export function callWithFallback(fn) {
20
+ const candidates = [
21
+ [],
22
+ [{}],
23
+ [
24
+ {
25
+ appSecret: 'app-secret',
26
+ method: 'manual',
27
+ paymentMethod: 'manual',
28
+ provider: 'google',
29
+ username: 'user',
30
+ password: 'pwd',
31
+ channel: 'channel',
32
+ subchannel: 'subchannel',
33
+ payload: { amount: 1 },
34
+ type: 'DEPOSIT',
35
+ amount: 100,
36
+ },
37
+ ],
38
+ ['manual'],
39
+ [1],
40
+ [undefined],
41
+ ]
42
+
43
+ let lastError
44
+ for (const args of candidates) {
45
+ try {
46
+ const result = fn(...args)
47
+ if (result && typeof result === 'object') {
48
+ return result
49
+ }
50
+ } catch (error) {
51
+ lastError = error
52
+ }
53
+ }
54
+
55
+ throw lastError || new Error('Function did not return an object with fallback arguments')
56
+ }
57
+
58
+ export function createAxiosMock() {
59
+ const handlers = {
60
+ requestSuccess: null,
61
+ responseSuccess: null,
62
+ responseError: null,
63
+ }
64
+
65
+ return {
66
+ handlers,
67
+ axios: {
68
+ defaults: {},
69
+ CancelToken: {
70
+ source: () => ({
71
+ token: { id: Math.random().toString(16).slice(2) },
72
+ cancel: () => {},
73
+ }),
74
+ },
75
+ interceptors: {
76
+ request: {
77
+ use: (success) => {
78
+ handlers.requestSuccess = success
79
+ },
80
+ },
81
+ response: {
82
+ use: (success, error) => {
83
+ handlers.responseSuccess = success
84
+ handlers.responseError = error
85
+ },
86
+ },
87
+ },
88
+ request: async (config) => ({ data: { ok: true }, config }),
89
+ },
90
+ }
91
+ }
@@ -0,0 +1,14 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import * as cuora from '../src/index.js'
5
+
6
+ test('index exports core modules', () => {
7
+ assert.ok(cuora.api)
8
+ assert.ok(cuora.machine)
9
+ assert.ok(cuora.Request)
10
+ assert.ok(cuora.Config)
11
+ assert.ok(cuora.util)
12
+ assert.ok(cuora.constant)
13
+ assert.ok(cuora.storage)
14
+ })