@seayoo-io/combo-sdk-node 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1264 @@
1
+ var node_os = require('node:os');
2
+ var http = require('node:http');
3
+ var https = require('node:https');
4
+ var crypto = require('crypto');
5
+ var jsonwebtoken = require('jsonwebtoken');
6
+
7
+ function _interopNamespace(e) {
8
+ if (e && e.__esModule) return e;
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n["default"] = e;
22
+ return n;
23
+ }
24
+
25
+ var http__namespace = /*#__PURE__*/_interopNamespace(http);
26
+ var https__namespace = /*#__PURE__*/_interopNamespace(https);
27
+
28
+ /** SDK 名称 */
29
+ const SDKName = "combo-sdk-node";
30
+ /** SDK 版本,在编译前会被动态替换 */
31
+ const SDKVersion = "0.1.0";
32
+ /**
33
+ * 世游支持的服务端点列表
34
+ */
35
+ exports.Endpoint = void 0;
36
+ (function (Endpoint) {
37
+ /** 中国大陆 API 端点,用于国内发行 */
38
+ Endpoint["China"] = "https://api.seayoo.com";
39
+ /** 全球的 API 端点,用于海外发行 */
40
+ Endpoint["Global"] = "https://api.seayoo.io";
41
+ })(exports.Endpoint || (exports.Endpoint = {}));
42
+ /** 支持的系统平台 */
43
+ exports.Platform = void 0;
44
+ (function (Platform) {
45
+ /** 安卓平台,包括华为鸿蒙系统、小米澎湃 OS 等基于 Android 的操作系统 */
46
+ Platform["Android"] = "android";
47
+ /** 苹果的 iOS 和 iPadOS */
48
+ Platform["iOS"] = "ios";
49
+ /** Windows (PC) 桌面平台 */
50
+ Platform["Windows"] = "windows";
51
+ /** macOS 桌面平台 */
52
+ Platform["macOS"] = "macos";
53
+ /** 微信小游戏 */
54
+ Platform["Weixin"] = "weixin";
55
+ })(exports.Platform || (exports.Platform = {}));
56
+ /** 支持的登录提供方 */
57
+ exports.IdP = void 0;
58
+ (function (IdP) {
59
+ /** 设备登录(游客) */
60
+ IdP["Device"] = "device";
61
+ /** 世游通行证 */
62
+ IdP["Seayoo"] = "seayoo";
63
+ /** Sign-in with Apple */
64
+ IdP["Apple"] = "apple";
65
+ /** Google Account */
66
+ IdP["Google"] = "google";
67
+ /** Facebook Login */
68
+ IdP["Facebook"] = "facebook";
69
+ /** 小米账号 */
70
+ IdP["Xiaomi"] = "xiaomi";
71
+ /** 微信登录 */
72
+ IdP["Weixin"] = "weixin";
73
+ })(exports.IdP || (exports.IdP = {}));
74
+
75
+ function getUserAgent(game) {
76
+ return `${SDKName}/${SDKVersion} game/${game} node/${process.version} os/${node_os.platform()} arch/${node_os.arch()}`;
77
+ }
78
+
79
+ const urlReg = /^(?:https?:)?\/\/.+/i;
80
+ const urlReg2 = /^https?:\/\//i;
81
+ const objReg = /^\{[\d\D]*\}$/;
82
+ const arrReg = /^\[[\d\D]*\]$/;
83
+ /**
84
+ * 暂停一段时间
85
+ * @param {number} ms 暂停的毫秒数
86
+ */
87
+ function sleep(ms) {
88
+ return new Promise(resolve => setTimeout(resolve, ms));
89
+ }
90
+ /**
91
+ * 空函数,异步空函数为 asyncNoop
92
+ */
93
+ function noop() {}
94
+ /**
95
+ * 检查是否为空值 null / undefined
96
+ */
97
+ function isEmpty(data) {
98
+ return data === null || data === undefined;
99
+ }
100
+ /**
101
+ * 检查是否为 object(非 null / array)
102
+ */
103
+ function isObject(data) {
104
+ return data !== null && typeof data === "object" && !Array.isArray(data);
105
+ }
106
+ /**
107
+ * 检测是否为 String Record
108
+ */
109
+ function isStringRecord(data) {
110
+ return isObject(data) && Object.keys(data).every(key => typeof key === "string");
111
+ }
112
+ /**
113
+ * 检查一个url地址是否以 http/https 开头,如果第二个参数传递 true,则自适应协议(//....)也被认为是完整 url
114
+ */
115
+ function isFullURL(url, ignoreProtocal = false) {
116
+ return ignoreProtocal ? urlReg.test(url) : urlReg2.test(url);
117
+ }
118
+ /**
119
+ * 检测文本是否有可能转化为 object 或 array,注意,检测通过也未必能被正确格式化为 json
120
+ */
121
+ function isJsonLike(text) {
122
+ return objReg.test(text) || arrReg.test(text);
123
+ }
124
+ /**
125
+ * 基于 baseURL 计算完整的 url 信息,仅可在浏览器环境使用
126
+ * @param url 要转化的 url,如果以 https: 或 http: 开头则直接返回
127
+ * @param baseURL 可选 baseURL
128
+ */
129
+ function getFullURL(url, baseURL = "") {
130
+ if (!baseURL || isFullURL(url, true)) {
131
+ return fillUrl(url);
132
+ }
133
+ return (fillUrl(baseURL) + "/" + url).replace(/(?<!:)\/{2,}/g, "/");
134
+ }
135
+ /**
136
+ * 给 url 添加完整域名和协议,仅可在浏览器环境使用
137
+ * @param url 要检查的 url,如果是自适应协议 //... 则会添加当前页面的协议信息,否则添加域名和协议信息
138
+ */
139
+ function fillUrl(url) {
140
+ return isFullURL(url, true) ? url.startsWith("http") ? url : location.protocol + url : location.origin + "/" + url.replace(/^\/+/, "");
141
+ }
142
+ function parseJSON(str, typeGuard) {
143
+ try {
144
+ const data = JSON.parse(str);
145
+ if (typeGuard) {
146
+ return typeGuard(data) ? data : null;
147
+ }
148
+ return data;
149
+ } catch (e) {
150
+ return null;
151
+ }
152
+ }
153
+
154
+ function getTypeGuard(typeGuard, defaultMessage = "数据未能正确识别") {
155
+ if (typeof typeGuard === "function") {
156
+ return {
157
+ guard: typeGuard,
158
+ message: defaultMessage
159
+ };
160
+ }
161
+ return {
162
+ guard: typeGuard.guard,
163
+ message: typeGuard.message || defaultMessage
164
+ };
165
+ }
166
+
167
+ /**
168
+ * 校验通用配置,如果有错误,则直接 throw Error
169
+ */
170
+ function verifyConfig(config) {
171
+ if (!isObject(config)) {
172
+ throw Error("Config Missing");
173
+ }
174
+ if (!isFullURL(config.endpoint)) {
175
+ throw Error(`Config.endpoint Error, Should be url, Preset Values: ${"https://api.seayoo.com" /* Endpoint.China */}, ${"https://api.seayoo.io" /* Endpoint.Global */}}`);
176
+ }
177
+ if (!config.game) {
178
+ throw Error(`Config.game Error, Missing Required GameId`);
179
+ }
180
+ if (!config.secret) {
181
+ throw Error(`Config.secret Error, Missing Required Secret`);
182
+ }
183
+ if (!config.secret.startsWith("sk_")) {
184
+ throw Error(`Config.secret Error, Should be Start With sk_`);
185
+ }
186
+ }
187
+
188
+ const AuthorizationField = "Authorization";
189
+ const MaxTimeDiff = 5 * 60 * 1000;
190
+ const EmptyStringSha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
191
+ const timestampReg = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;
192
+ // 签名方法定义,给未来扩展新签名方法留出空间
193
+ const SigningDefinitions = {
194
+ HS256: {
195
+ prefix: "SEAYOO-HMAC-SHA256",
196
+ sign({
197
+ game,
198
+ secret,
199
+ endpoint,
200
+ method,
201
+ url,
202
+ data,
203
+ timestamp
204
+ }, onlySignature = false) {
205
+ const payloadHash = !data ? EmptyStringSha256 : sha256(convertBodyData(data));
206
+ const ts = timestamp || getTimestamp();
207
+ const fullURL = url.startsWith("http") ? new URL(url) : new URL(url, endpoint);
208
+ const uri = fullURL.pathname + fullURL.search;
209
+ const signature = hS256(secret, [this.prefix, method.toUpperCase(), uri, ts, payloadHash].join("\n"));
210
+ return onlySignature ? signature : `${this.prefix} Game=${game},Timestamp=${ts},Signature=${signature}`;
211
+ },
212
+ verify(authString, option) {
213
+ const info = parseRawAuthHeader(authString, this.prefix);
214
+ if (!info) {
215
+ return false;
216
+ }
217
+ const game = "Game" in info ? info.Game : null;
218
+ const timestamp = "Timestamp" in info ? info.Timestamp : null;
219
+ const signature = "Signature" in info ? info.Signature : null;
220
+ if (!game || !signature || !timestamp || option.game && option.game !== game) {
221
+ return false;
222
+ }
223
+ const ts = parseTimestamp(timestamp);
224
+ const now = Date.now();
225
+ if (!ts || ts < now - MaxTimeDiff || ts > now + MaxTimeDiff) {
226
+ return false;
227
+ }
228
+ return signature === this.sign({
229
+ ...option,
230
+ game,
231
+ timestamp
232
+ }, true);
233
+ }
234
+ }
235
+ };
236
+ /**
237
+ * 格式化 AuthorizationHeader
238
+ */
239
+ function parseAuthorizationHeader(authString, version = "HS256") {
240
+ if (!version || !SigningDefinitions[version]) {
241
+ console.error({
242
+ type: "parseAuthorizationHeader Error",
243
+ message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
244
+ });
245
+ return null;
246
+ }
247
+ return parseRawAuthHeader(authString, SigningDefinitions[version].prefix);
248
+ }
249
+ /**
250
+ * 获取请求签名值,默认签名方法是 HS256
251
+ */
252
+ function calcAuthorizationHeader(option, onlySignature = false, version = "HS256") {
253
+ if (!version || !SigningDefinitions[version]) {
254
+ console.error({
255
+ type: "calcAuthorizationHeader Error",
256
+ message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
257
+ });
258
+ return "ErrorSigningVersion";
259
+ }
260
+ return SigningDefinitions[version].sign(option, onlySignature);
261
+ }
262
+ /**
263
+ * 检查 http auth 信息是否正确
264
+ */
265
+ function checkHttpAuthInfo(authString, option) {
266
+ if (!authString) {
267
+ return false;
268
+ }
269
+ const cfgs = Object.values(SigningDefinitions);
270
+ for (const cfg of cfgs) {
271
+ if (authString.startsWith(cfg.prefix + " ")) {
272
+ return cfg.verify(authString, option);
273
+ }
274
+ }
275
+ return false;
276
+ }
277
+ function getTimestamp() {
278
+ const d = new Date();
279
+ return d.toISOString().replace(/\.\d+Z$/, "Z").replace(/[-:]/g, "");
280
+ }
281
+ function parseTimestamp(ts) {
282
+ const info = ts.match(timestampReg);
283
+ if (!info) {
284
+ return null;
285
+ }
286
+ return Date.UTC(+info[1], +info[2] - 1, +info[3], +info[4], +info[5], +info[6]);
287
+ }
288
+ function sha256(data) {
289
+ return crypto.createHash("sha256").update(data).digest("hex").toLowerCase();
290
+ }
291
+ function hS256(secret, data) {
292
+ return crypto.createHmac("sha256", secret).update(data).digest("hex").toLowerCase();
293
+ }
294
+ function convertBodyData(body) {
295
+ if (typeof body === "string") {
296
+ return body;
297
+ }
298
+ // TODO
299
+ return body.toString();
300
+ }
301
+ function parseRawAuthHeader(authString, prefix) {
302
+ if (!authString || !authString.startsWith(prefix + " ")) {
303
+ return null;
304
+ }
305
+ return Object.fromEntries(authString.substring(prefix.length + 1).split(",").map(kvs => {
306
+ const kv = kvs.split("=");
307
+ if (kv.length !== 2) {
308
+ return null;
309
+ }
310
+ const key = kv[0].trim();
311
+ const value = getValue(kv[1]);
312
+ if (!key || !value) {
313
+ return null;
314
+ }
315
+ return [key, value];
316
+ }).filter(v => v !== null));
317
+ }
318
+ function getValue(value) {
319
+ const v = value.trim();
320
+ return /^".+"$/.test(v) ? value.replace(/^"|"$/g, "") : v;
321
+ }
322
+
323
+ async function readBody(req, backup) {
324
+ const body = [];
325
+ if (!req.readable) {
326
+ backup || console.error({
327
+ type: "RequestUnReadable",
328
+ url: req.url,
329
+ methe: req.method,
330
+ message: "Cannot read body, stream not readable"
331
+ });
332
+ return backup || "";
333
+ }
334
+ return new Promise((resolve, reject) => {
335
+ req.on("error", reject);
336
+ req.on("data", chunk => body.push(chunk));
337
+ req.on("end", () => {
338
+ resolve(Buffer.concat(body).toString("utf-8"));
339
+ });
340
+ });
341
+ }
342
+ async function done(res, statusCode, message) {
343
+ res.statusCode = statusCode;
344
+ if (statusCode !== 204) {
345
+ res.write(message || "");
346
+ }
347
+ res.end();
348
+ }
349
+
350
+ const defaultDataField = "data";
351
+ const defaultMessageField = "message";
352
+ /**
353
+ * 分析响应内容中的错误信息和数据
354
+ */
355
+ function analyseResponse(status, statusText, responseText, globalRule, rule) {
356
+ const responseRule = rule || globalRule;
357
+ return statusOK(status) ? getResponseOKInfo(responseRule.ok || globalRule.ok, status, statusText, responseText) : getReponseFailedInfo(responseRule.failed || globalRule.failed, statusText, responseText);
358
+ }
359
+ function getReponseFailedInfo(rule, statusText, responseText) {
360
+ const r = rule || {
361
+ resolve: "json",
362
+ messageField: defaultMessageField
363
+ };
364
+ const result = {
365
+ ok: false,
366
+ code: statusText,
367
+ message: responseText,
368
+ data: null
369
+ };
370
+ switch (r.resolve) {
371
+ case "body":
372
+ result.message = formatPresetBody(responseText) || responseText;
373
+ break;
374
+ case "json":
375
+ const {
376
+ code,
377
+ message
378
+ } = formatJsonBody(responseText, r.statusField, r.messageField);
379
+ result.code = code || statusText;
380
+ result.message = formatPresetBody(responseText) || message;
381
+ break;
382
+ }
383
+ return result;
384
+ }
385
+ function formatJsonBody(body, statusField, msgField = defaultMessageField) {
386
+ if (!isJsonLike(body)) {
387
+ return {
388
+ message: ""
389
+ };
390
+ }
391
+ const json = parseJSON(body);
392
+ if (!json || !isStringRecord(json)) {
393
+ return {
394
+ message: body
395
+ };
396
+ }
397
+ return {
398
+ code: statusField ? readMessageFrom(json, statusField) : "",
399
+ message: readMessageFrom(json, msgField) || body
400
+ };
401
+ }
402
+ function readMessageFrom(json, field) {
403
+ const fields = Array.isArray(field) ? field : [field];
404
+ for (const field of fields) {
405
+ if (field in json) {
406
+ return convert2str(json[field]);
407
+ }
408
+ }
409
+ return "";
410
+ }
411
+ function convert2str(data) {
412
+ if (!data) {
413
+ return "";
414
+ }
415
+ if (typeof data === "string") {
416
+ return data;
417
+ }
418
+ return JSON.stringify(data);
419
+ }
420
+ const htmlReg = /<title>([^<]+)<\/title>/i;
421
+ const xmlReg = /<message>([^<]+)<\/message>/i;
422
+ function formatPresetBody(str) {
423
+ const htmlMatch = str.match(htmlReg);
424
+ if (htmlMatch) {
425
+ return htmlMatch[1];
426
+ }
427
+ const xmlMatch = str.match(xmlReg);
428
+ if (xmlMatch) {
429
+ return xmlMatch[1];
430
+ }
431
+ return "";
432
+ }
433
+ function getResponseOKInfo(rule, status, statusText, responseText) {
434
+ const r = rule || {
435
+ resolve: "body"
436
+ };
437
+ const result = {
438
+ ok: true,
439
+ code: statusText,
440
+ message: "",
441
+ data: null
442
+ };
443
+ // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status#%E6%88%90%E5%8A%9F%E5%93%8D%E5%BA%94
444
+ if (status === 202 || status === 204 || !responseText) {
445
+ return result;
446
+ }
447
+ // 解析策略为 body 则直接将 body 当作响应数据
448
+ if (r.resolve === "body") {
449
+ result.data = isJsonLike(responseText) ? parseJSON(responseText) : responseText;
450
+ return result;
451
+ }
452
+ // 否则解析策略为 json,从 object json 中查找数据和消息
453
+ const response = parseJSON(responseText);
454
+ if (!response || !isStringRecord(response)) {
455
+ result.ok = false;
456
+ result.code = "ResponseFormatError";
457
+ result.message = "响应内容无法格式化为 Object";
458
+ return result;
459
+ }
460
+ const statusField = r.statusField;
461
+ const statusOKValue = r.statusOKValue || "";
462
+ const dataField = r.dataField || defaultDataField;
463
+ const messageField = r.messageField || defaultMessageField;
464
+ const ignoreMessage = r.ignoreMessage || "";
465
+ if (statusField && !(statusField in response)) {
466
+ result.ok = false;
467
+ result.code = "ResponseFieldMissing";
468
+ result.message = "响应内容找不到状态字段 " + statusField;
469
+ return result;
470
+ }
471
+ const code = statusField ? response[statusField] + "" : "";
472
+ result.ok = statusField ? code === statusOKValue : true;
473
+ result.code = code || statusText;
474
+ result.data = dataField in response ? response[dataField] : null;
475
+ result.message = readMessageFrom(response, messageField);
476
+ if (ignoreMessage && result.message) {
477
+ if (Array.isArray(ignoreMessage) && ignoreMessage.includes(result.message) || typeof ignoreMessage === "string" && result.message === ignoreMessage) {
478
+ result.message = "";
479
+ }
480
+ }
481
+ return result;
482
+ }
483
+ function statusOK(status) {
484
+ return status >= 200 && status < 400;
485
+ }
486
+
487
+ async function retryRequest(agent, url, config, options, _try) {
488
+ var _ref, _options$maxRetry, _options$retryResolve, _options$retryInterva;
489
+ const currentTryCount = _try || 0;
490
+ const maxRetry = Math.min(10, (_ref = (_options$maxRetry = options == null ? void 0 : options.maxRetry) != null ? _options$maxRetry : config.get("maxRetry")) != null ? _ref : 0);
491
+ const retryResolve = (_options$retryResolve = options == null ? void 0 : options.retryResolve) != null ? _options$retryResolve : config.get("retryResolve");
492
+ const logger = config.get("logHandler") || noop;
493
+ logger({
494
+ type: "prepear",
495
+ url,
496
+ method: (options == null ? void 0 : options.method) || "GET",
497
+ retry: currentTryCount,
498
+ maxRetry,
499
+ message: currentTryCount === 0 ? "start" : `retry ${currentTryCount}/${maxRetry} start`,
500
+ headers: options == null ? void 0 : options.headers,
501
+ options
502
+ });
503
+ const start = Date.now();
504
+ const result = await agent(url, config, options);
505
+ const status = result.status;
506
+ const cost = Date.now() - start;
507
+ const payload = `[cost ${cost}][${status}] ${status < 0 ? result.body : ""}`;
508
+ logger({
509
+ type: "finished",
510
+ url,
511
+ method: result.method,
512
+ retry: currentTryCount,
513
+ maxRetry,
514
+ message: currentTryCount === 0 ? `finish ${payload}` : `retry ${currentTryCount}/${maxRetry} finish ${payload}`,
515
+ response: result,
516
+ headers: result.headers,
517
+ cost
518
+ });
519
+ // status 大于 0 表示服务器已经有响应
520
+ const ok = statusOK(status);
521
+ if (!maxRetry || retryResolve === "network" && status > 0 || retryResolve === "status" && ok || currentTryCount >= maxRetry) {
522
+ return result;
523
+ }
524
+ const retryInterval = (_options$retryInterva = options == null ? void 0 : options.retryInterval) != null ? _options$retryInterva : config.get("retryInterval");
525
+ // 最短间隔 100ms 才能重试
526
+ await sleep(Math.max(100, typeof retryInterval === "function" ? retryInterval(currentTryCount + 1) : retryInterval));
527
+ return await retryRequest(agent, url, config, options, currentTryCount + 1);
528
+ }
529
+
530
+ function handleResponse(res, url, config, options) {
531
+ var _config$get2;
532
+ // status为负数的表示网络错误或请求取消等异常情况
533
+ if (res.status < 0) {
534
+ return checkGlobalMessage({
535
+ ok: false,
536
+ status: res.status,
537
+ code: res.statusText,
538
+ headers: {},
539
+ message: "",
540
+ data: null
541
+ }, `${res.method} ${url} ${res.statusText}`, res.method, url, config, options);
542
+ }
543
+ // 处理全局 http 错误
544
+ if (!statusOK(res.status)) {
545
+ var _config$get;
546
+ (_config$get = config.get("errorHandler")) == null || _config$get(res.status, res.method, url);
547
+ }
548
+ // 分析响应内容
549
+ const result = {
550
+ ...analyseResponse(res.status, res.statusText, res.body, config.get("responseRule"), options == null ? void 0 : options.responseRule),
551
+ status: res.status,
552
+ headers: Object.fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
553
+ };
554
+ // 全局处理响应结果 (浅复制,防止被修改,同时保留修改 result.data 的可能性)
555
+ (_config$get2 = config.get("responseHandler")) == null || _config$get2({
556
+ ...result
557
+ }, res.method, url);
558
+ // 检查并全局提示
559
+ const defaultMessage = result.ok ? result.message : `${res.method} ${url} [${result.code || res.statusText}] ${result.message || res.statusText}`;
560
+ return checkGlobalMessage(result, defaultMessage, res.method, url, config, options);
561
+ }
562
+ function checkGlobalMessage(result, defaultMessage, method, url, config, options) {
563
+ const gmessageConvert = config.get("message");
564
+ const messageConvert = gmessageConvert === false || (options == null ? void 0 : options.message) === false ? false : (options == null ? void 0 : options.message) || gmessageConvert;
565
+ if (messageConvert !== false) {
566
+ config.showMessage(!result.ok, typeof messageConvert === "function" ? messageConvert(result, method, url, defaultMessage) : defaultMessage);
567
+ }
568
+ return result;
569
+ }
570
+
571
+ async function convertOptions(url, config, options) {
572
+ var _config$get, _config$get2;
573
+ const opt = Object.assign({
574
+ method: "GET"
575
+ }, options);
576
+ const isFormMode = opt.body instanceof FormData;
577
+ const method = isFormMode ? "POST" : opt.method;
578
+ if (method === "GET" || method === "HEAD" || method === "DELETE") {
579
+ if (opt.body !== undefined) {
580
+ console.warn("request body is invalid with method get, head, delete");
581
+ delete opt.body;
582
+ }
583
+ }
584
+ const headers = Object.assign(isFormMode ? {} : {
585
+ "Content-Type": "application/json;charset=utf-8"
586
+ }, opt.headers);
587
+ const p = opt.params || {};
588
+ const params = {};
589
+ Object.keys(p).forEach(key => {
590
+ if (p[key] !== undefined) {
591
+ params[key] = convertParam(p[key]);
592
+ }
593
+ });
594
+ const fullUrl = config.getFullUrl(url);
595
+ const body = convertBody(opt.body);
596
+ const timeout = opt.timeout || config.get("timeout");
597
+ // 全局请求干预函数,可以修改 headers 和 params 并返回新的 url 地址
598
+ const newURL = await ((_config$get = config.get("requestTransformer")) == null ? void 0 : _config$get({
599
+ headers,
600
+ params,
601
+ method,
602
+ url: fullUrl,
603
+ body
604
+ }));
605
+ const finalUrl = typeof newURL === "string" && newURL ? newURL : fullUrl;
606
+ // 打印日志
607
+ (_config$get2 = config.get("logHandler")) == null || _config$get2({
608
+ type: "ready",
609
+ url: finalUrl,
610
+ method,
611
+ headers,
612
+ timeout,
613
+ body
614
+ });
615
+ // 返回
616
+ return {
617
+ url: finalUrl,
618
+ method,
619
+ body,
620
+ params,
621
+ headers,
622
+ timeout
623
+ };
624
+ }
625
+ /** 将数据转成 string 格式表示,仅仅特殊处理 array 为 item,item... */
626
+ function convertParam(val) {
627
+ if (typeof val === "string") {
628
+ return val;
629
+ }
630
+ if (Array.isArray(val)) {
631
+ return val.join(",");
632
+ }
633
+ return val + "";
634
+ }
635
+ function convertBody(body) {
636
+ if (!body) {
637
+ return;
638
+ }
639
+ if (body instanceof Blob || body instanceof ArrayBuffer || body instanceof FormData || body instanceof URLSearchParams || typeof body === "string") {
640
+ return body;
641
+ }
642
+ return JSON.stringify(body);
643
+ }
644
+
645
+ /**
646
+ * 基于 nodejs 的 http/https 包的网络请求包装函数,url 必须是一个完整 url
647
+ *
648
+ * 该方法必定 resolve,限制在 nodejs 环境中使用
649
+ */
650
+ const nodeRequest = async function (url, config, options) {
651
+ return handleResponse(await retryRequest(coreNodeRequest, url, config, options), url, config, options);
652
+ };
653
+ const coreNodeRequest = async function (url, config, options) {
654
+ const opt = await convertOptions(url, config, options);
655
+ if (!isFullURL(opt.url)) {
656
+ return {
657
+ url: opt.url,
658
+ method: opt.method,
659
+ status: -2,
660
+ statusText: "URLFormatError",
661
+ headers: {},
662
+ body: ""
663
+ };
664
+ }
665
+ const client = /^https:\/\//i.test(opt.url) ? https__namespace : http__namespace;
666
+ const iURL = new URL(opt.url);
667
+ const params = opt.params;
668
+ if (params instanceof Object) {
669
+ Object.keys(params).forEach(key => iURL.searchParams.set(key, params[key]));
670
+ }
671
+ const isHeadRequest = opt.method === "HEAD";
672
+ return new Promise(resolve => {
673
+ const req = client.request(iURL, {
674
+ headers: opt.headers,
675
+ method: opt.method,
676
+ timeout: opt.timeout > 0 ? opt.timeout : undefined
677
+ }, function (res) {
678
+ const resbody = [];
679
+ res.on("data", chunk => resbody.push(chunk));
680
+ res.on("end", () => {
681
+ const headers = Object.fromEntries(Object.entries(res.headers).map(([key, value]) => {
682
+ return [key.toLowerCase(), Array.isArray(value) ? value.join(",") : value];
683
+ }));
684
+ resolve({
685
+ url: iURL.toString(),
686
+ method: opt.method,
687
+ status: res.statusCode || -3,
688
+ statusText: res.statusMessage || "Unknown",
689
+ headers,
690
+ body: isHeadRequest ? "" : Buffer.concat(resbody).toString("utf-8")
691
+ });
692
+ });
693
+ });
694
+ req.on("error", e => {
695
+ resolve({
696
+ url: iURL.toString(),
697
+ method: opt.method,
698
+ status: -1,
699
+ statusText: e.name || "Unknown",
700
+ body: e.message
701
+ });
702
+ });
703
+ req.on("timeout", () => {
704
+ resolve({
705
+ url: iURL.toString(),
706
+ method: opt.method,
707
+ status: -1,
708
+ statusText: "Timeout",
709
+ body: ""
710
+ });
711
+ });
712
+ if (opt.body) {
713
+ req.write(opt.body);
714
+ }
715
+ req.end();
716
+ });
717
+ };
718
+
719
+ /** 为 get 请求并发而设计的缓冲工具 */
720
+ class Cache {
721
+ constructor(ttl = 500) {
722
+ this.ttl = void 0;
723
+ this.cache = void 0;
724
+ this.cache = {};
725
+ this.ttl = Math.max(ttl, 0);
726
+ }
727
+ getKey(url, param) {
728
+ const p = Object.keys(param || {}).sort().map(key => `${key}#${param == null ? void 0 : param[key]}`);
729
+ return url + p.join(",");
730
+ }
731
+ updateTTL(ttl) {
732
+ this.ttl = Math.max(ttl, 0);
733
+ }
734
+ get(key) {
735
+ if (this.ttl === 0) {
736
+ return null;
737
+ }
738
+ const c = this.cache[key];
739
+ if (!c) {
740
+ return null;
741
+ }
742
+ if (c.ttl < Date.now()) {
743
+ delete this.cache[key];
744
+ return null;
745
+ }
746
+ return c.res;
747
+ }
748
+ set(key, action) {
749
+ if (this.ttl === 0) {
750
+ return;
751
+ }
752
+ this.cache[key] = {
753
+ ttl: Date.now() + this.ttl,
754
+ res: action
755
+ };
756
+ }
757
+ }
758
+
759
+ function checkTypedDataResult(url, result, config, typeGard) {
760
+ if (result.ok && !isEmpty(result.data) && typeGard) {
761
+ const guard = getTypeGuard(typeGard, "响应数据未能正确识别");
762
+ if (guard.guard(result.data)) {
763
+ return result;
764
+ }
765
+ config.showMessage(true, `${url} ${guard.message}`);
766
+ result.data = null;
767
+ return result;
768
+ }
769
+ return result;
770
+ }
771
+
772
+ class RequestGlobalConfig {
773
+ constructor(config) {
774
+ // 保存的配置需要部分字段强制设置默认值
775
+ this.config = {
776
+ baseURL: "",
777
+ maxRetry: 0,
778
+ retryInterval: 1000,
779
+ retryResolve: "network",
780
+ timeout: 5000,
781
+ cacheTTL: 500,
782
+ responseRule: {
783
+ ok: {
784
+ resolve: "body"
785
+ },
786
+ failed: {
787
+ resolve: "json",
788
+ messageField: "message"
789
+ }
790
+ }
791
+ };
792
+ config && this.set(config);
793
+ }
794
+ set(config) {
795
+ if (config.baseURL && !/^\/.+/.test(config.baseURL) && !isFullURL(config.baseURL)) {
796
+ console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址");
797
+ throw new Error("BaseURLError");
798
+ }
799
+ Object.assign(this.config, config);
800
+ }
801
+ get(key) {
802
+ return this.config[key];
803
+ }
804
+ /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
805
+ getFullUrl(url) {
806
+ return url.startsWith("/") ? getFullURL(url) : getFullURL(url, this.config.baseURL);
807
+ }
808
+ /** 提示消息 */
809
+ showMessage(isError, message) {
810
+ if (this.config.messageHandler && message) {
811
+ this.config.messageHandler(isError, message);
812
+ }
813
+ }
814
+ }
815
+
816
+ /** 工具函数主类 */
817
+ class NetRequestHandler {
818
+ constructor(agent, config) {
819
+ this.agent = void 0;
820
+ this.config = void 0;
821
+ this.cache = void 0;
822
+ this.config = new RequestGlobalConfig(config);
823
+ this.agent = agent;
824
+ this.cache = new Cache(this.config.get("cacheTTL"));
825
+ // bind this
826
+ this.setConfig = this.setConfig.bind(this);
827
+ this.getConfig = this.getConfig.bind(this);
828
+ this.get = this.get.bind(this);
829
+ this.post = this.post.bind(this);
830
+ this.del = this.del.bind(this);
831
+ this.patch = this.patch.bind(this);
832
+ this.put = this.put.bind(this);
833
+ this.head = this.head.bind(this);
834
+ }
835
+ /**
836
+ * 执行网络请求
837
+ */
838
+ async exec(url, options) {
839
+ return await this.agent(url, this.config, options);
840
+ }
841
+ /**
842
+ * 检查响应的数据类型
843
+ */
844
+ async guard(url, result, typeGard) {
845
+ return checkTypedDataResult(url, result, this.config, typeGard);
846
+ }
847
+ /**
848
+ * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
849
+ */
850
+ setConfig(config) {
851
+ this.config.set(config);
852
+ this.cache.updateTTL(this.config.get("cacheTTL"));
853
+ }
854
+ /**
855
+ * 读取默认的请求配置
856
+ */
857
+ getConfig(key) {
858
+ return this.config.get(key);
859
+ }
860
+ /**
861
+ * 发送一个 HEAD 请求,并且不处理响应 body
862
+ */
863
+ async head(url, options) {
864
+ const ops = Object.assign({}, options || null);
865
+ ops.method = "HEAD";
866
+ return this.guard(url, await this.exec(url, ops), null);
867
+ }
868
+ async get(url, typeGard, options) {
869
+ const ops = Object.assign({}, options || null);
870
+ ops.method = "GET";
871
+ const cacheKey = this.cache.getKey(url, ops.params);
872
+ const cache = this.cache.get(cacheKey);
873
+ if (cache) {
874
+ return this.guard(url, await cache, typeGard || null);
875
+ }
876
+ const res = this.exec(url, ops);
877
+ this.cache.set(cacheKey, res);
878
+ return this.guard(url, await res, typeGard || null);
879
+ }
880
+ async post(url, data, typeGard, options) {
881
+ const ops = Object.assign({}, options || null);
882
+ ops.method = "POST";
883
+ ops.body = data;
884
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
885
+ }
886
+ async del(url, typeGard, options) {
887
+ const ops = Object.assign({}, options || null);
888
+ ops.method = "DELETE";
889
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
890
+ }
891
+ async put(url, data, typeGard, options) {
892
+ const ops = Object.assign({}, options || null);
893
+ ops.method = "PUT";
894
+ ops.body = data;
895
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
896
+ }
897
+ async patch(url, data, typeGard, options) {
898
+ const ops = Object.assign({}, options || null);
899
+ ops.method = "PATCH";
900
+ ops.body = data;
901
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
902
+ }
903
+ }
904
+
905
+ function NetRequest(config) {
906
+ return new NetRequestHandler(nodeRequest, config);
907
+ }
908
+
909
+ const ApiPrefix = "/v1/server";
910
+ /**
911
+ * Combo SDK For Server REST Api
912
+ */
913
+ class ApiClient {
914
+ constructor(config) {
915
+ var _config$maxRetry;
916
+ this.req = void 0;
917
+ verifyConfig(config);
918
+ const ua = getUserAgent(config.game);
919
+ this.req = NetRequest({
920
+ baseURL: `${config.endpoint.replace(/\/$/, "")}${ApiPrefix}`,
921
+ maxRetry: (_config$maxRetry = config.maxRetry) != null ? _config$maxRetry : 1,
922
+ retryInterval: config.retryInterval,
923
+ responseRule: {
924
+ ok: {
925
+ resolve: "body"
926
+ },
927
+ failed: {
928
+ resolve: "json",
929
+ statusField: "error",
930
+ messageField: "message"
931
+ }
932
+ },
933
+ requestTransformer({
934
+ headers,
935
+ method,
936
+ url,
937
+ params,
938
+ body
939
+ }) {
940
+ const iURL = new URL(url);
941
+ if (params) {
942
+ if (params instanceof Object) {
943
+ Object.keys(params).forEach(key => iURL.searchParams.set(key, params[key]));
944
+ }
945
+ }
946
+ headers["User-Agent"] = ua;
947
+ headers[AuthorizationField] = calcAuthorizationHeader({
948
+ game: config.game,
949
+ secret: config.secret,
950
+ endpoint: config.endpoint,
951
+ method,
952
+ url: iURL.toString(),
953
+ data: body || ""
954
+ });
955
+ },
956
+ logHandler: config.logger,
957
+ timeout: config.timeout
958
+ });
959
+ }
960
+ /**
961
+ * 创建订单
962
+ */
963
+ async createOrder(option) {
964
+ if (!option.combo_id || !option.notify_url || !option.product_id || !option.reference_id) {
965
+ throw new Error("createOrder: 必要参数缺失");
966
+ }
967
+ // 检查购买数量
968
+ option.quantity = Math.min(Math.max(1, Math.ceil(option.quantity)), Number.MAX_SAFE_INTEGER);
969
+ const {
970
+ ok,
971
+ data,
972
+ code,
973
+ status,
974
+ message,
975
+ headers
976
+ } = await this.req.post("create-order", option, isCreateOrderResponse);
977
+ if (!ok || !data) {
978
+ console.error({
979
+ type: "createOrder Error",
980
+ status,
981
+ code,
982
+ message,
983
+ traceId: headers["x-trace-id"]
984
+ });
985
+ throw new Error(`createOrder: ${message || code || status}`);
986
+ }
987
+ return data;
988
+ }
989
+ /**
990
+ * 通知世游服务端玩家进入游戏世界(上线)
991
+ *
992
+ * 此接口仅用于中宣部防沉迷系统的上下线数据上报
993
+ *
994
+ * @param comboId 聚合用户标识
995
+ * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
996
+ */
997
+ async enterGame(comboId, sessionId) {
998
+ if (!comboId || !sessionId) {
999
+ throw new Error("enterGame: 必要参数缺失");
1000
+ }
1001
+ const {
1002
+ ok,
1003
+ status,
1004
+ code,
1005
+ message,
1006
+ headers
1007
+ } = await this.req.post("enter-game", {
1008
+ combo_id: comboId,
1009
+ session_id: sessionId
1010
+ });
1011
+ if (!ok) {
1012
+ console.error({
1013
+ type: "enterGame Error",
1014
+ status,
1015
+ code,
1016
+ message,
1017
+ traceId: headers["x-trace-id"]
1018
+ });
1019
+ }
1020
+ return ok;
1021
+ }
1022
+ /**
1023
+ * 通知世游服务端玩家离开游戏世界(下线)
1024
+ *
1025
+ * 此接口仅用于中宣部防沉迷系统的上下线数据上报
1026
+ *
1027
+ * @param comboId 聚合用户标识
1028
+ * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
1029
+ */
1030
+ async leaveGame(comboId, sessionId) {
1031
+ if (!comboId || !sessionId) {
1032
+ throw new Error("enterGame: 必要参数缺失");
1033
+ }
1034
+ const {
1035
+ ok,
1036
+ status,
1037
+ code,
1038
+ message,
1039
+ headers
1040
+ } = await this.req.post("leave-game", {
1041
+ combo_id: comboId,
1042
+ session_id: sessionId
1043
+ });
1044
+ if (!ok) {
1045
+ console.error({
1046
+ type: "leaveGame Error",
1047
+ status,
1048
+ code,
1049
+ message,
1050
+ traceId: headers["x-trace-id"]
1051
+ });
1052
+ }
1053
+ return ok;
1054
+ }
1055
+ }
1056
+ function isCreateOrderResponse(data) {
1057
+ return isObject(data) && ["order_id", "order_token"].every(field => field in data) && "expires_at" in data && typeof data.expires_at === "number";
1058
+ }
1059
+
1060
+ function isIdentityJwtPayload(payload) {
1061
+ return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "external_id" in payload && "external_name" in payload;
1062
+ }
1063
+
1064
+ function isAdJwtPayload(payload) {
1065
+ return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "placement_id" in payload && "impression_id" in payload;
1066
+ }
1067
+
1068
+ const IdentityTokenScope = "auth";
1069
+ const AdTokenScope = "ads";
1070
+ /**
1071
+ * token 验证器
1072
+ */
1073
+ class TokenVerifier {
1074
+ constructor(config) {
1075
+ this.privateKey = void 0;
1076
+ this.baseOption = void 0;
1077
+ verifyConfig(config);
1078
+ this.privateKey = config.secret;
1079
+ this.baseOption = {
1080
+ // https://github.com/auth0/node-jsonwebtoken#algorithms-supported
1081
+ algorithms: ["HS256"],
1082
+ audience: config.game,
1083
+ issuer: config.endpoint,
1084
+ ignoreExpiration: false
1085
+ };
1086
+ }
1087
+ /**
1088
+ * verifyIdentityToken 对 IdentityToken 进行验证
1089
+ *
1090
+ * 验证失败会返回 Error 对象
1091
+ */
1092
+ verifyIdentityToken(token) {
1093
+ try {
1094
+ const payload = jsonwebtoken.verify(token, this.privateKey, {
1095
+ ...this.baseOption,
1096
+ complete: false
1097
+ });
1098
+ if (!payload || !isIdentityJwtPayload(payload) || !payload.sub) {
1099
+ return new Error("verifyIdentityToken: token 格式化失败 " + JSON.stringify(payload));
1100
+ }
1101
+ if (payload.scope !== IdentityTokenScope) {
1102
+ return new Error("verifyIdentityToken: 无效的 Scope");
1103
+ }
1104
+ return {
1105
+ combo_id: payload.sub,
1106
+ idp: payload.idp,
1107
+ external_id: payload.external_id,
1108
+ external_name: payload.external_name,
1109
+ weixin_unionid: payload.weixin_unionid
1110
+ };
1111
+ } catch (error) {
1112
+ return new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1113
+ }
1114
+ }
1115
+ /**
1116
+ * verifyAdToken 对 AdToken 进行验证
1117
+ *
1118
+ * 验证失败会返回 Error 对象
1119
+ */
1120
+ verifyAdToken(token) {
1121
+ try {
1122
+ const payload = jsonwebtoken.verify(token, this.privateKey, {
1123
+ ...this.baseOption,
1124
+ complete: false
1125
+ });
1126
+ if (!payload || !isAdJwtPayload(payload) || !payload.sub) {
1127
+ return new Error("verifyAdToken: token 格式化失败 " + JSON.stringify(payload));
1128
+ }
1129
+ if (payload.scope !== AdTokenScope) {
1130
+ return new Error("verifyAdToken: 无效的 Scope");
1131
+ }
1132
+ return {
1133
+ combo_id: payload.sub,
1134
+ placement_id: payload.placement_id,
1135
+ impression_id: payload.impression_id
1136
+ };
1137
+ } catch (error) {
1138
+ return new Error(`AdToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1139
+ }
1140
+ }
1141
+ }
1142
+
1143
+ function isShipOrderPayload(data) {
1144
+ 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;
1145
+ }
1146
+
1147
+ /**
1148
+ * 消息处理分发配置
1149
+ */
1150
+ const messageDataGuards = {
1151
+ ["ship_order" /* NotificationType.ShipOrder */]: {
1152
+ guard: isShipOrderPayload,
1153
+ message: "ShipOrder Data Format Error"
1154
+ }
1155
+ };
1156
+
1157
+ function isNotificationRequestBody(data) {
1158
+ 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";
1159
+ }
1160
+ /**
1161
+ * 获取一个处理函数用于接收 Seayoo Server 推送过来的消息通知
1162
+ *
1163
+ * 另有 express 和 koa2 版本的处理函数可以使用。
1164
+ *
1165
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以用以签名
1166
+ */
1167
+ function getNotificationHandler(config, handler) {
1168
+ verifyConfig(config);
1169
+ /**
1170
+ * 第三个可选参数 rawBodyString 用于在特定场景 request 为 unreadable 时作为容错兜底方案处理
1171
+ *
1172
+ * 具体方案可以参考
1173
+ *
1174
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1175
+ */
1176
+ return async function (req, res, rawBodyString) {
1177
+ if (req.method !== "POST") {
1178
+ done(res, 405);
1179
+ return;
1180
+ }
1181
+ const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1182
+ if (!contentType || !contentType.startsWith("application/json")) {
1183
+ done(res, 415);
1184
+ return;
1185
+ }
1186
+ const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
1187
+ const body = await readBody(req, rawBodyString);
1188
+ if (!body || !checkHttpAuthInfo(`${authString}`, {
1189
+ game: config.game,
1190
+ secret: config.secret,
1191
+ method: "POST",
1192
+ // 此处协议不参与计算不需要准确设定
1193
+ endpoint: `http://${req.headers.host}`,
1194
+ url: req.url || "",
1195
+ data: body
1196
+ })) {
1197
+ done(res, 401);
1198
+ return;
1199
+ }
1200
+ const notification = parseJSON(body, isNotificationRequestBody);
1201
+ if (!notification) {
1202
+ done(res, 400, `Notification body Format Error`);
1203
+ return;
1204
+ }
1205
+ const guardCfg = messageDataGuards[notification.notification_type];
1206
+ if (!guardCfg) {
1207
+ done(res, 400, `Unknown Notification Type: ${notification.notification_type}`);
1208
+ return;
1209
+ }
1210
+ if (!guardCfg.guard(notification.data)) {
1211
+ done(res, 400, guardCfg.message);
1212
+ return;
1213
+ }
1214
+ // 所有错误检查完毕,通知游戏处理函数
1215
+ try {
1216
+ await handler(notification.notification_type, notification.data);
1217
+ done(res, 200, "OK");
1218
+ } catch (e) {
1219
+ done(res, 500, e instanceof Error ? e.message : String(e));
1220
+ }
1221
+ };
1222
+ }
1223
+ /**
1224
+ * 获取基于 express 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1225
+ *
1226
+ * 如需自定义处理,可以使用 getNotificationHandler 方法,
1227
+ *
1228
+ * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1229
+ *
1230
+ * 处理方法可以参考
1231
+ *
1232
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1233
+ */
1234
+ function getNotificationHandlerForExpress(config, handler) {
1235
+ const func = getNotificationHandler(config, handler);
1236
+ return async function (req, res) {
1237
+ await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1238
+ };
1239
+ }
1240
+ /**
1241
+ * 获取基于 koa2 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1242
+ *
1243
+ * 如需自定义处理,可以使用 getNotificationHandler 方法
1244
+ *
1245
+ * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1246
+ *
1247
+ * 处理方法可以参考
1248
+ *
1249
+ *
1250
+ */
1251
+ function getNotificationHandlerForKoa(config, handler) {
1252
+ const func = getNotificationHandler(config, handler);
1253
+ return async function (ctx) {
1254
+ await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1255
+ };
1256
+ }
1257
+
1258
+ exports.ApiClient = ApiClient;
1259
+ exports.TokenVerifier = TokenVerifier;
1260
+ exports.calcAuthorizationHeader = calcAuthorizationHeader;
1261
+ exports.getNotificationHandler = getNotificationHandler;
1262
+ exports.getNotificationHandlerForExpress = getNotificationHandlerForExpress;
1263
+ exports.getNotificationHandlerForKoa = getNotificationHandlerForKoa;
1264
+ exports.parseAuthorizationHeader = parseAuthorizationHeader;