@seayoo-io/combo-sdk-node 1.7.0 → 1.8.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/dist/index.js CHANGED
@@ -1,1803 +1,1616 @@
1
- import { platform, arch } from 'os';
2
- import http from 'http';
3
- import https from 'https';
4
- import { createHash, createHmac, createDecipheriv } from 'crypto';
5
- import { verify } from 'jsonwebtoken';
6
-
1
+ import { arch, platform } from "os";
2
+ import http from "http";
3
+ import https from "https";
4
+ import { createDecipheriv, createHash, createHmac } from "crypto";
5
+ import jwt from "jsonwebtoken";
6
+ //#region src/const.ts
7
7
  /** SDK 名称 */
8
8
  const SDKName = "combo-sdk-node";
9
9
  /** SDK 版本,在编译前会被动态替换 */
10
- const SDKVersion = "1.7.0";
10
+ const SDKVersion = "1.8.1";
11
11
  /**
12
- * 世游支持的服务端点列表
13
- */
14
- var Endpoint;
15
- (function (Endpoint) {
16
- /** 中国大陆 API 端点,用于国内发行 */
17
- Endpoint["China"] = "https://api.seayoo.com";
18
- /** 全球的 API 端点,用于海外发行 */
19
- Endpoint["Global"] = "https://api.seayoo.io";
20
- })(Endpoint || (Endpoint = {}));
12
+ * 世游支持的服务端点列表
13
+ */
14
+ let Endpoint = /* @__PURE__ */ function(Endpoint) {
15
+ /** 中国大陆 API 端点,用于国内发行 */
16
+ Endpoint["China"] = "https://api.seayoo.com";
17
+ /** 全球的 API 端点,用于海外发行 */
18
+ Endpoint["Global"] = "https://api.seayoo.io";
19
+ return Endpoint;
20
+ }({});
21
21
  /** 支持的系统平台 */
22
- var Platform;
23
- (function (Platform) {
24
- /** 安卓平台,包括华为鸿蒙系统、小米澎湃 OS 等基于 Android 的操作系统 */
25
- Platform["Android"] = "android";
26
- /** 苹果的 iOS 和 iPadOS */
27
- Platform["iOS"] = "ios";
28
- /** Windows (PC) 桌面平台 */
29
- Platform["Windows"] = "windows";
30
- /** macOS 桌面平台 */
31
- Platform["macOS"] = "macos";
32
- /** WebGL 平台,包括微信、抖音等小游戏,以及 HTML5 网页游戏 */
33
- Platform["WebGL"] = "webgl";
34
- /** 华为的 HarmonyOS NEXT 鸿蒙应用开发平台 */
35
- Platform["HarmonyOS"] = "harmonyos";
36
- })(Platform || (Platform = {}));
22
+ let Platform = /* @__PURE__ */ function(Platform) {
23
+ /** 安卓平台,包括华为鸿蒙系统、小米澎湃 OS 等基于 Android 的操作系统 */
24
+ Platform["Android"] = "android";
25
+ /** 苹果的 iOS 和 iPadOS */
26
+ Platform["iOS"] = "ios";
27
+ /** Windows (PC) 桌面平台 */
28
+ Platform["Windows"] = "windows";
29
+ /** macOS 桌面平台 */
30
+ Platform["macOS"] = "macos";
31
+ /** WebGL 平台,包括微信、抖音等小游戏,以及 HTML5 网页游戏 */
32
+ Platform["WebGL"] = "webgl";
33
+ /** 华为的 HarmonyOS NEXT 鸿蒙应用开发平台 */
34
+ Platform["HarmonyOS"] = "harmonyos";
35
+ return Platform;
36
+ }({});
37
37
  /** 支持的登录提供方 */
38
- var IdP;
39
- (function (IdP) {
40
- /** 游客登录 */
41
- IdP["Guest"] = "guest";
42
- /** 世游通行证 */
43
- IdP["Seayoo"] = "seayoo";
44
- /** Sign-in with Apple */
45
- IdP["Apple"] = "apple";
46
- /** Google Account */
47
- IdP["Google"] = "google";
48
- /** Facebook Login */
49
- IdP["Facebook"] = "facebook";
50
- /** 小米账号 */
51
- IdP["Xiaomi"] = "xiaomi";
52
- /** 微信登录 */
53
- IdP["Weixin"] = "weixin";
54
- /** OPPO 账号 */
55
- IdP["Oppo"] = "oppo";
56
- /** VIVO 账号 */
57
- IdP["Vivo"] = "vivo";
58
- /** 华为账号 */
59
- IdP["Huawei"] = "huawei";
60
- /** 荣耀账号 */
61
- IdP["Honor"] = "honor";
62
- /** UC(九游)登录 */
63
- IdP["UC"] = "uc";
64
- /** TapTap 登录 */
65
- IdP["TapTap"] = "taptap";
66
- /** 哔哩哔哩(B站)账号 */
67
- IdP["Bilibili"] = "bilibili";
68
- /** 应用宝 YSDK 登录 */
69
- IdP["Yingyongbao"] = "yingyongbao";
70
- /** 4399 账号登录 */
71
- IdP["F4399"] = "4399";
72
- /** 抖音账号 */
73
- IdP["Douyin"] = "douyin";
74
- /** 雷电模拟器账号 */
75
- IdP["Leidian"] = "leidian";
76
- /** 猫窝游戏 */
77
- IdP["Maowo"] = "maowo";
78
- /** 联想 */
79
- IdP["Lenovo"] = "lenovo";
80
- /** 魅族 */
81
- IdP["Meizu"] = "meizu";
82
- /** 酷派 */
83
- IdP["Coolpad"] = "coolpad";
84
- /** 努比亚 */
85
- IdP["Nubia"] = "nubia";
86
- /** 绝峰游戏 */
87
- IdP["Juefeng"] = "juefeng";
88
- /** 魅拓游戏 */
89
- IdP["Meituo"] = "meituo";
90
- /** 微信小游戏 */
91
- IdP["MinigameWeixin"] = "minigame_weixin";
92
- /** 抖音小游戏 */
93
- IdP["MinigameDouyin"] = "minigame_douyin";
94
- /** MuMu 模拟器 */
95
- IdP["Mumu"] = "mumu";
96
- /** 虎牙游戏 */
97
- IdP["Huya"] = "huya";
98
- /** 好游快爆 */
99
- IdP["Hykb"] = "hykb";
100
- /** 233 乐园 */
101
- IdP["L233"] = "233";
102
- })(IdP || (IdP = {}));
38
+ let IdP = /* @__PURE__ */ function(IdP) {
39
+ /** 游客登录 */
40
+ IdP["Guest"] = "guest";
41
+ /** 世游通行证 */
42
+ IdP["Seayoo"] = "seayoo";
43
+ /** Sign-in with Apple */
44
+ IdP["Apple"] = "apple";
45
+ /** Google Account */
46
+ IdP["Google"] = "google";
47
+ /** Facebook Login */
48
+ IdP["Facebook"] = "facebook";
49
+ /** 小米账号 */
50
+ IdP["Xiaomi"] = "xiaomi";
51
+ /** 微信登录 */
52
+ IdP["Weixin"] = "weixin";
53
+ /** OPPO 账号 */
54
+ IdP["Oppo"] = "oppo";
55
+ /** VIVO 账号 */
56
+ IdP["Vivo"] = "vivo";
57
+ /** 华为账号 */
58
+ IdP["Huawei"] = "huawei";
59
+ /** 荣耀账号 */
60
+ IdP["Honor"] = "honor";
61
+ /** UC(九游)登录 */
62
+ IdP["UC"] = "uc";
63
+ /** TapTap 登录 */
64
+ IdP["TapTap"] = "taptap";
65
+ /** 哔哩哔哩(B站)账号 */
66
+ IdP["Bilibili"] = "bilibili";
67
+ /** 应用宝 YSDK 登录 */
68
+ IdP["Yingyongbao"] = "yingyongbao";
69
+ /** 4399 账号登录 */
70
+ IdP["F4399"] = "4399";
71
+ /** 抖音账号 */
72
+ IdP["Douyin"] = "douyin";
73
+ /** 雷电模拟器账号 */
74
+ IdP["Leidian"] = "leidian";
75
+ /** 猫窝游戏 */
76
+ IdP["Maowo"] = "maowo";
77
+ /** 联想 */
78
+ IdP["Lenovo"] = "lenovo";
79
+ /** 魅族 */
80
+ IdP["Meizu"] = "meizu";
81
+ /** 酷派 */
82
+ IdP["Coolpad"] = "coolpad";
83
+ /** 努比亚 */
84
+ IdP["Nubia"] = "nubia";
85
+ /** 绝峰游戏 */
86
+ IdP["Juefeng"] = "juefeng";
87
+ /** 魅拓游戏 */
88
+ IdP["Meituo"] = "meituo";
89
+ /** 微信小游戏 */
90
+ IdP["MinigameWeixin"] = "minigame_weixin";
91
+ /** 抖音小游戏 */
92
+ IdP["MinigameDouyin"] = "minigame_douyin";
93
+ /** MuMu 模拟器 */
94
+ IdP["Mumu"] = "mumu";
95
+ /** 虎牙游戏 */
96
+ IdP["Huya"] = "huya";
97
+ /** 好游快爆 */
98
+ IdP["Hykb"] = "hykb";
99
+ /** 233 乐园 */
100
+ IdP["L233"] = "233";
101
+ return IdP;
102
+ }({});
103
103
  /** GM 错误类型枚举 */
