@jetthai/cuora 1.1.442 → 1.1.443-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.
package/README.md CHANGED
@@ -1,34 +1,8 @@
1
1
  # @jetthai/cuora
2
2
 
3
- `@jetthai/cuora` 是一個純 ESM JavaScript 函式庫,無建置步驟,原始 `.js` 檔案直接發佈至 npm。透過 XState v4 狀態機整合 API 呼叫與業務邏輯,服務於線上遊戲平台,處理認證、支付(存款/提款)、遊戲管理、活動及即時 WebSocket 通訊。設計用於 Nuxt.js 客戶端應用程式(`ssr: false`)。
4
-
5
- - **模組格式**:`"type": "module"`
6
- - **進入點**:`./src/index.js`
7
- - **無建置步驟**:無 Webpack/Rollup/TypeScript,無測試框架,無 Linter
8
- - **程式碼格式化**:Prettier(不加分號、單引號、2 空格縮排、150 字元行寬、ES5 尾隨逗號)
9
- - **Pre-commit Hook**:Husky 執行 `npm run format && git add .`
10
-
11
- ## 目錄
12
-
13
- - [Installation](#installation)
14
- - [Setup](#setup)
15
- - [Usage](#usage)
16
- - [模組匯出](#模組匯出)
17
- - [Config](#config)
18
- - [Request](#request)
19
- - [API](#api)
20
- - [Machine](#machine)
21
- - [Utilities](#utilities)
22
- - [Dependencies](#dependencies)
23
- - [Architecture](#architecture)
24
- - [Development](#development)
25
- - [Git 分支版本發佈流程](#git-分支版本發佈流程)
26
- - [分支策略](#分支策略)
27
- - [腳本權責分離](#腳本權責分離)
28
- - [dev / qa 分支自動版本流程](#dev--qa-分支自動版本流程)
29
- - [版號計算規則](#版號計算規則)
30
- - [Husky Hooks 總覽](#husky-hooks-總覽)
31
- - [License](#license)
3
+ ESM JavaScript 函式庫,透過 XState v4 狀態機整合 API 呼叫與業務邏輯,服務於線上遊戲平台。處理認證、支付(存款/提款)、遊戲管理、活動及即時 WebSocket 通訊。
4
+
5
+ 設計用於 Nuxt.js 客戶端應用程式(`ssr: false`)。
32
6
 
33
7
  ## Installation
34
8
 
@@ -56,18 +30,6 @@ export default {
56
30
  import { api, machine, Request, Config, util, constant, storage } from '@jetthai/cuora'
57
31
  ```
58
32
 
59
- ### 模組匯出
60
-
61
- | 匯出名稱 | 說明 |
62
- | ---------- | ------------------------------------------------------- |
63
- | `api` | 11 個 API 模組的聚合物件 |
64
- | `machine` | 91 個 XState 狀態機工廠函式的聚合物件 |
65
- | `Request` | Axios 封裝類別(攔截器、Token、版本控制) |
66
- | `Config` | 設定類別(apiURL、clientId、appSecret 等) |
67
- | `util` | 工具函式(`getDeviceToken`、`getDeviceTokenWithRetry`) |
68
- | `constant` | 遊戲類型常數(16 種遊戲類型) |
69
- | `storage` | localStorage 封裝(支援 TTL/過期) |
70
-
71
33
  ### Config
72
34
 
73
35
  初始化 API 設定:
@@ -158,35 +120,36 @@ storage.set('key', value, ttl)
158
120
  storage.get('key')
159
121
 
160
122
  // 遊戲類型常數
161
- constant.GAME_TYPE_LIST // 16 種遊戲類型陣列,每筆為 { typeId, name, gameTypeMappingId }
162
- constant.MY_FAVORITE // 'MyFavorite'
163
- constant.GAME_SEARCH // 'GameSearch'
123
+ constant.SLOT
124
+ constant.FISH
125
+ constant.LIVE
126
+ constant.SPORT
164
127
  ```
165
128
 
166
- ## Dependencies
167
-
168
- | 套件 | 版本 | 角色 | 使用位置 |
169
- | ------------------ | ---------- | ---------------------------------------------------------------------------------- | ---------------------- |
170
- | `xstate` | `^4.25.0` | 狀態機核心框架 | 所有 `machine/` 檔案 |
171
- | `socket.io-client` | `^4.8.3` | WebSocket 即時通訊 | `machine/websocket.js` |
172
- | `lodash` | `^4.17.21` | 工具函式(`pickBy`、`uniqBy`、`findLastIndex`、`padStart`、`toNumber`、`isEqual`) | 分散於 12 個檔案 |
173
- | `ua-parser-js` | `^0.7.34` | 使用者代理解析(行動裝置偵測) | `machine/common.js` |
174
- | `url-join` | `^4.0.1` | URL 路徑安全組合 | `request/config.js` |
175
- | `universal-cookie` | `^4.0.4` | Cookie 操作 | `machine/common.js` |
176
-
177
129
  ## Architecture
178
130
 
179
131
  ```
180
132
  src/
181
133
  ├── index.js # 進入點
182
134
  ├── api/ # API 請求描述物件
135
+ │ ├── auth.js
136
+ │ ├── account.js
137
+ │ ├── activity.js
138
+ │ ├── common.js
139
+ │ ├── form.js
140
+ │ ├── game.js
141
+ │ ├── mailbox.js
142
+ │ ├── otp.js
143
+ │ ├── payment.js
144
+ │ ├── ranking.js
145
+ │ └── user.js
183
146
  ├── machine/ # XState v4 狀態機
184
147
  │ ├── auth.js # 登入/註冊流程
185
148
  │ ├── common.js # 網站設定、UA、聯盟行銷
186
149
  │ ├── websocket.js # Socket.IO 即時通訊
187
- │ ├── deposit/ # 存款狀態機
188
- │ ├── withdraw/ # 提款狀態機
189
- │ └── activity/ # 活動狀態機
150
+ │ ├── deposit/ # 存款狀態機 (22+)
151
+ │ ├── withdraw/ # 提款狀態機 (4)
152
+ │ └── activity/ # 活動狀態機 (24+)
190
153
  ├── request/
191
154
  │ ├── config.js # Config 設定類別
192
155
  │ └── request.js # Axios 封裝 + 攔截器
@@ -217,92 +180,32 @@ npm run release:qa
217
180
 
218
181
  程式碼風格由 Prettier 管理(無分號、單引號、尾隨逗號 ES5、2 空格縮排、150 字元行寬),Husky pre-commit hook 會在每次提交時自動格式化。
219
182
 
220
- ## Git 分支版本發佈流程
221
-
222
- ### 分支策略
223
-
224
- | 分支 | 用途 | 版本格式 |
225
- | -------- | -------- | -------------------------- |
226
- | `master` | 正式發佈 | `x.y.z`(如 `1.1.430`) |
227
- | `dev` | 開發測試 | `{master_version}-dev.{N}` |
228
- | `qa` | QA 測試 | `{master_version}-qa.{N}` |
229
-
230
- ### 腳本權責分離
231
-
232
- dev/qa 分支的自動版本發佈由三個腳本各司其職:
233
-
234
- | 腳本 | 職責 | 說明 |
235
- | ------------------------------------ | --------------------- | ----------------------------------------------------------------------------------------------------- |
236
- | `scripts/auto-version.sh` | **流程控制**(Shell) | pre-push hook 入口。依序呼叫版號計算 → standard-version → push + publish,最後 `exit 1` 中止原始 push |
237
- | `scripts/auto-version.js` | **版號計算**(ESM) | 純計算邏輯。讀取 master 版本、比對當前版本與 git log 歷史(historyMax 防倒退),stdout 輸出新版號 |
238
- | `scripts/branch-auto-npm-publish.js` | **推送與發佈**(ESM) | 執行 `git push --follow-tags` 推送至遠端,再 `npm publish --tag {branch}` 發佈至 npm registry |
183
+ ### dev / qa 分支版本發佈
239
184
 
240
- ### dev / qa 分支自動版本流程
241
-
242
- 當開發者在 `dev` 或 `qa` 分支執行 `git push` 時,Husky `pre-push` hook 觸發以下流程:
185
+ 在 `dev` 或 `qa` 分支執行 `git push` 時,Husky `pre-push` hook 會自動觸發三階段流程:
243
186
 
244
187
  ```
245
- git push origin dev
246
- │
247
- ├─ .husky/pre-push
248
- │ ├─ sh scripts/clean-tags.sh # 清理本地 tag
249
- │ └─ sh scripts/auto-version.sh "$1" # 流程入口(傳入 remote name)
250
- │
251
- ├─ auto-version.sh 流程控制
252
- │ │
253
- │ ├─ ① node scripts/auto-version.js ← 版號計算
254
- │ │ ├─ git show origin/master:package.json → 取得 master version(如 1.1.430)
255
- │ │ │ └─ fallback: git show master:package.json
256
- │ │ ├─ 讀取當前 package.json version
257
- │ │ ├─ 從 currentVersion 推算下一編號
258
- │ │ ├─ 掃描 git log 最近 50 筆 commit(historyMax 防倒退)
259
- │ │ └─ stdout 輸出新版號(如 1.1.430-dev.3)
260
- │ │ └─ 若版號無變更 → 靜默退出,auto-version.sh 跳過後續步驟
261
- │ │
262
- │ ├─ ② npx standard-version --release-as {version}
263
- │ │ └─ 更新 CHANGELOG.md + 建立 commit + 建立 git tag
264
- │ │
265
- │ ├─ ③ node scripts/branch-auto-npm-publish.js ← 推送與發佈
266
- │ │ ├─ git push --follow-tags origin dev
267
- │ │ └─ npm publish --tag dev
268
- │ │
269
- │ └─ exit 1(中止原始 push,因為 script 已完成推送)
270
- │
271
- └─ 終端顯示 push 失敗,但實際發佈已成功(以 Released x.x.x 訊息為準)
188
+ git push → auto-version.sh(流程控制)
189
+ ├─ ① auto-version.js → 計算版號(含 historyMax 防倒退)
190
+ ├─ ② standard-version → 更新 CHANGELOG + commit + tag
191
+ └─ ③ branch-auto-npm-publish.js → git push + npm publish
272
192
  ```
273
193
 
274
- ### 版號計算規則
275
-
276
- **基本遞增**:
277
-
278
- - master 為 `1.1.430` → dev 第一次 push:`1.1.430-dev.0`
279
- - 再次 push:`1.1.430-dev.1`、`1.1.430-dev.2`、...
280
- - master 升版至 `1.1.431` → dev 重置為 `1.1.431-dev.0`
281
- - qa 分支同理:`1.1.430-qa.0`、`1.1.430-qa.1`、...
194
+ **腳本權責:**
282
195
 
283
- **historyMax 防倒退機制**:
196
+ | 腳本 | 職責 | 說明 |
197
+ | ------------------------------------ | ---------- | --------------------------------------------------------- |
198
+ | `scripts/auto-version.sh` | 流程控制 | pre-push 入口,串接版號計算 → standard-version → 發佈 |
199
+ | `scripts/auto-version.js` | 版號計算 | 讀取 master 版本 + 掃描 git log 防倒退,stdout 輸出新版號 |
200
+ | `scripts/branch-auto-npm-publish.js` | 推送與發佈 | `git push --follow-tags` + `npm publish --tag {branch}` |
284
201
 
285
- merge 其他分支後,`package.json` 的 version 可能被覆蓋為舊值(如從 `1.1.430-dev.4` 退回 `1.0.9-dev.20`)。此時腳本會掃描 git log 找出該 prefix 歷史上用過的最大編號,確保新版號不會倒退:
202
+ **版本號規則:**
286
203
 
287
- ```
288
- currentVersion = "1.0.9-dev.20" ← merge 後被覆蓋
289
- git log 發現歷史有 "1.1.430-dev.4"
290
- → historyMax = 4, nextNum = 5
291
- → 新版號 = "1.1.430-dev.5"(而非從 0 重新開始)
292
- ```
293
-
294
- ### Husky Hooks 總覽
295
-
296
- | Hook | 檔案 | 說明 |
297
- | --------------- | ---------------------- | ---------------------------------------------------- |
298
- | `pre-commit` | `.husky/pre-commit` | 執行 `npm run format && git add .`(Prettier) |
299
- | `pre-push` | `.husky/pre-push` | dev/qa 分支自動版本發佈(`scripts/auto-version.sh`) |
300
- | `post-checkout` | `.husky/post-checkout` | dev/qa/hotfix 分支自動 `git pull --rebase` |
301
- | `post-commit` | `.husky/post-commit` | (保留,目前無額外操作) |
302
- | `post-merge` | `.husky/post-merge` | (保留,目前無額外操作) |
204
+ | 情境 | 範例 |
205
+ | ------------------------------------ | ------------------------------------- |
206
+ | master 為 `1.1.425`,dev 第一次 push | `1.1.425-dev.0` |
207
+ | dev 再次 push | `1.1.425-dev.1`、`1.1.425-dev.2`、... |
208
+ | master 升版至 `1.1.426` 後 | dev 重置為 `1.1.426-dev.0` |
209
+ | qa 分支 | `1.1.425-qa.0`、`1.1.425-qa.1`、... |
303
210
 
304
211
  > **注意**:`pre-push` hook 完成推送後會以 `exit 1` 中止原始 push(因為已推送完成),終端會顯示 push 失敗訊息,但實際發佈已成功。以 `Released x.x.x on {branch}` 訊息為準。
305
-
306
- ## License
307
-
308
- ISC
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jetthai/cuora",
3
- "version": "1.1.442",
3
+ "version": "1.1.443-dev.1",
4
4
  "description": "",
5
5
  "main": "./src/index.js",
6
6
  "type": "module",
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // Copyright 2024 The Terasology Foundation
2
3
 
3
4
  // dev/qa 分支自動計算下一個 prerelease 版號
4
5
  // 版號格式:{master 版號}-{分支名}.{遞增編號}
@@ -125,4 +125,14 @@ export default {
125
125
  method: 'get',
126
126
  params: { activityNo, appSecret },
127
127
  }),
128
+ getProgressSummary: ({ appSecret }) => ({
129
+ url: 'activities/progress-summary',
130
+ method: 'get',
131
+ params: { appSecret },
132
+ }),
133
+ getProgressDetail: ({ appSecret }) => ({
134
+ url: 'activities/progress-details',
135
+ method: 'get',
136
+ params: { appSecret },
137
+ }),
128
138
  }
@@ -11,6 +11,7 @@ export default function (request) {
11
11
  context: {
12
12
  tick: 2000,
13
13
  activityList: [],
14
+ progressSummary: {},
14
15
  tournamentList: [],
15
16
  promotionList: [],
16
17
  uidSite: '',
@@ -24,7 +25,7 @@ export default function (request) {
24
25
  src: 'fetchList',
25
26
  onDone: {
26
27
  target: 'checking',
27
- actions: ['setActivityList', 'setTournamentList', 'setPromotionList'],
28
+ actions: ['setActivityList', 'setTournamentList', 'setPromotionList', 'setProgressSummary'],
28
29
  },
29
30
  onError: {
30
31
  target: 'pending',
@@ -96,6 +97,12 @@ export default function (request) {
96
97
  activityList: list,
97
98
  }
98
99
  }),
100
+ setProgressSummary: assign((context, event) => {
101
+ const { progressSummary } = event.data
102
+ return {
103
+ progressSummary: progressSummary || null,
104
+ }
105
+ }),
99
106
  setPromotionList: assign((context, event) => {
100
107
  const { promotionList } = event.data
101
108
  return {
@@ -154,12 +161,20 @@ export default function (request) {
154
161
  services: {
155
162
  fetchList: async (context, event) => {
156
163
  const hasToken = request.getToken()
157
- const [{ data }, promotionList] = await Promise.all([
164
+ const siteConfig = window?.$nuxt?.$store?.state?.siteConfig
165
+ const isProgressEnable = siteConfig?.frontendActivityProgressEnable
166
+
167
+ const [{ data }, promotionList, progressSummaryRes] = await Promise.all([
158
168
  hasToken ? request.send(activity.getActivityList({ appSecret })) : request.send(activity.getAllActivityList({ appSecret })),
159
169
  hasToken ? request.send(payment.getPromotionsList()) : [],
170
+ hasToken && isProgressEnable ? request.send(activity.getProgressSummary({ appSecret })).catch(() => null) : null,
160
171
  ])
161
172
 
162
- return { activityList: data, promotionList }
173
+ return {
174
+ activityList: data,
175
+ promotionList,
176
+ progressSummary: progressSummaryRes?.data || null,
177
+ }
163
178
  },
164
179
  fetchActivityDetailList: async (context, event) => {
165
180
  await new Promise((resolve) => setTimeout(resolve, 1000)) // delay 1 second
@@ -217,18 +217,25 @@ export default function (request) {
217
217
  },
218
218
  guards: {
219
219
  isVerified: (context, event) => {
220
- return context.userInfo?.verification_status === 1
220
+ const { strategy, userInfo } = context
221
+ if (strategy === 'phone') return !!userInfo?.phone_verification_status
222
+ if (strategy === 'email') return !!userInfo?.email_verification_status
223
+ return false
221
224
  },
222
225
  isNotVerified: (context, event) => {
223
- return context.userInfo && context.userInfo.verification_status !== 1
226
+ const { strategy, userInfo } = context
227
+ if (!userInfo) return false
228
+ if (strategy === 'phone') return !userInfo.phone_verification_status
229
+ if (strategy === 'email') return !userInfo.email_verification_status
230
+ return false
224
231
  },
225
232
  isPhoneNotVerified: (context, event) => {
226
233
  const { strategy, userInfo } = context
227
- return strategy === 'phone' && userInfo && userInfo.verification_status !== 1 && !userInfo.phone
234
+ return strategy === 'phone' && !!userInfo && !userInfo.phone_verification_status && !userInfo.phone
228
235
  },
229
236
  isEmailNotVerified: (context, event) => {
230
237
  const { strategy, userInfo } = context
231
- return strategy === 'email' && userInfo && userInfo.verification_status !== 1 && !userInfo.email
238
+ return strategy === 'email' && !!userInfo && !userInfo.email_verification_status && !userInfo.email
232
239
  },
233
240
  hasNoPhone: (context, event) => {
234
241
  const { error } = context
@@ -1,19 +1,28 @@
1
1
  import { createMachine, assign } from 'xstate'
2
2
  import ranking from '../api/ranking.js'
3
3
 
4
+ const ROUND_LIMIT = { DAILY: 56, WEEKLY: 8, MONTHLY: 2, ALL: 2 }
5
+ const ONE_DAY_MS = 24 * 60 * 60 * 1000
6
+
7
+ // 後端每個 cycle 只回傳「當前回合」一筆,前台依當前回合往前回填歷史回合
8
+ // 回合長度 = 當期長度(endDate - beginDate)+ 1 天,回合之間連續無間隔
9
+ function expandPeriodOption(option, cycle) {
10
+ if (!option) return []
11
+ const { round, beginDate, endDate } = option
12
+ // 回合長度取整到整數天,避免後端 endDate 帶當日 23:59:59 等時間造成歷史回合逐期偏移
13
+ const step = Math.floor((endDate - beginDate) / ONE_DAY_MS + 1) * ONE_DAY_MS
14
+ const count = Math.min(ROUND_LIMIT[cycle] || round, round)
15
+ // 降冪排列,當前回合在最前
16
+ return Array.from({ length: count }, (_, i) => ({
17
+ round: round - i,
18
+ beginDate: beginDate - i * step,
19
+ endDate: endDate - i * step,
20
+ }))
21
+ }
22
+
4
23
  export default function (request) {
5
24
  const { appSecret } = request.config
6
25
  const cycleMapping = ['DAILY', 'WEEKLY', 'MONTHLY']
7
- const limit = { DAILY: 56, WEEKLY: 8, MONTHLY: 2, ALL: 2 }
8
-
9
- function roundProcess(rounds, cycles) {
10
- const roundArrays = rounds.map((round) => Array.from({ length: round }, (_, i) => i + 1))
11
- return roundArrays.reduce((acc, roundArray, index) => {
12
- const max = limit[cycles[index]] || rounds[index] // 若沒限制則取全部
13
- acc[cycles[index]] = roundArray.reverse().slice(0, max)
14
- return acc
15
- }, {})
16
- }
17
26
 
18
27
  function transGameData(item) {
19
28
  if (!item) return {}
@@ -30,7 +39,6 @@ export default function (request) {
30
39
  site: '',
31
40
  activityNo: '',
32
41
  // api options 回傳的資料
33
- currentRound: [],
34
42
  cycle: '',
35
43
  round: 0,
36
44
  rule: '',
@@ -42,7 +50,7 @@ export default function (request) {
42
50
  gameRanking: [],
43
51
  topRanking: [],
44
52
  settleStatus: false,
45
- // 前端這邊用的選單資料 { cycle, round }
53
+ // 前端這邊用的選單資料 { cycle: [string], round: { [cycle]: [{ round, beginDate, endDate }] } }
46
54
  options: {},
47
55
  },
48
56
  states: {
@@ -156,31 +164,41 @@ export default function (request) {
156
164
  setRankingOptions: assign((context, event) => {
157
165
  const isChampion = event.data?.rule === 'CHAMPION'
158
166
  const cycle = event.data?.cycle
159
- const currentRound = event.data?.currentRound || []
160
- // 取得結算週期選單列表
161
- const cycleOptions = isChampion ? cycleMapping.slice(0, currentRound.length) : [cycle]
162
- const roundOptions = roundProcess(currentRound, cycleOptions)
167
+ const periodOptions = event.data?.periodOptions || []
168
+ // 每個 cycle 對應一筆「當前回合」
169
+ const optionByCycle = periodOptions.reduce((acc, option) => {
170
+ acc[option.cycle] = option
171
+ return acc
172
+ }, {})
173
+ // 依照 cycleMapping 順序取出有資料的 cycle
174
+ const cycleOptions = isChampion ? cycleMapping.filter((c) => optionByCycle[c]) : [cycle]
175
+ // 將每個 cycle 的當前回合往前回填為完整回合列表 { [cycle]: [{ round, beginDate, endDate }] }
176
+ const roundOptions = cycleOptions.reduce((acc, c) => {
177
+ acc[c] = expandPeriodOption(optionByCycle[c], c)
178
+ return acc
179
+ }, {})
163
180
  // 如果是冠軍龍虎月結算,則加入全部選項
164
181
  if (cycle === 'MONTHLY' && isChampion) {
165
182
  cycleOptions.push('ALL')
166
- roundOptions.ALL = roundOptions.MONTHLY
183
+ roundOptions.ALL = expandPeriodOption(optionByCycle.MONTHLY, 'ALL')
167
184
  }
185
+ // 初始 cycle 與 round
186
+ const initialCycle = isChampion ? 'DAILY' : cycle
187
+ const initialRound = roundOptions[initialCycle]?.[0]?.round
168
188
  return {
169
189
  ...event.data,
170
190
  options: { cycle: cycleOptions, round: roundOptions },
171
- // 初始固定顯示 DAILY
172
- cycle: isChampion ? 'DAILY' : cycle,
173
- round: currentRound[0],
191
+ cycle: initialCycle,
192
+ round: initialRound,
174
193
  }
175
194
  }),
176
195
  setOptions: assign((context, event) => {
177
- const { cycle, round } = context
196
+ const { cycle, round, options } = context
178
197
  // 處理變更 cycle,如果沒有輸入或沒有變更就不更新
179
198
  if (event.data?.cycle && cycle !== event.data?.cycle) {
180
- const { currentRound } = context
181
- const cycleForRound = event.data?.cycle === 'ALL' ? 'MONTHLY' : event.data?.cycle
182
- const cycleIndex = cycleMapping.indexOf(cycleForRound)
183
- return { cycle: event.data?.cycle, round: currentRound[cycleIndex] }
199
+ const newCycle = event.data?.cycle
200
+ const newRound = options?.round?.[newCycle]?.[0]?.round
201
+ return { cycle: newCycle, round: newRound }
184
202
  }
185
203
  if (event.data?.round && round !== event.data?.round) {
186
204
  return { round: event.data?.round }
@@ -1,5 +1,6 @@
1
1
  import pickBy from 'lodash/pickBy.js'
2
2
  import storage from '../util/storage.js'
3
+ import { getErr998SentryExtra } from '../util/err998SentryExtra.js'
3
4
 
4
5
  // const pickBy = require('lodash/pickBy')
5
6
  const supportVersion2List = [
@@ -171,6 +172,8 @@ export default class Request {
171
172
  this.errorHandler = null
172
173
  this.hosts = []
173
174
  this.isBlocked = false
175
+ this.clientIp = '' // 由外部 plugin(如 clientIp.client.js)非同步寫入,用於 ERR_998 Sentry 回報
176
+ this.hostTester = null // 由外部 plugin(如 host.client.js)寫入,需提供 lastResults 陣列供 ERR_998 Sentry 回報使用
174
177
  this.initialize()
175
178
  }
176
179
 
@@ -219,15 +222,24 @@ export default class Request {
219
222
  (error) => {
220
223
  if (error.message === 'Network Error' || error.message === 'Request failed with status code 404') {
221
224
  const endpoint = error.config?.url || ''
222
- const uidSite = window.$nuxt?.$store?.state?.userInfo?.uid_site || ''
223
- this.sentry?.captureException(`ERR_998:${error.message}`, {
224
- extra: {
225
- endpoint,
226
- site: this.config.clientId,
227
- uidSite,
228
- version: this.config.version,
229
- },
230
- })
225
+ const method = error.config?.method || ''
226
+ const baseURL = error.config?.baseURL || ''
227
+ // 確實在線才以 warning 等級回報(連線不穩定多為使用者端網路問題,非應用程式錯誤)
228
+ const isOnline = typeof navigator !== 'undefined' ? navigator.onLine : true
229
+ if (isOnline) {
230
+ const errData998 = getErr998SentryExtra(this, { endpoint, method, baseURL })
231
+ const sentryError = new Error(`ERR_998:${error.message}`)
232
+ sentryError.name = 'ERR_998'
233
+ this.sentry?.captureException(sentryError, {
234
+ level: 'warning',
235
+ tags: errData998,
236
+ extra: {
237
+ ...errData998,
238
+ version: this.config.version,
239
+ hostTestResults: this.hostTester?.lastResults || [],
240
+ },
241
+ })
242
+ }
231
243
  return Promise.reject({ code: 'ERR_998', endpoint })
232
244
  }
233
245
  return Promise.reject(error.response?.data?.error || error)
@@ -0,0 +1,52 @@
1
+ // ERR_998(Network Error / 404)Sentry 回報資料組裝工具
2
+ // 集中組裝 tags/extra,避免在 request.js 內重複拼裝邏輯
3
+ export function getErr998SentryExtra(request, requestInfo) {
4
+ const relativePath = requestInfo?.endpoint || ''
5
+ const method = requestInfo?.method || ''
6
+ const baseURL = requestInfo?.baseURL || ''
7
+ const endpoint = buildFullUrl(baseURL, relativePath)
8
+ const apiHost = getUrlOrigin(baseURL) || getUrlOrigin(relativePath) || request?.config?.apiURL || ''
9
+ const uidSite = getUidSite()
10
+
11
+ return {
12
+ code: 'ERR_998',
13
+ endpoint: normalizeSentryTagValue(endpoint),
14
+ method,
15
+ site: request?.config?.clientId || '',
16
+ ip: request?.clientIp || '',
17
+ apiHost,
18
+ uidSite,
19
+ }
20
+ }
21
+
22
+ function buildFullUrl(baseURL, path) {
23
+ if (!path) return baseURL || ''
24
+ if (!baseURL) return path
25
+ try {
26
+ const base = baseURL.endsWith('/') ? baseURL : baseURL + '/'
27
+ return new URL(path, base).href
28
+ } catch {
29
+ return path
30
+ }
31
+ }
32
+
33
+ export function getUrlOrigin(url) {
34
+ try {
35
+ return new URL(url).origin
36
+ } catch (error) {
37
+ return ''
38
+ }
39
+ }
40
+
41
+ function getUidSite() {
42
+ try {
43
+ return (typeof window !== 'undefined' && window.$nuxt?.$store?.state?.userInfo?.uid_site) || ''
44
+ } catch (error) {
45
+ return ''
46
+ }
47
+ }
48
+
49
+ function normalizeSentryTagValue(value) {
50
+ if (value === undefined || value === null) return ''
51
+ return String(value).slice(0, 200)
52
+ }