104
- var GMError;
105
- (function (GMError) {
106
- /** 请求中的 HTTP method 不正确,没有按照预期使用 POST。*/
107
- GMError["InvalidHttpMethod"] = "invalid_http_method";
108
- /** 请求中的 Content-Type 不是 application/json。*/
109
- GMError["InvalidContentType"] = "invalid_content_type";
110
- /** 对 HTTP 请求的签名验证不通过。这意味着 HTTP 请求不可信。 */
111
- GMError["InvalidSignature"] = "invalid_signature";
112
- /** 请求的结构不正确。例如,缺少必要的字段,或字段类型不正确。 */
113
- GMError["InvalidRequest"] = "invalid_request";
114
- /** 游戏侧不认识请求中的 GM 命令。 */
115
- GMError["InvalidCommand"] = "invalid_command";
116
- /** GM 命令发送频率过高,被游戏侧限流,命令未被处理。 */
117
- GMError["ThrottlingError"] = "throttling_error";
118
- /** 幂等处理重试请求时,idempotency_key 所对应的原始请求尚未处理完毕。*/
119
- GMError["IdempotencyConflict"] = "idempotency_conflict";
120
- /** 幂等处理重试请求时,请求内容和 idempotency_key 所对应的原始请求内容不一致。*/
121
- GMError["IdempotencyMismatch"] = "idempotency_mismatch";
122
- /** GM 命令的参数不正确。例如,参数缺少必要的字段,或参数的字段类型不正确。 */
123
- GMError["InvalidArgs"] = "invalid_args";
124
- /** 游戏当前处于停服维护状态,无法处理收到的 GM 命令。*/
125
- GMError["MaintenanceError"] = "maintenance_error";
126
- /** 网络通信错误。 */
127
- GMError["NetworkError"] = "network_error";
128
- /** 数据库操作异常导致 GM 命令执行失败。 */
129
- GMError["DatabaseError"] = "database_error";
130
- /** GM 命令处理超时。 */
131
- GMError["TimeoutError"] = "timeout_error";
132
- /** 处理 GM 命令时内部出错。可作为兜底的通用错误类型。*/
133
- GMError["InternalError"] = "internal_error";
134
- })(GMError || (GMError = {}));
135
-
104
+ let GMError = /* @__PURE__ */ function(GMError) {
105
+ /** 请求中的 HTTP method 不正确,没有按照预期使用 POST。*/
106
+ GMError["InvalidHttpMethod"] = "invalid_http_method";
107
+ /** 请求中的 Content-Type 不是 application/json。*/
108
+ GMError["InvalidContentType"] = "invalid_content_type";
109
+ /** 对 HTTP 请求的签名验证不通过。这意味着 HTTP 请求不可信。 */
110
+ GMError["InvalidSignature"] = "invalid_signature";
111
+ /** 请求的结构不正确。例如,缺少必要的字段,或字段类型不正确。 */
112
+ GMError["InvalidRequest"] = "invalid_request";
113
+ /** 游戏侧不认识请求中的 GM 命令。 */
114
+ GMError["InvalidCommand"] = "invalid_command";
115
+ /** GM 命令发送频率过高,被游戏侧限流,命令未被处理。 */
116
+ GMError["ThrottlingError"] = "throttling_error";
117
+ /** 幂等处理重试请求时,idempotency_key 所对应的原始请求尚未处理完毕。*/
118
+ GMError["IdempotencyConflict"] = "idempotency_conflict";
119
+ /** 幂等处理重试请求时,请求内容和 idempotency_key 所对应的原始请求内容不一致。*/
120
+ GMError["IdempotencyMismatch"] = "idempotency_mismatch";
121
+ /** GM 命令的参数不正确。例如,参数缺少必要的字段,或参数的字段类型不正确。 */
122
+ GMError["InvalidArgs"] = "invalid_args";
123
+ /** 游戏当前处于停服维护状态,无法处理收到的 GM 命令。*/
124
+ GMError["MaintenanceError"] = "maintenance_error";
125
+ /** 网络通信错误。 */
126
+ GMError["NetworkError"] = "network_error";
127
+ /** 数据库操作异常导致 GM 命令执行失败。 */
128
+ GMError["DatabaseError"] = "database_error";
129
+ /** GM 命令处理超时。 */
130
+ GMError["TimeoutError"] = "timeout_error";
131
+ /** 处理 GM 命令时内部出错。可作为兜底的通用错误类型。*/
132
+ GMError["InternalError"] = "internal_error";
133
+ return GMError;
134
+ }({});
135
+ let HttpStatus = /* @__PURE__ */ function(HttpStatus) {
136
+ HttpStatus[HttpStatus["OK"] = 200] = "OK";
137
+ HttpStatus[HttpStatus["Accepted"] = 202] = "Accepted";
138
+ HttpStatus[HttpStatus["NoContent"] = 204] = "NoContent";
139
+ HttpStatus[HttpStatus["BadRequest"] = 400] = "BadRequest";
140
+ HttpStatus[HttpStatus["Unauthorized"] = 401] = "Unauthorized";
141
+ HttpStatus[HttpStatus["Forbidden"] = 403] = "Forbidden";
142
+ HttpStatus[HttpStatus["NotFound"] = 404] = "NotFound";
143
+ HttpStatus[HttpStatus["MethodNotAllowed"] = 405] = "MethodNotAllowed";
144
+ HttpStatus[HttpStatus["NotAcceptable"] = 406] = "NotAcceptable";
145
+ HttpStatus[HttpStatus["RequestTimeout"] = 408] = "RequestTimeout";
146
+ HttpStatus[HttpStatus["Conflict"] = 409] = "Conflict";
147
+ HttpStatus[HttpStatus["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
148
+ HttpStatus[HttpStatus["UnprocessableEntity"] = 422] = "UnprocessableEntity";
149
+ HttpStatus[HttpStatus["TooManyRequests"] = 429] = "TooManyRequests";
150
+ HttpStatus[HttpStatus["InternalServerError"] = 500] = "InternalServerError";
151
+ HttpStatus[HttpStatus["BadGateway"] = 502] = "BadGateway";
152
+ HttpStatus[HttpStatus["ServiceUnavailable"] = 503] = "ServiceUnavailable";
153
+ return HttpStatus;
154
+ }({});
155
+ //#endregion
156
+ //#region src/api/ua.ts
136
157
  function getUserAgent(game) {
137
- return `${SDKName}/${SDKVersion} game/${game} node/${process.version} os/${platform()} arch/${arch()}`;
158
+ return `${SDKName}/${SDKVersion} game/${game} node/${process.version} os/${platform()} arch/${arch()}`;
138
159
  }
139
-
160
+ //#endregion
161
+ //#region src/utils/base.ts
140
162
  const urlReg = /^(?:https?:)?\/\/.+/i;
141
163
  const urlReg2 = /^https?:\/\//i;
142
164
  const objReg = /^\{[\d\D]*\}$/;
143
165
  const arrReg = /^\[[\d\D]*\]$/;
144
166
  /**
145
- * 暂停一段时间
146
- * @param {number} ms 暂停的毫秒数
147
- */
167
+ * 暂停一段时间
168
+ * @param {number} ms 暂停的毫秒数
169
+ */
148
170
  function sleep(ms) {
149
- return new Promise(resolve => setTimeout(resolve, ms));
171
+ return new Promise((resolve) => setTimeout(resolve, ms));
150
172
  }
151
173
  /**
152
- * 空函数,异步空函数为 asyncNoop
153
- */
174
+ * 空函数,异步空函数为 asyncNoop
175
+ */
154
176
  function noop() {}
155
177
  /**
156
- * 检查是否为空值 null / undefined
157
- */
178
+ * 检查是否为空值 null / undefined
179
+ */
158
180
  function isEmpty(data) {
159
- return data === null || data === undefined;
181
+ return data === null || data === void 0;
160
182
  }
161
183
  /**
162
- * 检查是否为 object(非 null / array)
163
- */
184
+ * 检查是否为 object(非 null / array)
185
+ */
164
186
  function isObject(data) {
165
- return data !== null && typeof data === "object" && !Array.isArray(data);
187
+ return data !== null && typeof data === "object" && !Array.isArray(data);
166
188
  }
167
189
  /**
168
- * 检测是否为 String Record
169
- */
190
+ * 检测是否为 String Record
191
+ */
170
192
  function isStringRecord(data) {
171
- return isObject(data) && Object.keys(data).every(key => typeof key === "string");
193
+ return isObject(data) && Object.keys(data).every((key) => typeof key === "string");
172
194
  }
173
195
  /**
174
- * 检查一个url地址是否以 http/https 开头,如果第二个参数传递 true,则自适应协议(//....)也被认为是完整 url
175
- */
196
+ * 检查一个url地址是否以 http/https 开头,如果第二个参数传递 true,则自适应协议(//....)也被认为是完整 url
197
+ */
176
198
  function isFullURL(url, ignoreProtocol = false) {
177
- return ignoreProtocol ? urlReg.test(url) : urlReg2.test(url);
199
+ return ignoreProtocol ? urlReg.test(url) : urlReg2.test(url);
178
200
  }
179
201
  /**
180
- * 检测文本是否有可能转化为 object 或 array,注意,检测通过也未必能被正确格式化为 json
181
- */
202
+ * 检测文本是否有可能转化为 object 或 array,注意,检测通过也未必能被正确格式化为 json
203
+ */
182
204
  function isJsonLike(text) {
183
- return objReg.test(text) || arrReg.test(text);
205
+ return objReg.test(text) || arrReg.test(text);
184
206
  }
185
207
  /**
186
- * 基于 baseURL 计算完整的 url 信息,仅可在浏览器环境使用
187
- * @param url 要转化的 url,如果以 https: 或 http: 开头则直接返回
188
- * @param baseURL 可选 baseURL
189
- */
208
+ * 基于 baseURL 计算完整的 url 信息,仅可在浏览器环境使用
209
+ * @param url 要转化的 url,如果以 https: 或 http: 开头则直接返回
210
+ * @param baseURL 可选 baseURL
211
+ */
190
212
  function getFullURL(url, baseURL = "") {
191
- if (!baseURL || isFullURL(url, true)) {
192
- return fillUrl(url);
193
- }
194
- return (fillUrl(baseURL) + "/" + url).replace(/\/{2,}/g, "/").replace(/:\//, "://");
213
+ if (!baseURL || isFullURL(url, true)) return fillUrl(url);
214
+ return (fillUrl(baseURL) + "/" + url).replace(/\/{2,}/g, "/").replace(/:\//, "://");
195
215
  }
196
216
  /**
197
- * 给 url 添加完整域名和协议,仅可在浏览器环境使用
198
- * @param url 要检查的 url,如果是自适应协议 //... 则会添加当前页面的协议信息,否则添加域名和协议信息
199
- */
217
+ * 给 url 添加完整域名和协议,仅可在浏览器环境使用
218
+ * @param url 要检查的 url,如果是自适应协议 //... 则会添加当前页面的协议信息,否则添加域名和协议信息
219
+ */
200
220
  function fillUrl(url) {
201
- if (isFullURL(url, true)) {
202
- if (url.startsWith("http")) {
203
- return url;
204
- }
205
- return ("location" in globalThis ? location.protocol : "https:") + url;
206
- }
207
- return ("location" in globalThis ? location.origin + "/" : "http://127.0.0.1/") + url.replace(/^\/+/, "");
221
+ if (isFullURL(url, true)) {
222
+ if (url.startsWith("http")) return url;
223
+ return ("location" in globalThis ? location.protocol : "https:") + url;
224
+ }
225
+ return ("location" in globalThis ? location.origin + "/" : "http://127.0.0.1/") + url.replace(/^\/+/, "");
208
226
  }
209
227
  /**
210
- * 简版 Object.fromEntries
211
- */
228
+ * 简版 Object.fromEntries
229
+ */
212
230
  function fromEntries(kv) {
213
- return kv.reduce((result, [key, value]) => {
214
- if (key) {
215
- result[key] = value || "";
216
- }
217
- return result;
218
- }, {});
231
+ return kv.reduce((result, [key, value]) => {
232
+ if (key) result[key] = value || "";
233
+ return result;
234
+ }, {});
219
235
  }
220
236
  function parseJSON(str, typeGuard) {
221
- try {
222
- const data = JSON.parse(str);
223
- if (typeGuard) {
224
- return typeGuard(data) ? data : null;
225
- }
226
- return data;
227
- } catch (e) {
228
- return null;
229
- }
230
- }
231
-
237
+ try {
238
+ const data = JSON.parse(str);
239
+ if (typeGuard) return typeGuard(data) ? data : null;
240
+ return data;
241
+ } catch (e) {
242
+ return null;
243
+ }
244
+ }
245
+ //#endregion
246
+ //#region src/utils/types.ts
232
247
  function getTypeGuard(typeGuard, defaultMessage = "数据未能正确识别") {
233
- if (typeof typeGuard === "function") {
234
- return {
235
- guard: typeGuard,
236
- message: defaultMessage
237
- };
238
- }
239
- return {
240
- guard: typeGuard.guard,
241
- message: typeGuard.message || defaultMessage
242
- };
243
- }
244
-
248
+ if (typeof typeGuard === "function") return {
249
+ guard: typeGuard,
250
+ message: defaultMessage
251
+ };
252
+ return {
253
+ guard: typeGuard.guard,
254
+ message: typeGuard.message || defaultMessage
255
+ };
256
+ }
257
+ //#endregion
258
+ //#region src/utils/config.ts
245
259
  /**
246
- * 校验通用配置,如果有错误,则直接 throw Error
247
- */
260
+ * 校验通用配置,如果有错误,则直接 throw Error
261
+ */
248
262
  function verifyConfig(config) {
249
- verifyConfigWithoutEndpoint(config);
250
- if (!isFullURL(config.endpoint)) {
251
- throw Error(`Config.endpoint Error, Should be url, Preset Values: ${Endpoint.China}, ${Endpoint.Global}}`);
252
- }
263
+ verifyConfigWithoutEndpoint(config);
264
+ if (!isFullURL(config.endpoint)) throw Error(`Config.endpoint Error, Should be url, Preset Values: ${Endpoint.China}, ${Endpoint.Global}}`);
253
265
  }
254
266
  /**
255
- * 校验通用配置,如果有错误,则直接 throw Error
256
- */
267
+ * 校验通用配置,如果有错误,则直接 throw Error
268
+ */
257
269
  function verifyConfigWithoutEndpoint(config) {
258
- if (!isObject(config)) {
259
- throw Error("Config Missing");
260
- }
261
- if (!config.game) {
262
- throw Error(`Config.game Error, Missing Required GameId`);
263
- }
264
- if (!config.secret) {
265
- throw Error(`Config.secret Error, Missing Required Secret`);
266
- }
267
- if (!config.secret.startsWith("sk_")) {
268
- throw Error(`Config.secret Error, Should be Start With sk_`);
269
- }
270
- }
271
-
270
+ if (!isObject(config)) throw Error("Config Missing");
271
+ if (!config.game) throw Error(`Config.game Error, Missing Required GameId`);
272
+ if (!config.secret) throw Error(`Config.secret Error, Missing Required Secret`);
273
+ if (!config.secret.startsWith("sk_")) throw Error(`Config.secret Error, Should be Start With sk_`);
274
+ }
275
+ //#endregion
276
+ //#region src/utils/signer.ts
272
277
  const AuthorizationField = "Authorization";
273
- const MaxTimeDiff = 5 * 60 * 1000;
278
+ const MaxTimeDiff = 300 * 1e3;
274
279
  const timestampReg = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;
275
- // 签名方法定义,给未来扩展新签名方法留出空间
276
- const SigningDefinitions = {
277
- HS256: {
278
- prefix: "SEAYOO-HMAC-SHA256",
279
- sign({
280
- game,
281
- secret,
282
- method,
283
- url,
284
- data,
285
- timestamp
286
- }, onlySignature = false) {
287
- if (timestamp && !timestampReg.test(timestamp)) {
288
- return "ErrorTimestamp";
289
- }
290
- const payloadHash = sha256(convertBodyData(data || ""));
291
- const ts = timestamp || getTimestamp();
292
- const fullURL = isFullURL(url) ? new URL(url) : new URL(url, "http://x.com");
293
- const uri = fullURL.pathname + fullURL.search;
294
- const signature = hS256(secret, [this.prefix, method.toUpperCase(), uri, ts, payloadHash].join("\n"));
295
- return onlySignature ? signature : `${this.prefix} Game=${game},Timestamp=${ts},Signature=${signature}`;
296
- },
297
- verify(authString, option) {
298
- const info = parseRawAuthHeader(authString, this.prefix);
299
- if (!info) {
300
- return false;
301
- }
302
- const game = "Game" in info ? info.Game : null;
303
- const timestamp = "Timestamp" in info ? info.Timestamp : null;
304
- const signature = "Signature" in info ? info.Signature : null;
305
- if (!game || !signature || !timestamp || option.game && option.game !== game) {
306
- return false;
307
- }
308
- const ts = parseTimestamp(timestamp);
309
- // 时间戳精度只到秒,需要忽略毫秒值
310
- const now = Math.floor(Date.now() / 1000) * 1000;
311
- if (!ts || ts < now - MaxTimeDiff || ts > now + MaxTimeDiff) {
312
- return false;
313
- }
314
- return signature === this.sign({
315
- ...option,
316
- game,
317
- timestamp
318
- }, true);
319
- }
320
- }
321
- };
280
+ const SigningDefinitions = { HS256: {
281
+ prefix: "SEAYOO-HMAC-SHA256",
282
+ sign({ game, secret, method, url, data, timestamp }, onlySignature = false) {
283
+ if (timestamp && !timestampReg.test(timestamp)) return "ErrorTimestamp";
284
+ const payloadHash = sha256(convertBodyData(data || ""));
285
+ const ts = timestamp || getTimestamp();
286
+ const fullURL = isFullURL(url) ? new URL(url) : new URL(url, "http://x.com");
287
+ const uri = fullURL.pathname + fullURL.search;
288
+ const signature = hS256(secret, [
289
+ this.prefix,
290
+ method.toUpperCase(),
291
+ uri,
292
+ ts,
293
+ payloadHash
294
+ ].join("\n"));
295
+ return onlySignature ? signature : `${this.prefix} Game=${game},Timestamp=${ts},Signature=${signature}`;
296
+ },
297
+ verify(authString, option) {
298
+ const info = parseRawAuthHeader(authString, this.prefix);
299
+ if (!info) return false;
300
+ const game = "Game" in info ? info.Game : null;
301
+ const timestamp = "Timestamp" in info ? info.Timestamp : null;
302
+ const signature = "Signature" in info ? info.Signature : null;
303
+ if (!game || !signature || !timestamp || option.game && option.game !== game) return false;
304
+ const ts = parseTimestamp(timestamp);
305
+ const now = Math.floor(Date.now() / 1e3) * 1e3;
306
+ if (!ts || ts < now - MaxTimeDiff || ts > now + MaxTimeDiff) return false;
307
+ return signature === this.sign({
308
+ ...option,
309
+ game,
310
+ timestamp
311
+ }, true);
312
+ }
313
+ } };
322
314
  /**
323
- * 格式化 AuthorizationHeader
324
- */
315
+ * 格式化 AuthorizationHeader
316
+ */
325
317
  function parseAuthorizationHeader(authString, version = "HS256") {
326
- if (!version || !SigningDefinitions[version]) {
327
- console.error({
328
- type: "parseAuthorizationHeader Error",
329
- message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
330
- });
331
- return null;
332
- }
333
- return parseRawAuthHeader(authString, SigningDefinitions[version].prefix);
318
+ if (!version || !SigningDefinitions[version]) {
319
+ console.error({
320
+ type: "parseAuthorizationHeader Error",
321
+ message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
322
+ });
323
+ return null;
324
+ }
325
+ return parseRawAuthHeader(authString, SigningDefinitions[version].prefix);
334
326
  }
335
327
  /**
336
- * 获取请求签名值,默认签名方法是 HS256
337
- */
328
+ * 获取请求签名值,默认签名方法是 HS256
329
+ */
338
330
  function calcAuthorizationHeader(option, onlySignature = false, version = "HS256") {
339
- if (!version || !SigningDefinitions[version]) {
340
- console.error({
341
- type: "calcAuthorizationHeader Error",
342
- message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
343
- });
344
- return "ErrorSigningVersion";
345
- }
346
- return SigningDefinitions[version].sign(option, onlySignature);
331
+ if (!version || !SigningDefinitions[version]) {
332
+ console.error({
333
+ type: "calcAuthorizationHeader Error",
334
+ message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
335
+ });
336
+ return "ErrorSigningVersion";
337
+ }
338
+ return SigningDefinitions[version].sign(option, onlySignature);
347
339
  }
348
340
  /**
349
- * 检查 http auth 信息是否正确
350
- */
341
+ * 检查 http auth 信息是否正确
342
+ */
351
343
  function checkHttpAuthInfo(authString, option) {
352
- if (!authString) {
353
- return false;
354
- }
355
- const configs = Object.values(SigningDefinitions);
356
- for (const cfg of configs) {
357
- if (authString.startsWith(cfg.prefix + " ")) {
358
- return cfg.verify(authString, option);
359
- }
360
- }
361
- return false;
344
+ if (!authString) return false;
345
+ const configs = Object.values(SigningDefinitions);
346
+ for (const cfg of configs) if (authString.startsWith(cfg.prefix + " ")) return cfg.verify(authString, option);
347
+ return false;
362
348
  }
363
349
  function getTimestamp() {
364
- const d = new Date();
365
- return d.toISOString().replace(/\.\d+Z$/, "Z").replace(/[-:]/g, "");
350
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d+Z$/, "Z").replace(/[-:]/g, "");
366
351
  }
367
352
  function parseTimestamp(ts) {
368
- const info = ts.match(timestampReg);
369
- if (!info) {
370
- return null;
371
- }
372
- return Date.UTC(+info[1], +info[2] - 1, +info[3], +info[4], +info[5], +info[6]);
353
+ const info = ts.match(timestampReg);
354
+ if (!info) return null;
355
+ return Date.UTC(+info[1], +info[2] - 1, +info[3], +info[4], +info[5], +info[6]);
373
356
  }
374
357
  function sha256(data) {
375
- return createHash("sha256").update(data).digest("hex").toLowerCase();
358
+ return createHash("sha256").update(data).digest("hex").toLowerCase();
376
359
  }
377
360
  function hS256(secret, data) {
378
- return createHmac("sha256", secret).update(data).digest("hex").toLowerCase();
361
+ return createHmac("sha256", secret).update(data).digest("hex").toLowerCase();
379
362
  }
380
363
  function convertBodyData(body) {
381
- if (typeof body === "string") {
382
- return body;
383
- }
384
- return JSON.stringify(body);
364
+ if (typeof body === "string") return body;
365
+ return JSON.stringify(body);
385
366
  }
386
367
  function parseRawAuthHeader(authString, prefix) {
387
- if (!authString || !authString.startsWith(prefix + " ")) {
388
- return null;
389
- }
390
- return fromEntries(authString.substring(prefix.length + 1).split(",").map(kvs => {
391
- const kv = kvs.split("=");
392
- if (kv.length !== 2) {
393
- return null;
394
- }
395
- const key = kv[0].trim();
396
- const value = getValue(kv[1]);
397
- if (!key || !value) {
398
- return null;
399
- }
400
- return [key, value];
401
- }).filter(v => v !== null));
368
+ if (!authString || !authString.startsWith(prefix + " ")) return null;
369
+ return fromEntries(authString.substring(prefix.length + 1).split(",").map((kvs) => {
370
+ const kv = kvs.split("=");
371
+ if (kv.length !== 2) return null;
372
+ const key = kv[0].trim();
373
+ const value = getValue(kv[1]);
374
+ if (!key || !value) return null;
375
+ return [key, value];
376
+ }).filter((v) => v !== null));
402
377
  }
403
378
  function getValue(value) {
404
- const v = value.trim();
405
- return /^".+"$/.test(v) ? v.replace(/^"|"$/g, "") : v;
379
+ const v = value.trim();
380
+ return /^".+"$/.test(v) ? v.replace(/^"|"$/g, "") : v;
406
381
  }
407
-
382
+ //#endregion
383
+ //#region src/utils/http.ts
408
384
  async function readBody(req, backup) {
409
- const body = [];
410
- if (!req.readable) {
411
- backup || console.error({
412
- type: "RequestUnReadable",
413
- url: req.url,
414
- methe: req.method,
415
- message: "Cannot read body, stream not readable"
416
- });
417
- return backup || "";
418
- }
419
- return new Promise((resolve, reject) => {
420
- req.on("error", reject);
421
- req.on("data", chunk => body.push(chunk));
422
- req.on("end", () => {
423
- resolve(Buffer.concat(body).toString("utf-8"));
424
- });
425
- });
385
+ const body = [];
386
+ if (!req.readable) {
387
+ backup || console.error({
388
+ type: "RequestUnReadable",
389
+ url: req.url,
390
+ methe: req.method,
391
+ message: "Cannot read body, stream not readable"
392
+ });
393
+ return backup || "";
394
+ }
395
+ return new Promise((resolve, reject) => {
396
+ req.on("error", reject);
397
+ req.on("data", (chunk) => body.push(chunk));
398
+ req.on("end", () => {
399
+ resolve(Buffer.concat(body).toString("utf-8"));
400
+ });
401
+ });
426
402
  }
427
403
  async function done(res, statusCode, message) {
428
- res.statusCode = statusCode;
429
- if (statusCode !== 204) {
430
- res.write(message || "");
431
- }
432
- res.end();
404
+ res.statusCode = statusCode;
405
+ if (statusCode !== 204) res.write(message || "");
406
+ res.end();
433
407
  }
434
408
  async function responseError(res, statusCode, error, message) {
435
- res.statusCode = statusCode;
436
- if (statusCode !== 204) {
437
- res.setHeader("Content-Type", "application/json");
438
- res.write(JSON.stringify({
439
- error,
440
- message
441
- }));
442
- }
443
- res.end();
409
+ res.statusCode = statusCode;
410
+ if (statusCode !== 204) {
411
+ res.setHeader("Content-Type", "application/json");
412
+ res.write(JSON.stringify({
413
+ error,
414
+ message
415
+ }));
416
+ }
417
+ res.end();
444
418
  }
445
419
  async function responseJson(res, data, statusCode = 200) {
446
- res.statusCode = statusCode;
447
- if (statusCode !== 204) {
448
- res.setHeader("Content-Type", "application/json");
449
- res.write(JSON.stringify(data));
450
- }
451
- res.end();
452
- }
453
-
420
+ res.statusCode = statusCode;
421
+ if (statusCode !== 204) {
422
+ res.setHeader("Content-Type", "application/json");
423
+ res.write(JSON.stringify(data));
424
+ }
425
+ res.end();
426
+ }
427
+ //#endregion
428
+ //#region src/utils/index.ts
454
429
  /** 生成一个 SessionID 以用作用户上下线的上报标记 */
455
430
  function genSessionID(comboId) {
456
- const ts = process.hrtime.bigint();
457
- const r = Math.random() + Math.random();
458
- return createHash("md5").update(`${comboId}${ts}${r}`).digest("hex").toLowerCase();
431
+ const ts = process.hrtime.bigint();
432
+ const r = Math.random() + Math.random();
433
+ return createHash("md5").update(`${comboId}${ts}${r}`).digest("hex").toLowerCase();
459
434
  }
460
435
  /** 生成一个随机id */
461
436
  function genNonceString() {
462
- const ts = process.hrtime.bigint();
463
- const r = Math.random() + Math.random();
464
- return createHash("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
437
+ const ts = process.hrtime.bigint();
438
+ const r = Math.random() + Math.random();
439
+ return createHash("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
465
440
  }
466
-
441
+ //#endregion
442
+ //#region src/request/inc/rule.ts
467
443
  const defaultDataField = "data";
468
444
  const defaultMessageField = "message";
469
445
  /**
470
- * 分析响应内容中的错误信息和数据
471
- */
446
+ * 分析响应内容中的错误信息和数据
447
+ */
472
448
  function analyseResponse(status, statusText, responseText, globalRule, rule) {
473
- const responseRule = rule || globalRule;
474
- return statusOK(status) ? getResponseOKInfo(responseRule.ok || globalRule.ok, status, statusText, responseText) : getReponseFailedInfo(responseRule.failed || globalRule.failed, statusText, responseText);
449
+ const responseRule = rule || globalRule;
450
+ return statusOK(status) ? getResponseOKInfo(responseRule.ok || globalRule.ok, status, statusText, responseText) : getReponseFailedInfo(responseRule.failed || globalRule.failed, statusText, responseText);
475
451
  }
476
452
  function getReponseFailedInfo(rule, statusText, responseText) {
477
- const r = rule || {
478
- resolve: "json",
479
- messageField: defaultMessageField
480
- };
481
- const result = {
482
- ok: false,
483
- code: statusText,
484
- message: responseText,
485
- data: null
486
- };
487
- switch (r.resolve) {
488
- case "body":
489
- result.message = formatPresetBody(responseText) || responseText;
490
- break;
491
- case "json":
492
- const {
493
- code,
494
- message
495
- } = formatJsonBody(responseText, r.statusField, r.messageField);
496
- result.code = code || statusText;
497
- result.message = formatPresetBody(responseText) || message;
498
- break;
499
- }
500
- return result;
453
+ const r = rule || {
454
+ resolve: "json",
455
+ messageField: defaultMessageField
456
+ };
457
+ const result = {
458
+ ok: false,
459
+ code: statusText,
460
+ message: responseText,
461
+ data: null
462
+ };
463
+ switch (r.resolve) {
464
+ case "body":
465
+ result.message = formatPresetBody(responseText) || responseText;
466
+ break;
467
+ case "json":
468
+ const { code, message } = formatJsonBody(responseText, r.statusField, r.messageField);
469
+ result.code = code || statusText;
470
+ result.message = formatPresetBody(responseText) || message;
471
+ break;
472
+ }
473
+ return result;
501
474
  }
502
475
  function formatJsonBody(body, statusField, msgField = defaultMessageField) {
503
- if (!isJsonLike(body)) {
504
- return {
505
- message: ""
506
- };
507
- }
508
- const json = parseJSON(body);
509
- if (!json || !isStringRecord(json)) {
510
- return {
511
- message: body
512
- };
513
- }
514
- return {
515
- code: statusField ? readMessageFrom(json, statusField) : "",
516
- message: readMessageFrom(json, msgField) || body
517
- };
476
+ if (!isJsonLike(body)) return { message: "" };
477
+ const json = parseJSON(body);
478
+ if (!json || !isStringRecord(json)) return { message: body };
479
+ return {
480
+ code: statusField ? readMessageFrom(json, statusField) : "",
481
+ message: readMessageFrom(json, msgField) || body
482
+ };
518
483
  }
519
484
  function readMessageFrom(json, field) {
520
- const fields = Array.isArray(field) ? field : [field];
521
- for (const field of fields) {
522
- if (field in json) {
523
- return convert2str(json[field]);
524
- }
525
- }
526
- return "";
485
+ const fields = Array.isArray(field) ? field : [field];
486
+ for (const field of fields) if (field in json) return convert2str(json[field]);
487
+ return "";
527
488
  }
528
489
  function convert2str(data) {
529
- if (!data) {
530
- return "";
531
- }
532
- if (typeof data === "string") {
533
- return data;
534
- }
535
- return JSON.stringify(data);
490
+ if (!data) return "";
491
+ if (typeof data === "string") return data;
492
+ return JSON.stringify(data);
536
493
  }
537
494
  const htmlReg = /<title>([^<]+)<\/title>/i;
538
495
  const xmlReg = /<message>([^<]+)<\/message>/i;
539
496
  function formatPresetBody(str) {
540
- const htmlMatch = str.match(htmlReg);
541
- if (htmlMatch) {
542
- return htmlMatch[1];
543
- }
544
- const xmlMatch = str.match(xmlReg);
545
- if (xmlMatch) {
546
- return xmlMatch[1];
547
- }
548
- return "";
497
+ const htmlMatch = str.match(htmlReg);
498
+ if (htmlMatch) return htmlMatch[1];
499
+ const xmlMatch = str.match(xmlReg);
500
+ if (xmlMatch) return xmlMatch[1];
501
+ return "";
549
502
  }
550
503
  function getResponseOKInfo(rule, status, statusText, responseText) {
551
- const r = rule || {
552
- resolve: "body"
553
- };
554
- const result = {
555
- ok: true,
556
- code: statusText,
557
- message: "",
558
- data: null
559
- };
560
- // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status#%E6%88%90%E5%8A%9F%E5%93%8D%E5%BA%94
561
- if (status === 202 || status === 204 || !responseText) {
562
- return result;
563
- }
564
- // 解析策略为 body 则直接将 body 当作响应数据
565
- if (r.resolve === "body") {
566
- result.data = isJsonLike(responseText) ? parseJSON(responseText) : responseText;
567
- return result;
568
- }
569
- // 否则解析策略为 json,从 object json 中查找数据和消息
570
- const response = parseJSON(responseText);
571
- if (!response || !isStringRecord(response)) {
572
- result.ok = false;
573
- result.code = "ResponseFormatError";
574
- result.message = "响应内容无法格式化为 Object";
575
- return result;
576
- }
577
- const statusField = r.statusField;
578
- const statusOKValue = r.statusOKValue || "";
579
- const dataField = r.dataField || defaultDataField;
580
- const messageField = r.messageField || defaultMessageField;
581
- const ignoreMessage = r.ignoreMessage || "";
582
- if (statusField && !(statusField in response)) {
583
- result.ok = false;
584
- result.code = "ResponseFieldMissing";
585
- result.message = "响应内容找不到状态字段 " + statusField;
586
- return result;
587
- }
588
- const code = statusField ? response[statusField] + "" : "";
589
- result.ok = statusField ? code === statusOKValue : true;
590
- result.code = code || statusText;
591
- result.data = dataField in response ? response[dataField] : null;
592
- result.message = readMessageFrom(response, messageField);
593
- if (ignoreMessage && result.message) {
594
- if (Array.isArray(ignoreMessage) && ignoreMessage.includes(result.message) || typeof ignoreMessage === "string" && result.message === ignoreMessage) {
595
- result.message = "";
596
- }
597
- }
598
- return result;
504
+ const r = rule || { resolve: "body" };
505
+ const result = {
506
+ ok: true,
507
+ code: statusText,
508
+ message: "",
509
+ data: null
510
+ };
511
+ if (status === 202 || status === 204 || !responseText) return result;
512
+ if (r.resolve === "body") {
513
+ result.data = isJsonLike(responseText) ? parseJSON(responseText) : responseText;
514
+ return result;
515
+ }
516
+ const response = parseJSON(responseText);
517
+ if (!response || !isStringRecord(response)) {
518
+ result.ok = false;
519
+ result.code = "ResponseFormatError";
520
+ result.message = "响应内容无法格式化为 Object";
521
+ return result;
522
+ }
523
+ const statusField = r.statusField;
524
+ const statusOKValue = r.statusOKValue || "";
525
+ const dataField = r.dataField || defaultDataField;
526
+ const messageField = r.messageField || defaultMessageField;
527
+ const ignoreMessage = r.ignoreMessage || "";
528
+ if (statusField && !(statusField in response)) {
529
+ result.ok = false;
530
+ result.code = "ResponseFieldMissing";
531
+ result.message = "响应内容找不到状态字段 " + statusField;
532
+ return result;
533
+ }
534
+ const code = statusField ? response[statusField] + "" : "";
535
+ result.ok = statusField ? code === statusOKValue : true;
536
+ result.code = code || statusText;
537
+ result.data = dataField in response ? response[dataField] : null;
538
+ result.message = readMessageFrom(response, messageField);
539
+ if (ignoreMessage && result.message) {
540
+ if (Array.isArray(ignoreMessage) && ignoreMessage.includes(result.message) || typeof ignoreMessage === "string" && result.message === ignoreMessage) result.message = "";
541
+ }
542
+ return result;
599
543
  }
600
544
  function statusOK(status) {
601
- return status >= 200 && status < 400;
545
+ return status >= 200 && status < 400;
602
546
  }
603
-
547
+ //#endregion
548
+ //#region src/request/inc/retry.ts
604
549
  async function retryRequest(agent, url, config, options, _try) {
605
- var _ref, _options$maxRetry, _options$retryResolve, _options$retryInterva;
606
- const currentTryCount = _try || 0;
607
- const maxRetry = Math.min(10, (_ref = (_options$maxRetry = options == null ? void 0 : options.maxRetry) != null ? _options$maxRetry : config.get("maxRetry")) != null ? _ref : 0);
608
- const retryResolve = (_options$retryResolve = options == null ? void 0 : options.retryResolve) != null ? _options$retryResolve : config.get("retryResolve");
609
- const logger = config.get("logHandler") || noop;
610
- logger({
611
- type: "prepear",
612
- url,
613
- method: (options == null ? void 0 : options.method) || "GET",
614
- retry: currentTryCount,
615
- maxRetry,
616
- message: currentTryCount === 0 ? "start" : `retry ${currentTryCount}/${maxRetry} start`,
617
- headers: options == null ? void 0 : options.headers,
618
- options
619
- });
620
- const start = Date.now();
621
- const result = await agent(url, config, options);
622
- const status = result.status;
623
- const cost = Date.now() - start;
624
- const payload = `[cost ${cost}][${status}] ${status < 0 ? result.body : ""}`;
625
- logger({
626
- type: "finished",
627
- url,
628
- method: result.method,
629
- retry: currentTryCount,
630
- maxRetry,
631
- message: currentTryCount === 0 ? `finish ${payload}` : `retry ${currentTryCount}/${maxRetry} finish ${payload}`,
632
- response: result,
633
- headers: result.headers,
634
- cost
635
- });
636
- // status 大于 0 表示服务器已经有响应
637
- const ok = statusOK(status);
638
- if (!maxRetry || retryResolve === "network" && status > 0 || retryResolve === "status" && ok || currentTryCount >= maxRetry) {
639
- return result;
640
- }
641
- const retryInterval = (_options$retryInterva = options == null ? void 0 : options.retryInterval) != null ? _options$retryInterva : config.get("retryInterval");
642
- // 最短间隔 100ms 才能重试
643
- await sleep(Math.max(100, typeof retryInterval === "function" ? retryInterval(currentTryCount + 1) : retryInterval));
644
- return await retryRequest(agent, url, config, options, currentTryCount + 1);
645
- }
646
-
550
+ var _ref, _options$maxRetry, _options$retryResolve, _options$retryInterva;
551
+ const currentTryCount = _try || 0;
552
+ const maxRetry = Math.min(10, (_ref = (_options$maxRetry = options === null || options === void 0 ? void 0 : options.maxRetry) !== null && _options$maxRetry !== void 0 ? _options$maxRetry : config.get("maxRetry")) !== null && _ref !== void 0 ? _ref : 0);
553
+ const retryResolve = (_options$retryResolve = options === null || options === void 0 ? void 0 : options.retryResolve) !== null && _options$retryResolve !== void 0 ? _options$retryResolve : config.get("retryResolve");
554
+ const logger = config.get("logHandler") || noop;
555
+ logger({
556
+ type: "prepear",
557
+ url,
558
+ method: (options === null || options === void 0 ? void 0 : options.method) || "GET",
559
+ retry: currentTryCount,
560
+ maxRetry,
561
+ message: currentTryCount === 0 ? "start" : `retry ${currentTryCount}/${maxRetry} start`,
562
+ headers: options === null || options === void 0 ? void 0 : options.headers,
563
+ options
564
+ });
565
+ const start = Date.now();
566
+ const result = await agent(url, config, options);
567
+ const status = result.status;
568
+ const cost = Date.now() - start;
569
+ const payload = `[cost ${cost}][${status}] ${status < 0 ? result.body : ""}`;
570
+ logger({
571
+ type: "finished",
572
+ url,
573
+ method: result.method,
574
+ retry: currentTryCount,
575
+ maxRetry,
576
+ message: currentTryCount === 0 ? `finish ${payload}` : `retry ${currentTryCount}/${maxRetry} finish ${payload}`,
577
+ response: result,
578
+ headers: result.headers,
579
+ cost
580
+ });
581
+ const ok = statusOK(status);
582
+ if (!maxRetry || retryResolve === "network" && status > 0 || retryResolve === "status" && ok || currentTryCount >= maxRetry) return result;
583
+ const retryInterval = (_options$retryInterva = options === null || options === void 0 ? void 0 : options.retryInterval) !== null && _options$retryInterva !== void 0 ? _options$retryInterva : config.get("retryInterval");
584
+ await sleep(Math.max(100, typeof retryInterval === "function" ? retryInterval(currentTryCount + 1) : retryInterval));
585
+ return await retryRequest(agent, url, config, options, currentTryCount + 1);
586
+ }
587
+ //#endregion
588
+ //#region src/request/inc/response.ts
647
589
  function handleResponse(res, url, config, options) {
648
- var _config$get2;
649
- // status为负数的表示网络错误或请求取消等异常情况
650
- if (res.status < 0) {
651
- return checkGlobalMessage({
652
- ok: false,
653
- status: res.status,
654
- code: res.statusText,
655
- headers: {},
656
- message: "",
657
- data: null
658
- }, `${res.method} ${url} ${res.statusText}`, res.method, url, config, options);
659
- }
660
- // 处理全局 http 错误
661
- if (!statusOK(res.status)) {
662
- var _config$get;
663
- (_config$get = config.get("errorHandler")) == null || _config$get(res.status, res.method, url);
664
- }
665
- // 分析响应内容
666
- const result = {
667
- ...analyseResponse(res.status, res.statusText, res.body, config.get("responseRule"), options == null ? void 0 : options.responseRule),
668
- status: res.status,
669
- headers: fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
670
- };
671
- // 全局处理响应结果 (浅复制,防止被修改,同时保留修改 result.data 的可能性)
672
- (_config$get2 = config.get("responseHandler")) == null || _config$get2({
673
- ...result
674
- }, res.method, url);
675
- // 检查并全局提示
676
- const defaultMessage = result.ok ? result.message : `${res.method} ${url} [${result.code || res.statusText}] ${result.message || res.statusText}`;
677
- return checkGlobalMessage(result, defaultMessage, res.method, url, config, options);
590
+ var _config$get2;
591
+ if (res.status < 0) return checkGlobalMessage({
592
+ ok: false,
593
+ status: res.status,
594
+ code: res.statusText,
595
+ headers: {},
596
+ message: "",
597
+ data: null
598
+ }, `${res.method} ${url} ${res.statusText}`, res.method, url, config, options);
599
+ if (!statusOK(res.status)) {
600
+ var _config$get;
601
+ (_config$get = config.get("errorHandler")) === null || _config$get === void 0 || _config$get(res.status, res.method, url);
602
+ }
603
+ const result = {
604
+ ...analyseResponse(res.status, res.statusText, res.body, config.get("responseRule"), options === null || options === void 0 ? void 0 : options.responseRule),
605
+ status: res.status,
606
+ headers: fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
607
+ };
608
+ (_config$get2 = config.get("responseHandler")) === null || _config$get2 === void 0 || _config$get2({ ...result }, res.method, url);
609
+ return checkGlobalMessage(result, result.ok ? result.message : `${res.method} ${url} [${result.code || res.statusText}] ${result.message || res.statusText}`, res.method, url, config, options);
678
610
  }
679
611
  function checkGlobalMessage(result, defaultMessage, method, url, config, options) {
680
- const gmessageConvert = config.get("message");
681
- const messageConvert = gmessageConvert === false || (options == null ? void 0 : options.message) === false ? false : (options == null ? void 0 : options.message) || gmessageConvert;
682
- if (messageConvert !== false) {
683
- config.showMessage(!result.ok, typeof messageConvert === "function" ? messageConvert(result, method, url, defaultMessage) : defaultMessage);
684
- }
685
- return result;
686
- }
687
-
612
+ const gmessageConvert = config.get("message");
613
+ const messageConvert = gmessageConvert === false || (options === null || options === void 0 ? void 0 : options.message) === false ? false : (options === null || options === void 0 ? void 0 : options.message) || gmessageConvert;
614
+ if (messageConvert !== false) config.showMessage(!result.ok, typeof messageConvert === "function" ? messageConvert(result, method, url, defaultMessage) : defaultMessage);
615
+ return result;
616
+ }
617
+ //#endregion
618
+ //#region src/request/inc/option.ts
688
619
  async function convertOptions(url, config, options) {
689
- var _config$get, _config$get2;
690
- const opt = Object.assign({
691
- method: "GET"
692
- }, options);
693
- const method = opt.method;
694
- if (method === "GET" || method === "HEAD" || method === "DELETE") {
695
- if (opt.body !== undefined) {
696
- console.warn("request body is invalid with method get, head, delete");
697
- delete opt.body;
698
- }
699
- }
700
- const headers = Object.assign({
701
- "Content-Type": "application/json;charset=utf-8"
702
- }, opt.headers);
703
- const p = opt.params || {};
704
- const params = {};
705
- Object.keys(p).forEach(key => {
706
- if (p[key] !== undefined) {
707
- params[key] = convertParam(p[key]);
708
- }
709
- });
710
- const fullUrl = config.getFullUrl(url);
711
- const body = convertBody(opt.body);
712
- const timeout = opt.timeout || config.get("timeout");
713
- // 全局请求干预函数,可以修改 headers 和 params 并返回新的 url 地址
714
- const newURL = await ((_config$get = config.get("requestTransformer")) == null ? void 0 : _config$get({
715
- headers,
716
- params,
717
- method,
718
- url: fullUrl,
719
- body
720
- }));
721
- const finalUrl = typeof newURL === "string" && newURL ? newURL : fullUrl;
722
- // 打印日志
723
- (_config$get2 = config.get("logHandler")) == null || _config$get2({
724
- type: "ready",
725
- url: finalUrl,
726
- method,
727
- headers,
728
- timeout,
729
- body
730
- });
731
- // 返回
732
- return {
733
- url: finalUrl,
734
- method,
735
- body,
736
- params,
737
- headers,
738
- timeout
739
- };
620
+ var _config$get, _config$get2;
621
+ const opt = Object.assign({ method: "GET" }, options);
622
+ const method = opt.method;
623
+ if (method === "GET" || method === "HEAD" || method === "DELETE") {
624
+ if (opt.body !== void 0) {
625
+ console.warn("request body is invalid with method get, head, delete");
626
+ delete opt.body;
627
+ }
628
+ }
629
+ const headers = Object.assign({ "Content-Type": "application/json;charset=utf-8" }, opt.headers);
630
+ const p = opt.params || {};
631
+ const params = {};
632
+ Object.keys(p).forEach((key) => {
633
+ if (p[key] !== void 0) params[key] = convertParam(p[key]);
634
+ });
635
+ const fullUrl = config.getFullUrl(url);
636
+ const body = convertBody(opt.body);
637
+ const timeout = opt.timeout || config.get("timeout");
638
+ const newURL = await ((_config$get = config.get("requestTransformer")) === null || _config$get === void 0 ? void 0 : _config$get({
639
+ headers,
640
+ params,
641
+ method,
642
+ url: fullUrl,
643
+ body
644
+ }));
645
+ const finalUrl = typeof newURL === "string" && newURL ? newURL : fullUrl;
646
+ (_config$get2 = config.get("logHandler")) === null || _config$get2 === void 0 || _config$get2({
647
+ type: "ready",
648
+ url: finalUrl,
649
+ method,
650
+ headers,
651
+ timeout,
652
+ body
653
+ });
654
+ return {
655
+ url: finalUrl,
656
+ method,
657
+ body,
658
+ params,
659
+ headers,
660
+ timeout
661
+ };
740
662
  }
741
663
  /** 将数据转成 string 格式表示,仅仅特殊处理 array 为 item,item... */
742
664
  function convertParam(val) {
743
- if (typeof val === "string") {
744
- return val;
745
- }
746
- if (Array.isArray(val)) {
747
- return val.join(",");
748
- }
749
- return val + "";
665
+ if (typeof val === "string") return val;
666
+ if (Array.isArray(val)) return val.join(",");
667
+ return val + "";
750
668
  }
751
669
  function convertBody(body) {
752
- if (!body) {
753
- return;
754
- }
755
- if (typeof body === "string" || body instanceof URLSearchParams) {
756
- return body;
757
- }
758
- return JSON.stringify(body);
759
- }
760
-
670
+ if (!body) return;
671
+ if (typeof body === "string" || body instanceof URLSearchParams) return body;
672
+ return JSON.stringify(body);
673
+ }
674
+ //#endregion
675
+ //#region src/request/inc/request.ts
761
676
  /**
762
- * 基于 nodejs 的 http/https 包的网络请求包装函数,url 必须是一个完整 url
763
- *
764
- * 该方法必定 resolve,限制在 nodejs 环境中使用
765
- */
766
- const nodeRequest = async function (url, config, options) {
767
- return handleResponse(await retryRequest(coreNodeRequest, url, config, options), url, config, options);
677
+ * 基于 nodejs 的 http/https 包的网络请求包装函数,url 必须是一个完整 url
678
+ *
679
+ * 该方法必定 resolve,限制在 nodejs 环境中使用
680
+ */
681
+ const nodeRequest = async function(url, config, options) {
682
+ return handleResponse(await retryRequest(coreNodeRequest, url, config, options), url, config, options);
768
683
  };
769
- const coreNodeRequest = async function (url, config, options) {
770
- const opt = await convertOptions(url, config, options);
771
- if (!isFullURL(opt.url)) {
772
- return {
773
- url: opt.url,
774
- method: opt.method,
775
- status: -2,
776
- statusText: "URLFormatError",
777
- headers: {},
778
- body: ""
779
- };
780
- }
781
- const client = /^https:\/\//i.test(opt.url) ? https : http;
782
- const iURL = new URL(opt.url);
783
- const params = opt.params;
784
- if (params instanceof Object) {
785
- Object.keys(params).forEach(key => iURL.searchParams.set(key, params[key]));
786
- }
787
- const isHeadRequest = opt.method === "HEAD";
788
- return new Promise(resolve => {
789
- const req = client.request(iURL.toString(), {
790
- headers: opt.headers,
791
- method: opt.method,
792
- timeout: opt.timeout > 0 ? opt.timeout : undefined
793
- }, function (res) {
794
- const resbody = [];
795
- res.on("data", chunk => resbody.push(chunk));
796
- res.on("end", () => {
797
- const headers = fromEntries(Object.entries(res.headers).map(([key, value]) => {
798
- return [key.toLowerCase(), Array.isArray(value) ? value.join(",") : value];
799
- }));
800
- resolve({
801
- url: iURL.toString(),
802
- method: opt.method,
803
- status: res.statusCode || -3,
804
- statusText: res.statusMessage || "Unknown",
805
- headers,
806
- body: isHeadRequest ? "" : Buffer.concat(resbody).toString("utf-8")
807
- });
808
- });
809
- });
810
- req.on("error", e => {
811
- resolve({
812
- url: iURL.toString(),
813
- method: opt.method,
814
- status: -1,
815
- statusText: e.name || "Unknown",
816
- body: e.message
817
- });
818
- });
819
- req.on("timeout", () => {
820
- resolve({
821
- url: iURL.toString(),
822
- method: opt.method,
823
- status: -1,
824
- statusText: "Timeout",
825
- body: ""
826
- });
827
- });
828
- if (opt.body) {
829
- req.write(opt.body);
830
- }
831
- req.end();
832
- });
684
+ const coreNodeRequest = async function(url, config, options) {
685
+ const opt = await convertOptions(url, config, options);
686
+ if (!isFullURL(opt.url)) return {
687
+ url: opt.url,
688
+ method: opt.method,
689
+ status: -2,
690
+ statusText: "URLFormatError",
691
+ headers: {},
692
+ body: ""
693
+ };
694
+ const client = /^https:\/\//i.test(opt.url) ? https : http;
695
+ const iURL = new URL(opt.url);
696
+ const params = opt.params;
697
+ if (params instanceof Object) Object.keys(params).forEach((key) => iURL.searchParams.set(key, params[key]));
698
+ const isHeadRequest = opt.method === "HEAD";
699
+ return new Promise((resolve) => {
700
+ const req = client.request(iURL.toString(), {
701
+ headers: opt.headers,
702
+ method: opt.method,
703
+ timeout: opt.timeout > 0 ? opt.timeout : void 0
704
+ }, function(res) {
705
+ const resbody = [];
706
+ res.on("data", (chunk) => resbody.push(chunk));
707
+ res.on("end", () => {
708
+ const headers = fromEntries(Object.entries(res.headers).map(([key, value]) => {
709
+ return [key.toLowerCase(), Array.isArray(value) ? value.join(",") : value];
710
+ }));
711
+ resolve({
712
+ url: iURL.toString(),
713
+ method: opt.method,
714
+ status: res.statusCode || -3,
715
+ statusText: res.statusMessage || "Unknown",
716
+ headers,
717
+ body: isHeadRequest ? "" : Buffer.concat(resbody).toString("utf-8")
718
+ });
719
+ });
720
+ });
721
+ req.on("error", (e) => {
722
+ resolve({
723
+ url: iURL.toString(),
724
+ method: opt.method,
725
+ status: -1,
726
+ statusText: e.name || "Unknown",
727
+ body: e.message
728
+ });
729
+ });
730
+ req.on("timeout", () => {
731
+ resolve({
732
+ url: iURL.toString(),
733
+ method: opt.method,
734
+ status: -1,
735
+ statusText: "Timeout",
736
+ body: ""
737
+ });
738
+ });
739
+ if (opt.body) req.write(opt.body);
740
+ req.end();
741
+ });
833
742
  };
834
-
743
+ //#endregion
744
+ //#region src/request/inc/cache.ts
835
745
  /** 为 get 请求并发而设计的缓冲工具 */
836
- class Cache {
837
- constructor(ttl = 500) {
838
- this.ttl = void 0;
839
- this.cache = void 0;
840
- this.cache = {};
841
- this.ttl = Math.max(ttl, 0);
842
- }
843
- getKey(url, param) {
844
- const p = Object.keys(param || {}).sort().map(key => `${key}#${param == null ? void 0 : param[key]}`);
845
- return url + p.join(",");
846
- }
847
- updateTTL(ttl) {
848
- this.ttl = Math.max(ttl, 0);
849
- }
850
- get(key) {
851
- if (this.ttl === 0) {
852
- return null;
853
- }
854
- const c = this.cache[key];
855
- if (!c) {
856
- return null;
857
- }
858
- if (c.ttl < Date.now()) {
859
- delete this.cache[key];
860
- return null;
861
- }
862
- return c.res;
863
- }
864
- set(key, action) {
865
- if (this.ttl === 0) {
866
- return;
867
- }
868
- this.cache[key] = {
869
- ttl: Date.now() + this.ttl,
870
- res: action
871
- };
872
- }
873
- }
874
-
746
+ var Cache = class {
747
+ constructor(ttl = 500) {
748
+ this.cache = {};
749
+ this.ttl = Math.max(ttl, 0);
750
+ }
751
+ getKey(url, param) {
752
+ return url + Object.keys(param || {}).sort().map((key) => `${key}#${param === null || param === void 0 ? void 0 : param[key]}`).join(",");
753
+ }
754
+ updateTTL(ttl) {
755
+ this.ttl = Math.max(ttl, 0);
756
+ }
757
+ get(key) {
758
+ if (this.ttl === 0) return null;
759
+ const c = this.cache[key];
760
+ if (!c) return null;
761
+ if (c.ttl < Date.now()) {
762
+ delete this.cache[key];
763
+ return null;
764
+ }
765
+ return c.res;
766
+ }
767
+ set(key, action) {
768
+ if (this.ttl === 0) return;
769
+ this.cache[key] = {
770
+ ttl: Date.now() + this.ttl,
771
+ res: action
772
+ };
773
+ }
774
+ };
775
+ //#endregion
776
+ //#region src/request/inc/guard.ts
875
777
  function checkTypedDataResult(url, result, config, typeGard) {
876
- if (result.ok && !isEmpty(result.data) && typeGard) {
877
- const guard = getTypeGuard(typeGard, "响应数据未能正确识别");
878
- if (guard.guard(result.data)) {
879
- return result;
880
- }
881
- config.showMessage(true, `${url} ${guard.message}`);
882
- result.data = null;
883
- return result;
884
- }
885
- return result;
886
- }
887
-
888
- class RequestGlobalConfig {
889
- constructor(config) {
890
- // 保存的配置需要部分字段强制设置默认值
891
- this.config = {
892
- baseURL: "",
893
- maxRetry: 0,
894
- retryInterval: 1000,
895
- retryResolve: "network",
896
- timeout: 5000,
897
- cacheTTL: 500,
898
- responseRule: {
899
- ok: {
900
- resolve: "body"
901
- },
902
- failed: {
903
- resolve: "json",
904
- messageField: "message"
905
- }
906
- }
907
- };
908
- config && this.set(config);
909
- }
910
- set(config) {
911
- if (config.baseURL && !/^\/.+/.test(config.baseURL) && !isFullURL(config.baseURL)) {
912
- console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址");
913
- throw new Error("BaseURLError");
914
- }
915
- Object.assign(this.config, config);
916
- }
917
- get(key) {
918
- return this.config[key];
919
- }
920
- /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
921
- getFullUrl(url) {
922
- return url.startsWith("/") ? getFullURL(url) : getFullURL(url, this.config.baseURL);
923
- }
924
- /** 提示消息 */
925
- showMessage(isError, message) {
926
- if (this.config.messageHandler && message) {
927
- this.config.messageHandler(isError, message);
928
- }
929
- }
930
- }
931
-
778
+ if (result.ok && !isEmpty(result.data) && typeGard) {
779
+ const guard = getTypeGuard(typeGard, "响应数据未能正确识别");
780
+ if (guard.guard(result.data)) return result;
781
+ config.showMessage(true, `${url} ${guard.message}`);
782
+ result.data = null;
783
+ return result;
784
+ }
785
+ return result;
786
+ }
787
+ //#endregion
788
+ //#region src/request/inc/config.ts
789
+ var RequestGlobalConfig = class {
790
+ constructor(config) {
791
+ this.config = {
792
+ baseURL: "",
793
+ maxRetry: 0,
794
+ retryInterval: 1e3,
795
+ retryResolve: "network",
796
+ timeout: 5e3,
797
+ cacheTTL: 500,
798
+ responseRule: {
799
+ ok: { resolve: "body" },
800
+ failed: {
801
+ resolve: "json",
802
+ messageField: "message"
803
+ }
804
+ }
805
+ };
806
+ config && this.set(config);
807
+ }
808
+ set(config) {
809
+ if (config.baseURL && !/^\/.+/.test(config.baseURL) && !isFullURL(config.baseURL)) {
810
+ console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址");
811
+ throw new Error("BaseURLError");
812
+ }
813
+ Object.assign(this.config, config);
814
+ }
815
+ get(key) {
816
+ return this.config[key];
817
+ }
818
+ /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
819
+ getFullUrl(url) {
820
+ return url.startsWith("/") ? getFullURL(url) : getFullURL(url, this.config.baseURL);
821
+ }
822
+ /** 提示消息 */
823
+ showMessage(isError, message) {
824
+ if (this.config.messageHandler && message) this.config.messageHandler(isError, message);
825
+ }
826
+ };
827
+ //#endregion
828
+ //#region src/request/inc/main.ts
932
829
  /** 工具函数主类 */
933
- class NetRequestHandler {
934
- constructor(agent, config) {
935
- this.agent = void 0;
936
- this.config = void 0;
937
- this.cache = void 0;
938
- this.config = new RequestGlobalConfig(config);
939
- this.agent = agent;
940
- this.cache = new Cache(this.config.get("cacheTTL"));
941
- // bind this
942
- this.setConfig = this.setConfig.bind(this);
943
- this.getConfig = this.getConfig.bind(this);
944
- this.get = this.get.bind(this);
945
- this.post = this.post.bind(this);
946
- this.del = this.del.bind(this);
947
- this.patch = this.patch.bind(this);
948
- this.put = this.put.bind(this);
949
- this.head = this.head.bind(this);
950
- }
951
- /**
952
- * 执行网络请求
953
- */
954
- async exec(url, options) {
955
- return await this.agent(url, this.config, options);
956
- }
957
- /**
958
- * 检查响应的数据类型
959
- */
960
- async guard(url, result, typeGard) {
961
- return checkTypedDataResult(url, result, this.config, typeGard);
962
- }
963
- /**
964
- * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
965
- */
966
- setConfig(config) {
967
- this.config.set(config);
968
- this.cache.updateTTL(this.config.get("cacheTTL"));
969
- }
970
- /**
971
- * 读取默认的请求配置
972
- */
973
- getConfig(key) {
974
- return this.config.get(key);
975
- }
976
- /**
977
- * 发送一个 HEAD 请求,并且不处理响应 body
978
- */
979
- async head(url, options) {
980
- const ops = Object.assign({}, options || null);
981
- ops.method = "HEAD";
982
- return this.guard(url, await this.exec(url, ops), null);
983
- }
984
- async get(url, typeGard, options) {
985
- const ops = Object.assign({}, options || null);
986
- ops.method = "GET";
987
- const cacheKey = this.cache.getKey(url, ops.params);
988
- const cache = this.cache.get(cacheKey);
989
- if (cache) {
990
- return this.guard(url, await cache, typeGard || null);
991
- }
992
- const res = this.exec(url, ops);
993
- this.cache.set(cacheKey, res);
994
- return this.guard(url, await res, typeGard || null);
995
- }
996
- async post(url, data, typeGard, options) {
997
- const ops = Object.assign({}, options || null);
998
- ops.method = "POST";
999
- ops.body = data;
1000
- return this.guard(url, await this.exec(url, ops), typeGard || null);
1001
- }
1002
- async del(url, typeGard, options) {
1003
- const ops = Object.assign({}, options || null);
1004
- ops.method = "DELETE";
1005
- return this.guard(url, await this.exec(url, ops), typeGard || null);
1006
- }
1007
- async put(url, data, typeGard, options) {
1008
- const ops = Object.assign({}, options || null);
1009
- ops.method = "PUT";
1010
- ops.body = data;
1011
- return this.guard(url, await this.exec(url, ops), typeGard || null);
1012
- }
1013
- async patch(url, data, typeGard, options) {
1014
- const ops = Object.assign({}, options || null);
1015
- ops.method = "PATCH";
1016
- ops.body = data;
1017
- return this.guard(url, await this.exec(url, ops), typeGard || null);
1018
- }
1019
- }
1020
-
830
+ var NetRequestHandler = class {
831
+ constructor(agent, config) {
832
+ this.config = new RequestGlobalConfig(config);
833
+ this.agent = agent;
834
+ this.cache = new Cache(this.config.get("cacheTTL"));
835
+ this.setConfig = this.setConfig.bind(this);
836
+ this.getConfig = this.getConfig.bind(this);
837
+ this.get = this.get.bind(this);
838
+ this.post = this.post.bind(this);
839
+ this.del = this.del.bind(this);
840
+ this.patch = this.patch.bind(this);
841
+ this.put = this.put.bind(this);
842
+ this.head = this.head.bind(this);
843
+ }
844
+ /**
845
+ * 执行网络请求
846
+ */
847
+ async exec(url, options) {
848
+ return await this.agent(url, this.config, options);
849
+ }
850
+ /**
851
+ * 检查响应的数据类型
852
+ */
853
+ async guard(url, result, typeGard) {
854
+ return checkTypedDataResult(url, result, this.config, typeGard);
855
+ }
856
+ /**
857
+ * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
858
+ */
859
+ setConfig(config) {
860
+ this.config.set(config);
861
+ this.cache.updateTTL(this.config.get("cacheTTL"));
862
+ }
863
+ /**
864
+ * 读取默认的请求配置
865
+ */
866
+ getConfig(key) {
867
+ return this.config.get(key);
868
+ }
869
+ /**
870
+ * 发送一个 HEAD 请求,并且不处理响应 body
871
+ */
872
+ async head(url, options) {
873
+ const ops = Object.assign({}, options || null);
874
+ ops.method = "HEAD";
875
+ return this.guard(url, await this.exec(url, ops), null);
876
+ }
877
+ async get(url, typeGard, options) {
878
+ const ops = Object.assign({}, options || null);
879
+ ops.method = "GET";
880
+ const cacheKey = this.cache.getKey(url, ops.params);
881
+ const cache = this.cache.get(cacheKey);
882
+ if (cache) return this.guard(url, await cache, typeGard || null);
883
+ const res = this.exec(url, ops);
884
+ this.cache.set(cacheKey, res);
885
+ return this.guard(url, await res, typeGard || null);
886
+ }
887
+ async post(url, data, typeGard, options) {
888
+ const ops = Object.assign({}, options || null);
889
+ ops.method = "POST";
890
+ ops.body = data;
891
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
892
+ }
893
+ async del(url, typeGard, options) {
894
+ const ops = Object.assign({}, options || null);
895
+ ops.method = "DELETE";
896
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
897
+ }
898
+ async put(url, data, typeGard, options) {
899
+ const ops = Object.assign({}, options || null);
900
+ ops.method = "PUT";
901
+ ops.body = data;
902
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
903
+ }
904
+ async patch(url, data, typeGard, options) {
905
+ const ops = Object.assign({}, options || null);
906
+ ops.method = "PATCH";
907
+ ops.body = data;
908
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
909
+ }
910
+ };
911
+ //#endregion
912
+ //#region src/request/index.ts
1021
913
  function NetRequest(config) {
1022
- return new NetRequestHandler(nodeRequest, config);
914
+ return new NetRequestHandler(nodeRequest, config);
1023
915
  }
1024
-
916
+ //#endregion
917
+ //#region src/api/index.ts
1025
918
  const ApiPrefix = "/v1/server";
1026
919
  const TraceIdField = "x-trace-id";
1027
920
  /**
1028
- * Combo SDK For Server REST Api
1029
- */
1030
- class ApiClient {
1031
- constructor(config) {
1032
- var _config$maxRetry;
1033
- this.req = void 0;
1034
- verifyConfig(config);
1035
- const ua = getUserAgent(config.game);
1036
- this.req = NetRequest({
1037
- baseURL: `${config.endpoint.replace(/\/$/, "")}${ApiPrefix}`,
1038
- maxRetry: (_config$maxRetry = config.maxRetry) != null ? _config$maxRetry : 1,
1039
- retryInterval: config.retryInterval,
1040
- responseRule: {
1041
- ok: {
1042
- resolve: "body"
1043
- },
1044
- failed: {
1045
- resolve: "json",
1046
- statusField: "error",
1047
- messageField: "message"
1048
- }
1049
- },
1050
- requestTransformer({
1051
- headers,
1052
- method,
1053
- url,
1054
- params,
1055
- body
1056
- }) {
1057
- const iURL = new URL(url);
1058
- if (params) {
1059
- if (params instanceof Object) {
1060
- Object.keys(params).forEach(key => iURL.searchParams.set(key, params[key]));
1061
- }
1062
- }
1063
- headers["User-Agent"] = ua;
1064
- headers[AuthorizationField] = calcAuthorizationHeader({
1065
- game: config.game,
1066
- secret: config.secret,
1067
- endpoint: config.endpoint,
1068
- method,
1069
- url: iURL.toString(),
1070
- data: body || ""
1071
- });
1072
- },
1073
- logHandler: config.logger,
1074
- timeout: config.timeout || 5000
1075
- });
1076
- }
1077
- /**
1078
- * 创建订单
1079
- */
1080
- async createOrder(option) {
1081
- const {
1082
- ok,
1083
- data,
1084
- code,
1085
- status,
1086
- message,
1087
- headers
1088
- } = await this.req.post("create-order", option, isCreateOrderResponse);
1089
- if (!ok || !data) {
1090
- console.error({
1091
- type: "createOrder Error",
1092
- status,
1093
- code,
1094
- message,
1095
- traceId: headers[TraceIdField]
1096
- });
1097
- throw new Error(`createOrder: ${message || code || status}`);
1098
- }
1099
- return data;
1100
- }
1101
- /**
1102
- * 通知世游服务端玩家进入游戏世界(上线)
1103
- *
1104
- * 此接口仅用于中宣部防沉迷系统的上下线数据上报
1105
- *
1106
- * @param comboId 聚合用户标识
1107
- * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
1108
- */
1109
- async enterGame(comboId, sessionId) {
1110
- const {
1111
- ok,
1112
- status,
1113
- code,
1114
- message,
1115
- headers
1116
- } = await this.req.post("enter-game", {
1117
- combo_id: comboId,
1118
- session_id: sessionId
1119
- });
1120
- if (!ok) {
1121
- console.error({
1122
- type: "enterGame Error",
1123
- status,
1124
- code,
1125
- message,
1126
- traceId: headers[TraceIdField]
1127
- });
1128
- }
1129
- return ok;
1130
- }
1131
- /**
1132
- * 通知世游服务端玩家离开游戏世界(下线)
1133
- *
1134
- * 此接口仅用于中宣部防沉迷系统的上下线数据上报
1135
- *
1136
- * @param comboId 聚合用户标识
1137
- * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
1138
- */
1139
- async leaveGame(comboId, sessionId) {
1140
- const {
1141
- ok,
1142
- status,
1143
- code,
1144
- message,
1145
- headers
1146
- } = await this.req.post("leave-game", {
1147
- combo_id: comboId,
1148
- session_id: sessionId
1149
- });
1150
- if (!ok) {
1151
- console.error({
1152
- type: "leaveGame Error",
1153
- status,
1154
- code,
1155
- message,
1156
- traceId: headers[TraceIdField]
1157
- });
1158
- }
1159
- return ok;
1160
- }
1161
- /**
1162
- * 发送验证码
1163
- *
1164
- * @param option 发送验证码参数
1165
- */
1166
- async sendOtp(option) {
1167
- const {
1168
- ok,
1169
- data,
1170
- code,
1171
- status,
1172
- message,
1173
- headers
1174
- } = await this.req.post("send-otp", option, isSendOtpResponse);
1175
- if (!ok || !data) {
1176
- console.error({
1177
- type: "sendOtp Error",
1178
- status,
1179
- code,
1180
- message,
1181
- traceId: headers[TraceIdField]
1182
- });
1183
- throw new Error(`sendOtp: ${message || code || status}`);
1184
- }
1185
- return data;
1186
- }
1187
- /**
1188
- * 验证验证码
1189
- *
1190
- * @param option 验证码验证参数
1191
- */
1192
- async verifyOtp(option) {
1193
- const {
1194
- ok,
1195
- data,
1196
- code,
1197
- status,
1198
- message,
1199
- headers
1200
- } = await this.req.post("verify-otp", option, isVerifyOtpResponse);
1201
- if (!ok || !data) {
1202
- console.error({
1203
- type: "verifyOtp Error",
1204
- status,
1205
- code,
1206
- message,
1207
- traceId: headers[TraceIdField]
1208
- });
1209
- throw new Error(`verifyOtp: ${message || code || status}`);
1210
- }
1211
- return data;
1212
- }
1213
- /**
1214
- * 申请语音审核。
1215
- *
1216
- * 玩家认为语音房间内某些玩家存在语音违规行为时,可提交语音审核申请。调用前提是:游戏已经在世游开启语音审核服务。
1217
- */
1218
- async voiceModerationRequest(option) {
1219
- const {
1220
- ok,
1221
- status,
1222
- code,
1223
- message,
1224
- headers
1225
- } = await this.req.post("voice-moderation-request", option);
1226
- if (!ok) {
1227
- console.error({
1228
- type: "voiceModerationRequest Error",
1229
- status,
1230
- code,
1231
- message,
1232
- traceId: headers[TraceIdField]
1233
- });
1234
- }
1235
- return ok;
1236
- }
1237
- }
921
+ * Combo SDK For Server REST Api
922
+ */
923
+ var ApiClient = class {
924
+ constructor(config) {
925
+ var _config$maxRetry;
926
+ verifyConfig(config);
927
+ const ua = getUserAgent(config.game);
928
+ this.req = NetRequest({
929
+ baseURL: `${config.endpoint.replace(/\/$/, "")}${ApiPrefix}`,
930
+ maxRetry: (_config$maxRetry = config.maxRetry) !== null && _config$maxRetry !== void 0 ? _config$maxRetry : 1,
931
+ retryInterval: config.retryInterval,
932
+ responseRule: {
933
+ ok: { resolve: "body" },
934
+ failed: {
935
+ resolve: "json",
936
+ statusField: "error",
937
+ messageField: "message"
938
+ }
939
+ },
940
+ requestTransformer({ headers, method, url, params, body }) {
941
+ const iURL = new URL(url);
942
+ if (params) {
943
+ if (params instanceof Object) Object.keys(params).forEach((key) => iURL.searchParams.set(key, params[key]));
944
+ }
945
+ headers["User-Agent"] = ua;
946
+ headers[AuthorizationField] = calcAuthorizationHeader({
947
+ game: config.game,
948
+ secret: config.secret,
949
+ endpoint: config.endpoint,
950
+ method,
951
+ url: iURL.toString(),
952
+ data: body || ""
953
+ });
954
+ },
955
+ logHandler: config.logger,
956
+ timeout: config.timeout || 5e3
957
+ });
958
+ }
959
+ /**
960
+ * 创建订单
961
+ */
962
+ async createOrder(option) {
963
+ const { ok, data, code, status, message, headers } = await this.req.post("create-order", option, isCreateOrderResponse);
964
+ if (!ok || !data) {
965
+ console.error({
966
+ type: "createOrder Error",
967
+ status,
968
+ code,
969
+ message,
970
+ traceId: headers[TraceIdField]
971
+ });
972
+ throw new Error(`createOrder: ${message || code || status}`);
973
+ }
974
+ return data;
975
+ }
976
+ /**
977
+ * 通知世游服务端玩家进入游戏世界(上线)
978
+ *
979
+ * 此接口仅用于中宣部防沉迷系统的上下线数据上报
980
+ *
981
+ * @param comboId 聚合用户标识
982
+ * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
983
+ */
984
+ async enterGame(comboId, sessionId) {
985
+ const { ok, status, code, message, headers } = await this.req.post("enter-game", {
986
+ combo_id: comboId,
987
+ session_id: sessionId
988
+ });
989
+ if (!ok) console.error({
990
+ type: "enterGame Error",
991
+ status,
992
+ code,
993
+ message,
994
+ traceId: headers[TraceIdField]
995
+ });
996
+ return ok;
997
+ }
998
+ /**
999
+ * 通知世游服务端玩家离开游戏世界(下线)
1000
+ *
1001
+ * 此接口仅用于中宣部防沉迷系统的上下线数据上报
1002
+ *
1003
+ * @param comboId 聚合用户标识
1004
+ * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
1005
+ */
1006
+ async leaveGame(comboId, sessionId) {
1007
+ const { ok, status, code, message, headers } = await this.req.post("leave-game", {
1008
+ combo_id: comboId,
1009
+ session_id: sessionId
1010
+ });
1011
+ if (!ok) console.error({
1012
+ type: "leaveGame Error",
1013
+ status,
1014
+ code,
1015
+ message,
1016
+ traceId: headers[TraceIdField]
1017
+ });
1018
+ return ok;
1019
+ }
1020
+ /**
1021
+ * 发送验证码
1022
+ *
1023
+ * @param option 发送验证码参数
1024
+ */
1025
+ async sendOtp(option) {
1026
+ const { ok, data, code, status, message, headers } = await this.req.post("send-otp", option, isSendOtpResponse);
1027
+ if (!ok || !data) {
1028
+ console.error({
1029
+ type: "sendOtp Error",
1030
+ status,
1031
+ code,
1032
+ message,
1033
+ traceId: headers[TraceIdField]
1034
+ });
1035
+ throw new Error(`sendOtp: ${message || code || status}`);
1036
+ }
1037
+ return data;
1038
+ }
1039
+ /**
1040
+ * 验证验证码
1041
+ *
1042
+ * @param option 验证码验证参数
1043
+ */
1044
+ async verifyOtp(option) {
1045
+ const { ok, data, code, status, message, headers } = await this.req.post("verify-otp", option, isVerifyOtpResponse);
1046
+ if (!ok || !data) {
1047
+ console.error({
1048
+ type: "verifyOtp Error",
1049
+ status,
1050
+ code,
1051
+ message,
1052
+ traceId: headers[TraceIdField]
1053
+ });
1054
+ throw new Error(`verifyOtp: ${message || code || status}`);
1055
+ }
1056
+ return data;
1057
+ }
1058
+ /**
1059
+ * 申请语音审核。
1060
+ *
1061
+ * 玩家认为语音房间内某些玩家存在语音违规行为时,可提交语音审核申请。调用前提是:游戏已经在世游开启语音审核服务。
1062
+ */
1063
+ async voiceModerationRequest(option) {
1064
+ const { ok, status, code, message, headers } = await this.req.post("voice-moderation-request", option);
1065
+ if (!ok) console.error({
1066
+ type: "voiceModerationRequest Error",
1067
+ status,
1068
+ code,
1069
+ message,
1070
+ traceId: headers[TraceIdField]
1071
+ });
1072
+ return ok;
1073
+ }
1074
+ };
1238
1075
  function isCreateOrderResponse(data) {
1239
- return isObject(data) && ["order_id", "order_token"].every(field => field in data) && "expires_at" in data && typeof data.expires_at === "number";
1076
+ return isObject(data) && ["order_id", "order_token"].every((field) => field in data) && "expires_at" in data && typeof data.expires_at === "number";
1240
1077
  }
1241
- // 目前 OTP 仅支持 sms 通道,mobile 恒为掩码后的手机号字符串,故此处统一按 string 校验。
1242
- // 后续新增 channel 时,需要在此根据 channel 补充 mobile 的关联校验
1243
- // (例如非 sms 通道下 mobile 可能为空),届时可考虑将 channel 传入本守卫。
1244
1078
  function isSendOtpResponse(data) {
1245
- return isObject(data) && "mobile" in data && "otp_ttl" in data && "otp_cooldown" in data && typeof data.mobile === "string" && typeof data.otp_ttl === "number" && typeof data.otp_cooldown === "number";
1079
+ return isObject(data) && "mobile" in data && "otp_ttl" in data && "otp_cooldown" in data && typeof data.mobile === "string" && typeof data.otp_ttl === "number" && typeof data.otp_cooldown === "number";
1246
1080
  }
1247
1081
  function isVerifyOtpResponse(data) {
1248
- return isObject(data) && "valid" in data && typeof data.valid === "boolean";
1082
+ return isObject(data) && "valid" in data && typeof data.valid === "boolean";
1249
1083
  }
1250
-
1084
+ //#endregion
1085
+ //#region src/verify/id.ts
1251
1086
  function isIdentityJwtPayload(payload) {
1252
- return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "device_id" in payload && "external_id" in payload && "external_name" in payload && "reg_time" in payload;
1087
+ return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "device_id" in payload && "external_id" in payload && "external_name" in payload && "reg_time" in payload;
1253
1088
  }
1254
-
1089
+ //#endregion
1090
+ //#region src/verify/ads.ts
1255
1091
  function isAdJwtPayload(payload) {
1256
- return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "placement_id" in payload && "impression_id" in payload;
1092
+ return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "placement_id" in payload && "impression_id" in payload;
1257
1093
  }
1258
-
1094
+ //#endregion
1095
+ //#region src/utils/gcm.ts
1259
1096
  /**
1260
- * decryptAESGCM 使用 AES-256-GCM 解密 base64 编码的密文。
1261
- * 密文格式为 base64(nonce || ciphertext || authTag),其中 nonce 为 12 字节,authTag 为 16 字节。
1262
- */
1097
+ * decryptAESGCM 使用 AES-256-GCM 解密 base64 编码的密文。
1098
+ * 密文格式为 base64(nonce || ciphertext || authTag),其中 nonce 为 12 字节,authTag 为 16 字节。
1099
+ */
1263
1100
  function decryptAESGCM(sk, encoded) {
1264
- let data;
1265
- try {
1266
- data = Buffer.from(encoded, "base64");
1267
- } catch (err) {
1268
- throw new Error(`base64 decode error: ${err}`);
1269
- }
1270
- const key = deriveAESKey(sk);
1271
- const nonceSize = 12;
1272
- const authTagSize = 16;
1273
- if (data.length < nonceSize + authTagSize) {
1274
- throw new Error("ciphertext too short");
1275
- }
1276
- const nonce = data.slice(0, nonceSize);
1277
- // 密文格式: nonce (12) || ciphertext (variable) || authTag (16)
1278
- const authTag = data.slice(data.length - authTagSize);
1279
- const ciphertext = data.slice(nonceSize, data.length - authTagSize);
1280
- const decipher = createDecipheriv("aes-256-gcm", key, nonce);
1281
- decipher.setAuthTag(authTag);
1282
- // Node.js 12 兼容:使用 update 处理所有数据,避免 final() 的问题
1283
- let plaintext;
1284
- try {
1285
- plaintext = decipher.update(ciphertext);
1286
- // Node.js 12 中 GCM 模式下 final() 通常返回空 Buffer,但会验证 authTag
1287
- const finalBuffer = decipher.final();
1288
- if (finalBuffer.length > 0) {
1289
- plaintext = Buffer.concat([plaintext, finalBuffer]);
1290
- }
1291
- } catch (err) {
1292
- throw new Error(`gcm decrypt error: ${err}`);
1293
- }
1294
- return plaintext.toString("utf8");
1101
+ let data;
1102
+ try {
1103
+ data = Buffer.from(encoded, "base64");
1104
+ } catch (err) {
1105
+ throw new Error(`base64 decode error: ${err}`);
1106
+ }
1107
+ const key = deriveAESKey(sk);
1108
+ const nonceSize = 12;
1109
+ const authTagSize = 16;
1110
+ if (data.length < nonceSize + authTagSize) throw new Error("ciphertext too short");
1111
+ const nonce = data.slice(0, nonceSize);
1112
+ const authTag = data.slice(data.length - authTagSize);
1113
+ const ciphertext = data.slice(nonceSize, data.length - authTagSize);
1114
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce);
1115
+ decipher.setAuthTag(authTag);
1116
+ let plaintext;
1117
+ try {
1118
+ plaintext = decipher.update(ciphertext);
1119
+ const finalBuffer = decipher.final();
1120
+ if (finalBuffer.length > 0) plaintext = Buffer.concat([plaintext, finalBuffer]);
1121
+ } catch (err) {
1122
+ throw new Error(`gcm decrypt error: ${err}`);
1123
+ }
1124
+ return plaintext.toString("utf8");
1295
1125
  }
1296
1126
  function deriveAESKey(sk) {
1297
- return createHash("sha256").update(sk).digest();
1127
+ return createHash("sha256").update(sk).digest();
1298
1128
  }
1299
-
1129
+ //#endregion
1130
+ //#region src/verify/index.ts
1300
1131
  const IdentityTokenScope = "auth";
1301
1132
  const AdTokenScope = "ads";
1302
1133
  /**
1303
- * token 验证器
1304
- */
1305
- class TokenVerifier {
1306
- constructor(config) {
1307
- this.privateKey = void 0;
1308
- this.baseOption = void 0;
1309
- verifyConfig(config);
1310
- this.privateKey = config.secret;
1311
- this.baseOption = {
1312
- // https://github.com/auth0/node-jsonwebtoken#algorithms-supported
1313
- algorithms: ["HS256"],
1314
- audience: config.game,
1315
- issuer: config.endpoint,
1316
- ignoreExpiration: false
1317
- };
1318
- }
1319
- /**
1320
- * verifyIdentityToken 对 IdentityToken 进行验证
1321
- *
1322
- * 验证失败会返回 Error 对象
1323
- */
1324
- verifyIdentityToken(token) {
1325
- try {
1326
- const payload = verify(token, this.privateKey, {
1327
- ...this.baseOption,
1328
- complete: false
1329
- });
1330
- if (!payload || !isIdentityJwtPayload(payload) || !payload.sub) {
1331
- return new Error("verifyIdentityToken: token 格式化失败 " + JSON.stringify(payload));
1332
- }
1333
- if (payload.scope !== IdentityTokenScope) {
1334
- return new Error("verifyIdentityToken: 无效的 Scope");
1335
- }
1336
- // spell-checker:ignore AESGCM
1337
- return {
1338
- combo_id: payload.sub,
1339
- idp: payload.idp,
1340
- external_id: payload.external_id,
1341
- external_name: payload.external_name,
1342
- weixin_session_key: payload.weixin_session_key ? decryptAESGCM(this.privateKey, payload.weixin_session_key) : "",
1343
- distro: payload.distro || "",
1344
- variant: payload.variant || "",
1345
- device_id: payload.device_id || "",
1346
- age: payload.age || 0,
1347
- reg_time: payload.reg_time || 0
1348
- };
1349
- } catch (error) {
1350
- return new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1351
- }
1352
- }
1353
- /**
1354
- * verifyAdToken 对 AdToken 进行验证
1355
- *
1356
- * 验证失败会返回 Error 对象
1357
- */
1358
- verifyAdToken(token) {
1359
- try {
1360
- const payload = verify(token, this.privateKey, {
1361
- ...this.baseOption,
1362
- complete: false
1363
- });
1364
- if (!payload || !isAdJwtPayload(payload) || !payload.sub) {
1365
- return new Error("verifyAdToken: token 格式化失败 " + JSON.stringify(payload));
1366
- }
1367
- if (payload.scope !== AdTokenScope) {
1368
- return new Error("verifyAdToken: 无效的 Scope");
1369
- }
1370
- return {
1371
- combo_id: payload.sub,
1372
- placement_id: payload.placement_id,
1373
- impression_id: payload.impression_id
1374
- };
1375
- } catch (error) {
1376
- return new Error(`AdToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1377
- }
1378
- }
1379
- }
1380
-
1134
+ * token 验证器
1135
+ */
1136
+ var TokenVerifier = class {
1137
+ constructor(config) {
1138
+ verifyConfig(config);
1139
+ this.privateKey = config.secret;
1140
+ this.baseOption = {
1141
+ algorithms: ["HS256"],
1142
+ audience: config.game,
1143
+ issuer: config.endpoint,
1144
+ ignoreExpiration: false
1145
+ };
1146
+ }
1147
+ /**
1148
+ * verifyIdentityToken 对 IdentityToken 进行验证
1149
+ *
1150
+ * 验证失败会返回 Error 对象
1151
+ */
1152
+ verifyIdentityToken(token) {
1153
+ try {
1154
+ const payload = jwt.verify(token, this.privateKey, {
1155
+ ...this.baseOption,
1156
+ complete: false
1157
+ });
1158
+ if (!payload || !isIdentityJwtPayload(payload) || !payload.sub) return /* @__PURE__ */ new Error("verifyIdentityToken: token 格式化失败 " + JSON.stringify(payload));
1159
+ if (payload.scope !== IdentityTokenScope) return /* @__PURE__ */ new Error("verifyIdentityToken: 无效的 Scope");
1160
+ return {
1161
+ combo_id: payload.sub,
1162
+ idp: payload.idp,
1163
+ external_id: payload.external_id,
1164
+ external_name: payload.external_name,
1165
+ weixin_session_key: payload.weixin_session_key ? decryptAESGCM(this.privateKey, payload.weixin_session_key) : "",
1166
+ distro: payload.distro || "",
1167
+ variant: payload.variant || "",
1168
+ device_id: payload.device_id || "",
1169
+ age: payload.age || 0,
1170
+ reg_time: payload.reg_time || 0
1171
+ };
1172
+ } catch (error) {
1173
+ return /* @__PURE__ */ new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1174
+ }
1175
+ }
1176
+ /**
1177
+ * verifyAdToken 对 AdToken 进行验证
1178
+ *
1179
+ * 验证失败会返回 Error 对象
1180
+ */
1181
+ verifyAdToken(token) {
1182
+ try {
1183
+ const payload = jwt.verify(token, this.privateKey, {
1184
+ ...this.baseOption,
1185
+ complete: false
1186
+ });
1187
+ if (!payload || !isAdJwtPayload(payload) || !payload.sub) return /* @__PURE__ */ new Error("verifyAdToken: token 格式化失败 " + JSON.stringify(payload));
1188
+ if (payload.scope !== AdTokenScope) return /* @__PURE__ */ new Error("verifyAdToken: 无效的 Scope");
1189
+ return {
1190
+ combo_id: payload.sub,
1191
+ placement_id: payload.placement_id,
1192
+ impression_id: payload.impression_id
1193
+ };
1194
+ } catch (error) {
1195
+ return /* @__PURE__ */ new Error(`AdToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1196
+ }
1197
+ }
1198
+ };
1199
+ //#endregion
1200
+ //#region src/notify/msgShipOrder.ts
1381
1201
  function isShipOrderPayload(data) {
1382
- return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && ("is_sandbox" in data ? typeof data.is_sandbox === "boolean" : true) && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1202
+ return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && ("is_sandbox" in data ? typeof data.is_sandbox === "boolean" : true) && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1383
1203
  }
1384
-
1204
+ //#endregion
1205
+ //#region src/notify/msgRefund.ts
1385
1206
  function isRefundPayload(data) {
1386
- return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1207
+ return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1387
1208
  }
1388
-
1209
+ //#endregion
1210
+ //#region src/notify/types.ts
1211
+ /**
1212
+ * 通知类型枚举
1213
+ */
1214
+ let NotificationType = /* @__PURE__ */ function(NotificationType) {
1215
+ /**
1216
+ * 世游服务端会在订单状态变更为已支付时,向游戏侧推送发货通知。
1217
+ *
1218
+ * 游戏侧需要在收到通知后,根据通知中的订单信息,发货给用户:
1219
+ *
1220
+ * - 如果游戏内发货成功,则应当返回 void 或 Promise<void>
1221
+ * - 如果游戏内发货出现错误,则应当 throw Error。世游服务端会在稍后重试推送发货通知。
1222
+ */
1223
+ NotificationType["ShipOrder"] = "ship_order";
1224
+ /**
1225
+ * 世游服务端会在订单状态发生退款时,向游戏侧推送退款通知。
1226
+ */
1227
+ NotificationType["Refund"] = "refund";
1228
+ return NotificationType;
1229
+ }({});
1389
1230
  /**
1390
- * 消息处理分发配置
1391
- */
1231
+ * 消息处理分发配置
1232
+ */
1392
1233
  const messageDataGuards = {
1393
- ["ship_order" /* NotificationType.ShipOrder */]: {
1394
- guard: isShipOrderPayload,
1395
- message: "ShipOrder Data Format Error"
1396
- },
1397
- ["refund" /* NotificationType.Refund */]: {
1398
- guard: isRefundPayload,
1399
- message: "Refund Data Format Error"
1400
- }
1234
+ [NotificationType.ShipOrder]: {
1235
+ guard: isShipOrderPayload,
1236
+ message: "ShipOrder Data Format Error"
1237
+ },
1238
+ [NotificationType.Refund]: {
1239
+ guard: isRefundPayload,
1240
+ message: "Refund Data Format Error"
1241
+ }
1401
1242
  };
1402
-
1243
+ //#endregion
1244
+ //#region src/notify/index.ts
1403
1245
  function isNotificationRequestBody(data) {
1404
- return isObject(data) && "version" in data && "notification_id" in data && "notification_type" in data && "data" in data && typeof data.version === "string" && typeof data.notification_id === "string" && typeof data.notification_type === "string";
1246
+ return isObject(data) && "version" in data && "notification_id" in data && "notification_type" in data && "data" in data && typeof data.version === "string" && typeof data.notification_id === "string" && typeof data.notification_type === "string";
1405
1247
  }
1406
1248
  /**
1407
- * 获取一个处理函数用于接收 Seayoo Server 推送过来的消息通知
1408
- *
1409
- * 另有 express 和 koa2 版本的处理函数可以使用。
1410
- *
1411
- * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1412
- */
1249
+ * 获取一个处理函数用于接收 Seayoo Server 推送过来的消息通知
1250
+ *
1251
+ * 另有 express 和 koa2 版本的处理函数可以使用。
1252
+ *
1253
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1254
+ */
1413
1255
  function getNotificationHandler(config, handler) {
1414
- verifyConfig(config);
1415
- /**
1416
- * 第三个可选参数 rawBodyString 用于在特定场景 request 为 unreadable 时作为容错兜底方案处理
1417
- *
1418
- * 具体方案可以参考
1419
- *
1420
- * https://cloud.tencent.com/developer/ask/sof/110062928
1421
- */
1422
- return async function (req, res, rawBodyString) {
1423
- if (req.method !== "POST") {
1424
- done(res, 405 /* HttpStatus.MethodNotAllowed */);
1425
- return;
1426
- }
1427
- const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1428
- if (!contentType || !contentType.startsWith("application/json")) {
1429
- done(res, 415 /* HttpStatus.UnsupportedMediaType */);
1430
- return;
1431
- }
1432
- const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
1433
- const body = await readBody(req, rawBodyString);
1434
- if (!body || !checkHttpAuthInfo(`${authString}`, {
1435
- game: config.game,
1436
- secret: config.secret,
1437
- method: "POST",
1438
- // 此处协议不参与计算不需要准确设定
1439
- endpoint: `http://${req.headers.host}`,
1440
- url: req.url || "",
1441
- data: body
1442
- })) {
1443
- done(res, 401 /* HttpStatus.Unauthorized */);
1444
- return;
1445
- }
1446
- const notification = parseJSON(body, isNotificationRequestBody);
1447
- if (!notification) {
1448
- done(res, 400 /* HttpStatus.BadRequest */, `Notification body format error`);
1449
- return;
1450
- }
1451
- const guardCfg = messageDataGuards[notification.notification_type];
1452
- if (!guardCfg) {
1453
- done(res, 400 /* HttpStatus.BadRequest */, `Unknown notification type: ${notification.notification_type}`);
1454
- return;
1455
- }
1456
- if (!guardCfg.guard(notification.data)) {
1457
- done(res, 400 /* HttpStatus.BadRequest */, guardCfg.message);
1458
- return;
1459
- }
1460
- // 所有错误检查完毕,通知游戏处理函数
1461
- try {
1462
- await handler(notification.notification_type, notification.data);
1463
- done(res, 200 /* HttpStatus.OK */, "OK");
1464
- } catch (e) {
1465
- console.error(`notify handler error`, e);
1466
- done(res, 500 /* HttpStatus.InternalServerError */, e instanceof Error ? e.message : String(e));
1467
- }
1468
- };
1256
+ verifyConfig(config);
1257
+ /**
1258
+ * 第三个可选参数 rawBodyString 用于在特定场景 request 为 unreadable 时作为容错兜底方案处理
1259
+ *
1260
+ * 具体方案可以参考
1261
+ *
1262
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1263
+ */
1264
+ return async function(req, res, rawBodyString) {
1265
+ if (req.method !== "POST") {
1266
+ done(res, HttpStatus.MethodNotAllowed);
1267
+ return;
1268
+ }
1269
+ const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1270
+ if (!contentType || !contentType.startsWith("application/json")) {
1271
+ done(res, HttpStatus.UnsupportedMediaType);
1272
+ return;
1273
+ }
1274
+ const authString = req.headers["Authorization"] || req.headers["Authorization".toLowerCase()];
1275
+ const body = await readBody(req, rawBodyString);
1276
+ if (!body || !checkHttpAuthInfo(`${authString}`, {
1277
+ game: config.game,
1278
+ secret: config.secret,
1279
+ method: "POST",
1280
+ endpoint: `http://${req.headers.host}`,
1281
+ url: req.url || "",
1282
+ data: body
1283
+ })) {
1284
+ done(res, HttpStatus.Unauthorized);
1285
+ return;
1286
+ }
1287
+ const notification = parseJSON(body, isNotificationRequestBody);
1288
+ if (!notification) {
1289
+ done(res, HttpStatus.BadRequest, `Notification body format error`);
1290
+ return;
1291
+ }
1292
+ const guardCfg = messageDataGuards[notification.notification_type];
1293
+ if (!guardCfg) {
1294
+ done(res, HttpStatus.BadRequest, `Unknown notification type: ${notification.notification_type}`);
1295
+ return;
1296
+ }
1297
+ if (!guardCfg.guard(notification.data)) {
1298
+ done(res, HttpStatus.BadRequest, guardCfg.message);
1299
+ return;
1300
+ }
1301
+ try {
1302
+ await handler(notification.notification_type, notification.data);
1303
+ done(res, HttpStatus.OK, "OK");
1304
+ } catch (e) {
1305
+ console.error(`notify handler error`, e);
1306
+ done(res, HttpStatus.InternalServerError, e instanceof Error ? e.message : String(e));
1307
+ }
1308
+ };
1469
1309
  }
1470
1310
  /**
1471
- * 获取基于 express 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1472
- *
1473
- * 如需自定义处理,可以使用 getNotificationHandler 方法,
1474
- *
1475
- * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1476
- *
1477
- * 处理方法可以参考
1478
- *
1479
- * https://cloud.tencent.com/developer/ask/sof/110062928
1480
- */
1311
+ * 获取基于 express 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1312
+ *
1313
+ * 如需自定义处理,可以使用 getNotificationHandler 方法,
1314
+ *
1315
+ * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1316
+ *
1317
+ * 处理方法可以参考
1318
+ *
1319
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1320
+ */
1481
1321
  function getNotificationHandlerForExpress(config, handler) {
1482
- const func = getNotificationHandler(config, handler);
1483
- return async function (req, res) {
1484
- await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1485
- };
1322
+ const func = getNotificationHandler(config, handler);
1323
+ return async function(req, res) {
1324
+ await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1325
+ };
1486
1326
  }
1487
1327
  /**
1488
- * 获取基于 express 的中间件用于接收 Seayoo Server 推送过来的消息通知
1489
- *
1490
- * 需要先于 body-parse 等类似插件加载
1491
- */
1328
+ * 获取基于 express 的中间件用于接收 Seayoo Server 推送过来的消息通知
1329
+ *
1330
+ * 需要先于 body-parse 等类似插件加载
1331
+ */
1492
1332
  function getNotificationMiddlewareForExpress(paths, config, handler) {
1493
- const func = getNotificationHandler(config, handler);
1494
- const matchPaths = Array.isArray(paths) ? paths : [paths];
1495
- return async function (req, res, next) {
1496
- if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1497
- await func(req, res);
1498
- return;
1499
- }
1500
- next();
1501
- };
1333
+ const func = getNotificationHandler(config, handler);
1334
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1335
+ return async function(req, res, next) {
1336
+ if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1337
+ await func(req, res);
1338
+ return;
1339
+ }
1340
+ next();
1341
+ };
1502
1342
  }
1503
1343
  /**
1504
- * 获取基于 koa2 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1505
- *
1506
- * 如需自定义处理,可以使用 getNotificationHandler 方法
1507
- *
1508
- * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1509
- */
1344
+ * 获取基于 koa2 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1345
+ *
1346
+ * 如需自定义处理,可以使用 getNotificationHandler 方法
1347
+ *
1348
+ * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1349
+ */
1510
1350
  function getNotificationHandlerForKoa(config, handler) {
1511
- const func = getNotificationHandler(config, handler);
1512
- return async function (ctx) {
1513
- await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1514
- };
1351
+ const func = getNotificationHandler(config, handler);
1352
+ return async function(ctx) {
1353
+ await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1354
+ };
1515
1355
  }
1516
1356
  /**
1517
- * 获取基于 koa2 的中间件用于接收 Seayoo Server 推送过来的消息通知
1518
- *
1519
- * 需要先于 koa-body 等类似插件加载
1520
- */
1357
+ * 获取基于 koa2 的中间件用于接收 Seayoo Server 推送过来的消息通知
1358
+ *
1359
+ * 需要先于 koa-body 等类似插件加载
1360
+ */
1521
1361
  function getNotificationMiddlewareForKoa(paths, config, handler) {
1522
- const func = getNotificationHandler(config, handler);
1523
- const matchPaths = Array.isArray(paths) ? paths : [paths];
1524
- return async function (ctx, next) {
1525
- if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1526
- await func(ctx.req, ctx.res);
1527
- return;
1528
- }
1529
- await next();
1530
- };
1531
- }
1532
-
1362
+ const func = getNotificationHandler(config, handler);
1363
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1364
+ return async function(ctx, next) {
1365
+ if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1366
+ await func(ctx.req, ctx.res);
1367
+ return;
1368
+ }
1369
+ await next();
1370
+ };
1371
+ }
1372
+ //#endregion
1373
+ //#region src/gm/types.ts
1533
1374
  function isGMRequestBody(data) {
1534
- return isObject(data) && "version" in data && "request_id" in data && "command" in data && "args" in data && ("idempotency_key" in data ? typeof data.idempotency_key === "string" : true) && ("origin" in data ? typeof data.origin === "string" : true) && typeof data.request_id === "string" && typeof data.command === "string" && typeof data.args === "object" && data.args !== null;
1375
+ return isObject(data) && "version" in data && "request_id" in data && "command" in data && "args" in data && ("idempotency_key" in data ? typeof data.idempotency_key === "string" : true) && ("origin" in data ? typeof data.origin === "string" : true) && typeof data.request_id === "string" && typeof data.command === "string" && typeof data.args === "object" && data.args !== null;
1535
1376
  }
1536
1377
  function isGMErrorResponse(data) {
1537
- return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1378
+ return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1538
1379
  }
1539
1380
  function isIdempotencyRecord(data) {
1540
- return isObject(data) && "key" in data && "id" in data && "cmd" in data && "args" in data;
1381
+ return isObject(data) && "key" in data && "id" in data && "cmd" in data && "args" in data;
1541
1382
  }
1542
-
1383
+ //#endregion
1384
+ //#region src/gm/utils.ts
1543
1385
  function verifyStoreHelper(storeHelper) {
1544
- if (storeHelper) {
1545
- if (typeof storeHelper !== "object" || !("setXX" in storeHelper) || !("setNX" in storeHelper)) {
1546
- throw new Error("store helper should be { setXX, setNX }");
1547
- }
1548
- if (typeof storeHelper.setNX !== "function" || storeHelper.setNX.length !== 2) {
1549
- throw new Error("store.setNX should be (key, value) => string");
1550
- }
1551
- if (typeof storeHelper.setXX !== "function" || storeHelper.setXX.length !== 2) {
1552
- throw new Error("store.setXX should be (key, value) => void");
1553
- }
1554
- }
1386
+ if (storeHelper) {
1387
+ if (typeof storeHelper !== "object" || !("setXX" in storeHelper) || !("setNX" in storeHelper)) throw new Error("store helper should be { setXX, setNX }");
1388
+ if (typeof storeHelper.setNX !== "function" || storeHelper.setNX.length !== 2) throw new Error("store.setNX should be (key, value) => string");
1389
+ if (typeof storeHelper.setXX !== "function" || storeHelper.setXX.length !== 2) throw new Error("store.setXX should be (key, value) => void");
1390
+ }
1555
1391
  }
1556
1392
  function toString(data) {
1557
- return JSON.stringify(data);
1393
+ return JSON.stringify(data);
1558
1394
  }
1559
1395
  /** 提供基于内存的 store helper,仅供本地调试使用,不支持 ttl 超时功能 */
1560
- class MemoryIdempotencyStore {
1561
- constructor() {
1562
- this.mc = void 0;
1563
- this.mc = {};
1564
- }
1565
- async setNX(key, value) {
1566
- const r = this.mc[key];
1567
- if (!r) {
1568
- this.mc[key] = value;
1569
- return "";
1570
- }
1571
- return r;
1572
- }
1573
- async setXX(key, value) {
1574
- const r = this.mc[key];
1575
- if (r) {
1576
- this.mc[key] = value;
1577
- }
1578
- }
1579
- }
1396
+ var MemoryIdempotencyStore = class {
1397
+ constructor() {
1398
+ this.mc = {};
1399
+ }
1400
+ async setNX(key, value) {
1401
+ const r = this.mc[key];
1402
+ if (!r) {
1403
+ this.mc[key] = value;
1404
+ return "";
1405
+ }
1406
+ return r;
1407
+ }
1408
+ async setXX(key, value) {
1409
+ if (this.mc[key]) this.mc[key] = value;
1410
+ }
1411
+ };
1580
1412
  /**
1581
- * 基于 ioredis 的 store helper,
1582
- *
1583
- * 需要 Redis >= 7.0,见 https://redis.io/docs/latest/commands/set/
1584
- */
1585
- class RedisIdempotencyStore {
1586
- constructor(options) {
1587
- var _options$ttl;
1588
- this.client = void 0;
1589
- this.ttl = void 0;
1590
- this.prefix = void 0;
1591
- this.client = options.client;
1592
- this.ttl = Math.max(24 * 3600, (_options$ttl = options.ttl) != null ? _options$ttl : 0);
1593
- this.prefix = options.prefix || "";
1594
- }
1595
- async setNX(key, value) {
1596
- return (await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "NX", "GET")) || "";
1597
- }
1598
- async setXX(key, value) {
1599
- await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "XX");
1600
- }
1601
- }
1602
-
1413
+ * 基于 ioredis 的 store helper,
1414
+ *
1415
+ * 需要 Redis >= 7.0,见 https://redis.io/docs/latest/commands/set/
1416
+ */
1417
+ var RedisIdempotencyStore = class {
1418
+ constructor(options) {
1419
+ var _options$ttl;
1420
+ this.client = options.client;
1421
+ this.ttl = Math.max(24 * 3600, (_options$ttl = options.ttl) !== null && _options$ttl !== void 0 ? _options$ttl : 0);
1422
+ this.prefix = options.prefix || "";
1423
+ }
1424
+ async setNX(key, value) {
1425
+ return await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "NX", "GET") || "";
1426
+ }
1427
+ async setXX(key, value) {
1428
+ await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "XX");
1429
+ }
1430
+ };
1431
+ //#endregion
1432
+ //#region src/gm/index.ts
1603
1433
  const error2httpStatus = {
1604
- [GMError.InvalidHttpMethod]: 405 /* HttpStatus.MethodNotAllowed */,
1605
- [GMError.InvalidContentType]: 415 /* HttpStatus.UnsupportedMediaType */,
1606
- [GMError.InvalidSignature]: 401 /* HttpStatus.Unauthorized */,
1607
- [GMError.InvalidRequest]: 400 /* HttpStatus.BadRequest */,
1608
- [GMError.InvalidCommand]: 400 /* HttpStatus.BadRequest */,
1609
- [GMError.InvalidArgs]: 400 /* HttpStatus.BadRequest */,
1610
- [GMError.NetworkError]: 500 /* HttpStatus.InternalServerError */,
1611
- [GMError.DatabaseError]: 500 /* HttpStatus.InternalServerError */,
1612
- [GMError.IdempotencyConflict]: 409 /* HttpStatus.Conflict */,
1613
- [GMError.IdempotencyMismatch]: 422 /* HttpStatus.UnprocessableEntity */,
1614
- [GMError.TimeoutError]: 500 /* HttpStatus.InternalServerError */,
1615
- [GMError.MaintenanceError]: 503 /* HttpStatus.ServiceUnavailable */,
1616
- [GMError.ThrottlingError]: 429 /* HttpStatus.TooManyRequests */,
1617
- [GMError.InternalError]: 500 /* HttpStatus.InternalServerError */
1434
+ [GMError.InvalidHttpMethod]: HttpStatus.MethodNotAllowed,
1435
+ [GMError.InvalidContentType]: HttpStatus.UnsupportedMediaType,
1436
+ [GMError.InvalidSignature]: HttpStatus.Unauthorized,
1437
+ [GMError.InvalidRequest]: HttpStatus.BadRequest,
1438
+ [GMError.InvalidCommand]: HttpStatus.BadRequest,
1439
+ [GMError.InvalidArgs]: HttpStatus.BadRequest,
1440
+ [GMError.NetworkError]: HttpStatus.InternalServerError,
1441
+ [GMError.DatabaseError]: HttpStatus.InternalServerError,
1442
+ [GMError.IdempotencyConflict]: HttpStatus.Conflict,
1443
+ [GMError.IdempotencyMismatch]: HttpStatus.UnprocessableEntity,
1444
+ [GMError.TimeoutError]: HttpStatus.InternalServerError,
1445
+ [GMError.MaintenanceError]: HttpStatus.ServiceUnavailable,
1446
+ [GMError.ThrottlingError]: HttpStatus.TooManyRequests,
1447
+ [GMError.InternalError]: HttpStatus.InternalServerError
1618
1448
  };
1619
1449
  /**
1620
- * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
1621
- *
1622
- * 另有 express 和 koa2 版本的处理函数可以使用。
1623
- *
1624
- * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1625
- */
1450
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
1451
+ *
1452
+ * 另有 express 和 koa2 版本的处理函数可以使用。
1453
+ *
1454
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1455
+ */
1626
1456
  function getGMCommandHandler(config, handler, storeHelper) {
1627
- verifyConfigWithoutEndpoint(config);
1628
- verifyStoreHelper(storeHelper);
1629
- return async function (req, res, rawBodyString) {
1630
- if (req.method !== "POST") {
1631
- responseError(res, 405 /* HttpStatus.MethodNotAllowed */, GMError.InvalidHttpMethod, `Expecting POST, got ${req.method}`);
1632
- return;
1633
- }
1634
- const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1635
- if (!contentType || !contentType.startsWith("application/json")) {
1636
- responseError(res, 415 /* HttpStatus.UnsupportedMediaType */, GMError.InvalidContentType, `Expecting application/json, got ${contentType}`);
1637
- return;
1638
- }
1639
- const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
1640
- const body = await readBody(req, rawBodyString);
1641
- if (!body || !checkHttpAuthInfo(`${authString}`, {
1642
- game: config.game,
1643
- secret: config.secret,
1644
- method: "POST",
1645
- // 此处协议不参与计算不需要准确设定
1646
- endpoint: `http://${req.headers.host}`,
1647
- url: req.url || "",
1648
- data: body
1649
- })) {
1650
- responseError(res, 401 /* HttpStatus.Unauthorized */, GMError.InvalidSignature, "Signature failed");
1651
- return;
1652
- }
1653
- const gmRequest = parseJSON(body, isGMRequestBody);
1654
- if (!gmRequest) {
1655
- responseError(res, 400 /* HttpStatus.BadRequest */, GMError.InvalidRequest, `GM request body format error`);
1656
- return;
1657
- }
1658
- // 处理幂等key
1659
- const currentRecord = {
1660
- nonce: genNonceString(),
1661
- key: gmRequest.idempotency_key || "",
1662
- id: gmRequest.request_id,
1663
- cmd: gmRequest.command,
1664
- args: toString(gmRequest.args)
1665
- };
1666
- let oldResponse = null;
1667
- if (storeHelper && gmRequest.idempotency_key) {
1668
- const oldRecordStr = await storeHelper.setNX(gmRequest.idempotency_key, toString(currentRecord)).catch(e => e instanceof Error ? e : new Error(String(e)));
1669
- if (oldRecordStr instanceof Error) {
1670
- console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) setNX error`, oldRecordStr);
1671
- responseError(res, 500 /* HttpStatus.InternalServerError */, GMError.InternalError, oldRecordStr.message);
1672
- return;
1673
- }
1674
- const oldRecord = oldRecordStr ? parseJSON(oldRecordStr, isIdempotencyRecord) : null;
1675
- if (!oldRecord && oldRecordStr) {
1676
- console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) parse old idempotency record failed: ${oldRecordStr}`);
1677
- responseError(res, 500 /* HttpStatus.InternalServerError */, GMError.InternalError, "parse old idempotency record failed");
1678
- return;
1679
- }
1680
- // spell-checker:disable
1681
- // fix spell error
1682
- if (oldRecord && "noce" in oldRecord) {
1683
- oldRecord.nonce = oldRecord.noce + "";
1684
- }
1685
- // spell-checker:enable
1686
- // 检查是否为首次请求
1687
- const isFirstRequest = oldRecordStr === "" || (oldRecord == null ? void 0 : oldRecord.nonce) === currentRecord.nonce;
1688
- if (!isFirstRequest && oldRecord) {
1689
- if (!oldRecord.resp) {
1690
- responseError(res, error2httpStatus[GMError.IdempotencyConflict], GMError.IdempotencyConflict, "previous request is not completed");
1691
- return;
1692
- }
1693
- if (oldRecord.cmd !== gmRequest.command) {
1694
- responseError(res, error2httpStatus[GMError.IdempotencyMismatch], GMError.IdempotencyMismatch, `cmd mismatch, expecting ${oldRecord.cmd}, got ${gmRequest.command}`);
1695
- return;
1696
- }
1697
- if (oldRecord.args !== currentRecord.args) {
1698
- responseError(res, error2httpStatus[GMError.IdempotencyMismatch], GMError.IdempotencyMismatch, `args mismatch, expecting ${oldRecord.args}, got ${currentRecord.args}`);
1699
- return;
1700
- }
1701
- oldResponse = oldRecord.resp;
1702
- }
1703
- }
1704
- // 所有错误检查完毕,通知游戏处理函数
1705
- try {
1706
- const result = oldResponse || (await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version, gmRequest.origin || ""));
1707
- // 记录handler返回的结果以备下次检查使用,setXX出现错误也不再中断请求
1708
- if (storeHelper && gmRequest.idempotency_key) {
1709
- currentRecord.resp = result;
1710
- storeHelper.setXX(gmRequest.idempotency_key, toString(currentRecord)).catch(err => {
1711
- console.error("failed to setXX idempotency record", err, currentRecord);
1712
- });
1713
- }
1714
- // 游戏主动抛错不打印日志信息
1715
- if (result instanceof Error) {
1716
- responseError(res, 500 /* HttpStatus.InternalServerError */, GMError.InternalError, result.message);
1717
- return;
1718
- }
1719
- if (isGMErrorResponse(result)) {
1720
- responseError(res, error2httpStatus[result.error] || 500 /* HttpStatus.InternalServerError */, result.error || GMError.InternalError, result.message);
1721
- return;
1722
- }
1723
- // 对游戏处理函数进一步兼容处理,允许返回一个预定义的错误码
1724
- // 但此逻辑不作为公开 api,仅作为内容兼容处理
1725
- if (typeof result === "string" && result in error2httpStatus) {
1726
- responseError(res, error2httpStatus[result], result, result);
1727
- return;
1728
- }
1729
- // 如果 result 没有结果则进行提示然后继续
1730
- if (!result) {
1731
- console.warn(`gm command "${gmRequest.command}" should give back some data`);
1732
- }
1733
- responseJson(res, result != null ? result : {});
1734
- } catch (e) {
1735
- console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) exec error`, e);
1736
- responseError(res, 500 /* HttpStatus.InternalServerError */, GMError.InternalError, e instanceof Error ? e.message : String(e));
1737
- }
1738
- };
1457
+ verifyConfigWithoutEndpoint(config);
1458
+ verifyStoreHelper(storeHelper);
1459
+ return async function(req, res, rawBodyString) {
1460
+ if (req.method !== "POST") {
1461
+ responseError(res, HttpStatus.MethodNotAllowed, GMError.InvalidHttpMethod, `Expecting POST, got ${req.method}`);
1462
+ return;
1463
+ }
1464
+ const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1465
+ if (!contentType || !contentType.startsWith("application/json")) {
1466
+ responseError(res, HttpStatus.UnsupportedMediaType, GMError.InvalidContentType, `Expecting application/json, got ${contentType}`);
1467
+ return;
1468
+ }
1469
+ const authString = req.headers["Authorization"] || req.headers["Authorization".toLowerCase()];
1470
+ const body = await readBody(req, rawBodyString);
1471
+ if (!body || !checkHttpAuthInfo(`${authString}`, {
1472
+ game: config.game,
1473
+ secret: config.secret,
1474
+ method: "POST",
1475
+ endpoint: `http://${req.headers.host}`,
1476
+ url: req.url || "",
1477
+ data: body
1478
+ })) {
1479
+ responseError(res, HttpStatus.Unauthorized, GMError.InvalidSignature, "Signature failed");
1480
+ return;
1481
+ }
1482
+ const gmRequest = parseJSON(body, isGMRequestBody);
1483
+ if (!gmRequest) {
1484
+ responseError(res, HttpStatus.BadRequest, GMError.InvalidRequest, `GM request body format error`);
1485
+ return;
1486
+ }
1487
+ const currentRecord = {
1488
+ nonce: genNonceString(),
1489
+ key: gmRequest.idempotency_key || "",
1490
+ id: gmRequest.request_id,
1491
+ cmd: gmRequest.command,
1492
+ args: toString(gmRequest.args)
1493
+ };
1494
+ let oldResponse = null;
1495
+ if (storeHelper && gmRequest.idempotency_key) {
1496
+ const oldRecordStr = await storeHelper.setNX(gmRequest.idempotency_key, toString(currentRecord)).catch((e) => e instanceof Error ? e : new Error(String(e)));
1497
+ if (oldRecordStr instanceof Error) {
1498
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) setNX error`, oldRecordStr);
1499
+ responseError(res, HttpStatus.InternalServerError, GMError.InternalError, oldRecordStr.message);
1500
+ return;
1501
+ }
1502
+ const oldRecord = oldRecordStr ? parseJSON(oldRecordStr, isIdempotencyRecord) : null;
1503
+ if (!oldRecord && oldRecordStr) {
1504
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) parse old idempotency record failed: ${oldRecordStr}`);
1505
+ responseError(res, HttpStatus.InternalServerError, GMError.InternalError, "parse old idempotency record failed");
1506
+ return;
1507
+ }
1508
+ if (oldRecord && "noce" in oldRecord) oldRecord.nonce = oldRecord.noce + "";
1509
+ if (!(oldRecordStr === "" || (oldRecord === null || oldRecord === void 0 ? void 0 : oldRecord.nonce) === currentRecord.nonce) && oldRecord) {
1510
+ if (!oldRecord.resp) {
1511
+ responseError(res, error2httpStatus[GMError.IdempotencyConflict], GMError.IdempotencyConflict, "previous request is not completed");
1512
+ return;
1513
+ }
1514
+ if (oldRecord.cmd !== gmRequest.command) {
1515
+ responseError(res, error2httpStatus[GMError.IdempotencyMismatch], GMError.IdempotencyMismatch, `cmd mismatch, expecting ${oldRecord.cmd}, got ${gmRequest.command}`);
1516
+ return;
1517
+ }
1518
+ if (oldRecord.args !== currentRecord.args) {
1519
+ responseError(res, error2httpStatus[GMError.IdempotencyMismatch], GMError.IdempotencyMismatch, `args mismatch, expecting ${oldRecord.args}, got ${currentRecord.args}`);
1520
+ return;
1521
+ }
1522
+ oldResponse = oldRecord.resp;
1523
+ }
1524
+ }
1525
+ try {
1526
+ const result = oldResponse || await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version, gmRequest.origin || "");
1527
+ if (storeHelper && gmRequest.idempotency_key) {
1528
+ currentRecord.resp = result;
1529
+ storeHelper.setXX(gmRequest.idempotency_key, toString(currentRecord)).catch((err) => {
1530
+ console.error("failed to setXX idempotency record", err, currentRecord);
1531
+ });
1532
+ }
1533
+ if (result instanceof Error) {
1534
+ responseError(res, HttpStatus.InternalServerError, GMError.InternalError, result.message);
1535
+ return;
1536
+ }
1537
+ if (isGMErrorResponse(result)) {
1538
+ responseError(res, error2httpStatus[result.error] || HttpStatus.InternalServerError, result.error || GMError.InternalError, result.message);
1539
+ return;
1540
+ }
1541
+ if (typeof result === "string" && result in error2httpStatus) {
1542
+ responseError(res, error2httpStatus[result], result, result);
1543
+ return;
1544
+ }
1545
+ if (!result) console.warn(`gm command "${gmRequest.command}" should give back some data`);
1546
+ responseJson(res, result !== null && result !== void 0 ? result : {});
1547
+ } catch (e) {
1548
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) exec error`, e);
1549
+ responseError(res, HttpStatus.InternalServerError, GMError.InternalError, e instanceof Error ? e.message : String(e));
1550
+ }
1551
+ };
1739
1552
  }
1740
1553
  /**
1741
- * 获取基于 express 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1742
- *
1743
- * 如需自定义处理,可以使用 getGMCommandHandler 方法,
1744
- *
1745
- * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1746
- *
1747
- * 处理方法可以参考
1748
- *
1749
- * https://cloud.tencent.com/developer/ask/sof/110062928
1750
- */
1554
+ * 获取基于 express 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1555
+ *
1556
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法,
1557
+ *
1558
+ * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1559
+ *
1560
+ * 处理方法可以参考
1561
+ *
1562
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1563
+ */
1751
1564
  function getGMHandlerForExpress(config, handler, storeHelper) {
1752
- const func = getGMCommandHandler(config, handler, storeHelper);
1753
- return async function (req, res) {
1754
- await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1755
- };
1565
+ const func = getGMCommandHandler(config, handler, storeHelper);
1566
+ return async function(req, res) {
1567
+ await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1568
+ };
1756
1569
  }
1757
1570
  /**
1758
- * 获取基于 express 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1759
- *
1760
- * 需要先于 body-parse 等类似插件加载
1761
- */
1571
+ * 获取基于 express 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1572
+ *
1573
+ * 需要先于 body-parse 等类似插件加载
1574
+ */
1762
1575
  function getGMMiddlewareForExpress(paths, config, handler, storeHelper) {
1763
- const func = getGMCommandHandler(config, handler, storeHelper);
1764
- const matchPaths = Array.isArray(paths) ? paths : [paths];
1765
- return async function (req, res, next) {
1766
- if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1767
- await func(req, res);
1768
- return;
1769
- }
1770
- next();
1771
- };
1576
+ const func = getGMCommandHandler(config, handler, storeHelper);
1577
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1578
+ return async function(req, res, next) {
1579
+ if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1580
+ await func(req, res);
1581
+ return;
1582
+ }
1583
+ next();
1584
+ };
1772
1585
  }
1773
1586
  /**
1774
- * 获取基于 koa2 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1775
- *
1776
- * 如需自定义处理,可以使用 getGMCommandHandler 方法
1777
- *
1778
- * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1779
- */
1587
+ * 获取基于 koa2 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1588
+ *
1589
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法
1590
+ *
1591
+ * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1592
+ */
1780
1593
  function getGMHandlerForKoa(config, handler, storeHelper) {
1781
- const func = getGMCommandHandler(config, handler, storeHelper);
1782
- return async function (ctx) {
1783
- await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1784
- };
1594
+ const func = getGMCommandHandler(config, handler, storeHelper);
1595
+ return async function(ctx) {
1596
+ await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1597
+ };
1785
1598
  }
1786
1599
  /**
1787
- * 获取基于 koa2 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1788
- *
1789
- * 需要先于 koa-body 等类似插件加载
1790
- */
1600
+ * 获取基于 koa2 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1601
+ *
1602
+ * 需要先于 koa-body 等类似插件加载
1603
+ */
1791
1604
  function getGMMiddlewareForKoa(paths, config, handler, storeHelper) {
1792
- const func = getGMCommandHandler(config, handler, storeHelper);
1793
- const matchPaths = Array.isArray(paths) ? paths : [paths];
1794
- return async function (ctx, next) {
1795
- if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1796
- await func(ctx.req, ctx.res);
1797
- return;
1798
- }
1799
- await next();
1800
- };
1801
- }
1802
-
1803
- export { ApiClient, Endpoint, GMError, IdP, MemoryIdempotencyStore, Platform, RedisIdempotencyStore, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
1605
+ const func = getGMCommandHandler(config, handler, storeHelper);
1606
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1607
+ return async function(ctx, next) {
1608
+ if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1609
+ await func(ctx.req, ctx.res);
1610
+ return;
1611
+ }
1612
+ await next();
1613
+ };
1614
+ }
1615
+ //#endregion
1616
+ export { ApiClient, Endpoint, GMError, IdP, MemoryIdempotencyStore, NotificationType, Platform, RedisIdempotencyStore, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };