@jayfong/x-server 2.119.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. package/lib/_virtual/_rolldown/runtime.mjs +4 -0
  2. package/lib/cli/api_generator.d.mts +75 -0
  3. package/lib/cli/api_generator.mjs +334 -0
  4. package/lib/cli/build_util.d.mts +15 -0
  5. package/lib/cli/build_util.mjs +101 -0
  6. package/lib/cli/cli.d.mts +1 -0
  7. package/lib/cli/cli.mjs +345 -0
  8. package/lib/cli/css_register.d.mts +1 -0
  9. package/lib/cli/css_register.mjs +7 -0
  10. package/lib/cli/deploy_util.d.mts +23 -0
  11. package/lib/cli/deploy_util.mjs +70 -0
  12. package/lib/cli/dev_util.d.mts +9 -0
  13. package/lib/cli/dev_util.mjs +25 -0
  14. package/lib/cli/env_util.d.mts +45 -0
  15. package/lib/cli/env_util.mjs +207 -0
  16. package/lib/cli/template_util.d.mts +18 -0
  17. package/lib/cli/template_util.mjs +85 -0
  18. package/lib/cli/templates/crons.ts +1 -1
  19. package/lib/cli/templates/handlers.ts +1 -1
  20. package/lib/cli/templates/hooks.ts +1 -1
  21. package/lib/cli/templates/models.ts +7 -7
  22. package/lib/cli/templates/package.json +11 -1
  23. package/lib/cli/templates/routes.ts +2 -2
  24. package/lib/core/ctx_storage.d.mts +3 -0
  25. package/lib/core/ctx_storage.mjs +4 -0
  26. package/lib/core/define_bus.d.mts +37 -0
  27. package/lib/core/define_bus.mjs +12 -0
  28. package/lib/core/{define_cron.d.ts → define_cron.d.mts} +2 -2
  29. package/lib/core/define_cron.mjs +11 -0
  30. package/lib/core/{define_handler.d.ts → define_handler.d.mts} +19 -19
  31. package/lib/core/define_handler.mjs +44 -0
  32. package/lib/core/define_hook.d.mts +2 -0
  33. package/lib/core/define_hook.mjs +6 -0
  34. package/lib/core/define_server.d.mts +3 -0
  35. package/lib/core/define_server.mjs +8 -0
  36. package/lib/core/{define_task.d.ts → define_task.d.mts} +2 -2
  37. package/lib/core/define_task.mjs +106 -0
  38. package/lib/core/get_handler_url.d.mts +2 -0
  39. package/lib/core/get_handler_url.mjs +7 -0
  40. package/lib/core/handler.d.mts +16 -0
  41. package/lib/core/handler.mjs +132 -0
  42. package/lib/core/http_error.d.mts +2 -0
  43. package/lib/core/http_error.mjs +1 -0
  44. package/lib/core/http_header.d.mts +856 -0
  45. package/lib/core/http_header.mjs +860 -0
  46. package/lib/core/http_method.d.mts +3 -0
  47. package/lib/core/http_method.mjs +10 -0
  48. package/lib/core/http_redirect.d.mts +5 -0
  49. package/lib/core/http_redirect.mjs +10 -0
  50. package/lib/core/server.d.mts +20 -0
  51. package/lib/core/server.mjs +186 -0
  52. package/lib/core/types.d.mts +256 -0
  53. package/lib/exports.d.mts +46 -0
  54. package/lib/exports.mjs +46 -0
  55. package/lib/index.d.mts +48 -0
  56. package/lib/index.mjs +45 -0
  57. package/lib/plugins/base.d.mts +4 -0
  58. package/lib/plugins/compress.d.mts +12 -0
  59. package/lib/plugins/compress.mjs +15 -0
  60. package/lib/plugins/cookie.d.mts +12 -0
  61. package/lib/plugins/cookie.mjs +15 -0
  62. package/lib/plugins/cors.d.mts +22 -0
  63. package/lib/plugins/cors.mjs +34 -0
  64. package/lib/plugins/file_parser.d.mts +15 -0
  65. package/lib/plugins/file_parser.mjs +24 -0
  66. package/lib/plugins/form_body_parser.d.mts +12 -0
  67. package/lib/plugins/form_body_parser.mjs +15 -0
  68. package/lib/plugins/ws_parser.d.mts +12 -0
  69. package/lib/plugins/ws_parser.mjs +15 -0
  70. package/lib/plugins/xml_parser.d.mts +19 -0
  71. package/lib/plugins/xml_parser.mjs +40 -0
  72. package/lib/services/ai.d.mts +31 -0
  73. package/lib/services/ai.mjs +44 -0
  74. package/lib/services/base.d.mts +4 -0
  75. package/lib/services/base.mjs +1 -0
  76. package/lib/services/cache.d.mts +165 -0
  77. package/lib/services/cache.mjs +323 -0
  78. package/lib/services/captcha.d.mts +65 -0
  79. package/lib/services/captcha.mjs +61 -0
  80. package/lib/services/{crypto.js → crypto.d.mts} +19 -78
  81. package/lib/services/crypto.mjs +141 -0
  82. package/lib/services/db_value.d.mts +60 -0
  83. package/lib/services/db_value.mjs +64 -0
  84. package/lib/services/dingtalk.d.mts +39 -0
  85. package/lib/services/dingtalk.mjs +44 -0
  86. package/lib/services/dispose.d.mts +17 -0
  87. package/lib/services/dispose.mjs +18 -0
  88. package/lib/services/emoji.d.mts +10 -0
  89. package/lib/services/emoji.mjs +2025 -0
  90. package/lib/services/file_store.d.mts +49 -0
  91. package/lib/services/file_store.mjs +58 -0
  92. package/lib/services/html.d.mts +11 -0
  93. package/lib/services/html.mjs +12 -0
  94. package/lib/services/jwt.d.mts +33 -0
  95. package/lib/services/jwt.mjs +42 -0
  96. package/lib/services/log.d.mts +37 -0
  97. package/lib/services/log.mjs +99 -0
  98. package/lib/services/mail.d.mts +22 -0
  99. package/lib/services/mail.mjs +28 -0
  100. package/lib/services/pay.d.mts +123 -0
  101. package/lib/services/pay.mjs +157 -0
  102. package/lib/services/random.d.mts +27 -0
  103. package/lib/services/random.mjs +42 -0
  104. package/lib/services/rate_limit.d.mts +37 -0
  105. package/lib/services/rate_limit.mjs +40 -0
  106. package/lib/services/redis.d.mts +11 -0
  107. package/lib/services/redis.mjs +6 -0
  108. package/lib/services/sensitive_words.d.mts +29 -0
  109. package/lib/services/sensitive_words.mjs +37 -0
  110. package/lib/services/sms.d.mts +40 -0
  111. package/lib/services/sms.mjs +30238 -0
  112. package/lib/types/dto.d.mts +30 -0
  113. package/lib/types/dto.mjs +1 -0
  114. package/lib/x.d.mts +11 -0
  115. package/lib/x.mjs +21 -0
  116. package/lib/x_init.d.mts +1 -0
  117. package/lib/x_init.mjs +10 -0
  118. package/package.json +82 -32
  119. package/lib/_cjs/cli/api_generator.js +0 -458
  120. package/lib/_cjs/cli/build_util.js +0 -243
  121. package/lib/_cjs/cli/cli.js +0 -378
  122. package/lib/_cjs/cli/css_register.js +0 -7
  123. package/lib/_cjs/cli/deploy_util.js +0 -76
  124. package/lib/_cjs/cli/dev_util.js +0 -26
  125. package/lib/_cjs/cli/env_util.js +0 -252
  126. package/lib/_cjs/cli/esbuild_register.js +0 -7
  127. package/lib/_cjs/cli/template_util.js +0 -101
  128. package/lib/_cjs/cli/templates/crons.ts +0 -2
  129. package/lib/_cjs/cli/templates/handlers.ts +0 -3
  130. package/lib/_cjs/cli/templates/hooks.ts +0 -2
  131. package/lib/_cjs/cli/templates/models.ts +0 -123
  132. package/lib/_cjs/cli/templates/package.json +0 -3
  133. package/lib/_cjs/cli/templates/routes.ts +0 -68
  134. package/lib/_cjs/core/ctx_storage.js +0 -6
  135. package/lib/_cjs/core/define_bus.js +0 -31
  136. package/lib/_cjs/core/define_cron.js +0 -13
  137. package/lib/_cjs/core/define_handler.js +0 -56
  138. package/lib/_cjs/core/define_hook.js +0 -8
  139. package/lib/_cjs/core/define_server.js +0 -10
  140. package/lib/_cjs/core/define_task.js +0 -113
  141. package/lib/_cjs/core/get_handler_url.js +0 -11
  142. package/lib/_cjs/core/handler.js +0 -216
  143. package/lib/_cjs/core/http_error.js +0 -6
  144. package/lib/_cjs/core/http_header.js +0 -142
  145. package/lib/_cjs/core/http_method.js +0 -12
  146. package/lib/_cjs/core/http_redirect.js +0 -11
  147. package/lib/_cjs/core/server.js +0 -219
  148. package/lib/_cjs/core/types.js +0 -8
  149. package/lib/_cjs/exports.js +0 -273
  150. package/lib/_cjs/index.js +0 -15
  151. package/lib/_cjs/plugins/base.js +0 -3
  152. package/lib/_cjs/plugins/compress.js +0 -18
  153. package/lib/_cjs/plugins/cookie.js +0 -18
  154. package/lib/_cjs/plugins/cors.js +0 -38
  155. package/lib/_cjs/plugins/file_parser.js +0 -28
  156. package/lib/_cjs/plugins/form_body_parser.js +0 -18
  157. package/lib/_cjs/plugins/ws_parser.js +0 -18
  158. package/lib/_cjs/plugins/xml_parser.js +0 -48
  159. package/lib/_cjs/services/ai.js +0 -48
  160. package/lib/_cjs/services/base.js +0 -3
  161. package/lib/_cjs/services/cache.js +0 -400
  162. package/lib/_cjs/services/captcha.js +0 -78
  163. package/lib/_cjs/services/crypto.js +0 -175
  164. package/lib/_cjs/services/db_value.js +0 -77
  165. package/lib/_cjs/services/dingtalk.js +0 -51
  166. package/lib/_cjs/services/dispose.js +0 -23
  167. package/lib/_cjs/services/emoji.js +0 -2034
  168. package/lib/_cjs/services/file_store.js +0 -67
  169. package/lib/_cjs/services/html.js +0 -17
  170. package/lib/_cjs/services/jwt.js +0 -65
  171. package/lib/_cjs/services/log.js +0 -108
  172. package/lib/_cjs/services/mail.js +0 -31
  173. package/lib/_cjs/services/pay.js +0 -191
  174. package/lib/_cjs/services/random.js +0 -51
  175. package/lib/_cjs/services/rate_limit.js +0 -54
  176. package/lib/_cjs/services/redis.js +0 -12
  177. package/lib/_cjs/services/sensitive_words.js +0 -61
  178. package/lib/_cjs/services/sms.js +0 -84
  179. package/lib/_cjs/types/dto.js +0 -3
  180. package/lib/_cjs/x.js +0 -35
  181. package/lib/cli/api_generator.d.ts +0 -74
  182. package/lib/cli/api_generator.js +0 -452
  183. package/lib/cli/build_util.d.ts +0 -17
  184. package/lib/cli/build_util.js +0 -236
  185. package/lib/cli/cli.d.ts +0 -2
  186. package/lib/cli/cli.js +0 -374
  187. package/lib/cli/css_register.js +0 -5
  188. package/lib/cli/deploy_util.d.ts +0 -23
  189. package/lib/cli/deploy_util.js +0 -70
  190. package/lib/cli/dev_util.d.ts +0 -8
  191. package/lib/cli/dev_util.js +0 -20
  192. package/lib/cli/env_util.d.ts +0 -45
  193. package/lib/cli/env_util.js +0 -246
  194. package/lib/cli/esbuild_register.js +0 -5
  195. package/lib/cli/template_util.d.ts +0 -18
  196. package/lib/cli/template_util.js +0 -95
  197. package/lib/core/ctx_storage.d.ts +0 -3
  198. package/lib/core/ctx_storage.js +0 -2
  199. package/lib/core/define_bus.d.ts +0 -37
  200. package/lib/core/define_bus.js +0 -27
  201. package/lib/core/define_cron.js +0 -9
  202. package/lib/core/define_handler.js +0 -48
  203. package/lib/core/define_hook.d.ts +0 -2
  204. package/lib/core/define_hook.js +0 -4
  205. package/lib/core/define_server.d.ts +0 -3
  206. package/lib/core/define_server.js +0 -6
  207. package/lib/core/define_task.js +0 -107
  208. package/lib/core/get_handler_url.d.ts +0 -2
  209. package/lib/core/get_handler_url.js +0 -7
  210. package/lib/core/handler.d.ts +0 -16
  211. package/lib/core/handler.js +0 -209
  212. package/lib/core/http_error.d.ts +0 -2
  213. package/lib/core/http_error.js +0 -2
  214. package/lib/core/http_header.d.ts +0 -856
  215. package/lib/core/http_header.js +0 -139
  216. package/lib/core/http_method.d.ts +0 -3
  217. package/lib/core/http_method.js +0 -8
  218. package/lib/core/http_redirect.d.ts +0 -5
  219. package/lib/core/http_redirect.js +0 -6
  220. package/lib/core/server.d.ts +0 -20
  221. package/lib/core/server.js +0 -213
  222. package/lib/core/types.d.ts +0 -265
  223. package/lib/core/types.js +0 -4
  224. package/lib/exports.d.ts +0 -45
  225. package/lib/exports.js +0 -47
  226. package/lib/index.d.ts +0 -2
  227. package/lib/index.js +0 -3
  228. package/lib/plugins/base.d.ts +0 -4
  229. package/lib/plugins/base.js +0 -1
  230. package/lib/plugins/compress.d.ts +0 -13
  231. package/lib/plugins/compress.js +0 -12
  232. package/lib/plugins/cookie.d.ts +0 -13
  233. package/lib/plugins/cookie.js +0 -12
  234. package/lib/plugins/cors.d.ts +0 -22
  235. package/lib/plugins/cors.js +0 -32
  236. package/lib/plugins/file_parser.d.ts +0 -16
  237. package/lib/plugins/file_parser.js +0 -22
  238. package/lib/plugins/form_body_parser.d.ts +0 -13
  239. package/lib/plugins/form_body_parser.js +0 -12
  240. package/lib/plugins/ws_parser.d.ts +0 -13
  241. package/lib/plugins/ws_parser.js +0 -12
  242. package/lib/plugins/xml_parser.d.ts +0 -19
  243. package/lib/plugins/xml_parser.js +0 -43
  244. package/lib/services/ai.d.ts +0 -31
  245. package/lib/services/ai.js +0 -43
  246. package/lib/services/base.d.ts +0 -4
  247. package/lib/services/base.js +0 -1
  248. package/lib/services/cache.d.ts +0 -173
  249. package/lib/services/cache.js +0 -394
  250. package/lib/services/captcha.d.ts +0 -65
  251. package/lib/services/captcha.js +0 -72
  252. package/lib/services/crypto.d.ts +0 -110
  253. package/lib/services/db_value.d.ts +0 -60
  254. package/lib/services/db_value.js +0 -72
  255. package/lib/services/dingtalk.d.ts +0 -39
  256. package/lib/services/dingtalk.js +0 -45
  257. package/lib/services/dispose.d.ts +0 -17
  258. package/lib/services/dispose.js +0 -17
  259. package/lib/services/emoji.d.ts +0 -10
  260. package/lib/services/emoji.js +0 -2029
  261. package/lib/services/file_store.d.ts +0 -49
  262. package/lib/services/file_store.js +0 -61
  263. package/lib/services/html.d.ts +0 -11
  264. package/lib/services/html.js +0 -12
  265. package/lib/services/jwt.d.ts +0 -34
  266. package/lib/services/jwt.js +0 -59
  267. package/lib/services/log.d.ts +0 -37
  268. package/lib/services/log.js +0 -102
  269. package/lib/services/mail.d.ts +0 -23
  270. package/lib/services/mail.js +0 -25
  271. package/lib/services/pay.d.ts +0 -123
  272. package/lib/services/pay.js +0 -185
  273. package/lib/services/random.d.ts +0 -27
  274. package/lib/services/random.js +0 -45
  275. package/lib/services/rate_limit.d.ts +0 -37
  276. package/lib/services/rate_limit.js +0 -49
  277. package/lib/services/redis.d.ts +0 -12
  278. package/lib/services/redis.js +0 -7
  279. package/lib/services/sensitive_words.d.ts +0 -29
  280. package/lib/services/sensitive_words.js +0 -56
  281. package/lib/services/sms.d.ts +0 -40
  282. package/lib/services/sms.js +0 -78
  283. package/lib/types/dto.d.ts +0 -86
  284. package/lib/types/dto.js +0 -1
  285. package/lib/x.d.ts +0 -17
  286. package/lib/x.js +0 -30
  287. /package/lib/{cli/css_register.d.ts → core/types.mjs} +0 -0
  288. /package/lib/{cli/esbuild_register.d.ts → plugins/base.mjs} +0 -0
@@ -1,67 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- exports.__esModule = true;
5
- exports.FileStoreService = void 0;
6
- var _clientS = require("@aws-sdk/client-s3");
7
- var _s3RequestPresigner = require("@aws-sdk/s3-request-presigner");
8
- var _xRequest = require("@jayfong/x-request");
9
- var _mime = _interopRequireDefault(require("mime"));
10
- var _vtils = require("vtils");
11
- var _x = require("../x");
12
- class FileStoreService {
13
- constructor(options) {
14
- this.options = options;
15
- this.serviceName = 'fileStore';
16
- this.endpoint = '';
17
- this.dir = '';
18
- this.cdnUrl = '';
19
- this.endpoint = (0, _vtils.isUrl)(this.options.endpoint) ? this.options.endpoint : `https://${this.options.endpoint}`;
20
- this.dir = this.options.dir ? `${this.options.dir.replace(/^\/+/, '').replace(/\/+$/, '')}` : '';
21
- this.cdnUrl = ((0, _vtils.isUrl)(this.options.cdnUrl) ? this.options.cdnUrl : `https://${this.options.cdnUrl}`).replace(/\/+$/, '');
22
- }
23
- async getUploadUrl(payload) {
24
- const s3Client = new _clientS.S3Client({
25
- credentials: {
26
- accessKeyId: this.options.accessKey,
27
- secretAccessKey: this.options.secretKey
28
- },
29
- endpoint: this.endpoint,
30
- region: 'x'
31
- });
32
- const contentType = _mime.default.getType(payload.fileName) || 'application/octet-stream';
33
- const fileName = payload.keepName ? payload.fileName : `${_x.x.random.cuid2()}.${_mime.default.getExtension(contentType)}`;
34
- const dir = this.dir ? `${this.dir}/` : '';
35
- const command = new _clientS.PutObjectCommand({
36
- Bucket: this.options.bucket,
37
- Key: `${dir}${fileName}`,
38
- ContentType: contentType
39
- });
40
- const uploadUrl = await (0, _s3RequestPresigner.getSignedUrl)(s3Client, command, {
41
- expiresIn: (0, _vtils.ms)(payload.ttl, true)
42
- });
43
- const publicUrl = `${this.cdnUrl}/${dir}${fileName}`;
44
- return {
45
- contentType,
46
- uploadUrl,
47
- publicUrl
48
- };
49
- }
50
- async upload(payload) {
51
- const res = await this.getUploadUrl({
52
- fileName: payload.fileName,
53
- ttl: (0, _vtils.ms)('1m'),
54
- keepName: payload.keepName
55
- });
56
- await _xRequest.xr.post({
57
- url: res.uploadUrl,
58
- method: 'PUT',
59
- headers: {
60
- 'Content-Type': res.contentType
61
- },
62
- data: payload.content
63
- });
64
- return res;
65
- }
66
- }
67
- exports.FileStoreService = FileStoreService;
@@ -1,17 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.HtmlService = void 0;
5
- var _fastEscapeHtml = require("fast-escape-html");
6
- class HtmlService {
7
- constructor() {
8
- this.serviceName = 'html';
9
- }
10
- escape(html) {
11
- return (0, _fastEscapeHtml.escapeHTML)(html);
12
- }
13
- unescape(html) {
14
- return (0, _fastEscapeHtml.unescapeHTML)(html);
15
- }
16
- }
17
- exports.HtmlService = HtmlService;
@@ -1,65 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- exports.__esModule = true;
5
- exports.JwtService = void 0;
6
- var _jsonwebtoken = _interopRequireDefault(require("jsonwebtoken"));
7
- var _lruCache = require("lru-cache");
8
- var _vtils = require("vtils");
9
- var _date = require("vtils/date");
10
- var _http_error = require("../core/http_error");
11
- class JwtService {
12
- constructor(options) {
13
- this.options = options;
14
- this.serviceName = 'jwt';
15
- this.cache = void 0;
16
- if (options.cache) {
17
- this.cache = new _lruCache.LRUCache(options.cache);
18
- }
19
- }
20
- sign(payload, ttl = this.options.ttl) {
21
- const token = _jsonwebtoken.default.sign(payload, this.options.secret, {
22
- expiresIn: (0, _vtils.ms)(ttl, true)
23
- });
24
- if (this.cache) {
25
- this.cache.set(token, payload, {
26
- ttl: (0, _vtils.ms)(ttl)
27
- });
28
- }
29
- return token;
30
- }
31
- async verify(token) {
32
- const data = await new Promise((resolve, reject) => {
33
- if (this.cache && this.cache.has(token)) {
34
- resolve(this.cache.get(token));
35
- } else {
36
- _jsonwebtoken.default.verify(token, this.options.secret, {
37
- ignoreExpiration: false
38
- }, (err, data) => {
39
- if (err || !data || typeof data === 'string' || !data.iat || !data.exp) {
40
- reject(new _http_error.HttpError.Unauthorized('data'));
41
- } else {
42
- data.token = token;
43
- if (this.cache) {
44
- this.cache.set(token, data, {
45
- ttl: (0, _date.differenceInMilliseconds)((0, _date.fromUnixTime)(data.exp), new Date())
46
- });
47
- }
48
- resolve(data);
49
- }
50
- });
51
- }
52
- });
53
- await this.options.onVerify?.(data);
54
- return data;
55
- }
56
- async verifyFromHttpHeaders(headers) {
57
- const authorization = headers.authorization || headers['sec-websocket-protocol'] && `Bearer ${headers['sec-websocket-protocol']}` || '';
58
- if (!authorization) {
59
- throw new _http_error.HttpError.Unauthorized('header');
60
- }
61
- const [scheme, token = scheme] = authorization.split(' ');
62
- return this.verify(token);
63
- }
64
- }
65
- exports.JwtService = JwtService;
@@ -1,108 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- exports.__esModule = true;
5
- exports.LogService = void 0;
6
- var _nodePath = _interopRequireDefault(require("node:path"));
7
- var _fsExtra = _interopRequireDefault(require("fs-extra"));
8
- var _vtils = require("vtils");
9
- var _date = require("vtils/date");
10
- var _x = require("../x");
11
- class LogService {
12
- constructor() {
13
- this.serviceName = 'log';
14
- this.getLogWriter = (0, _vtils.memoize)(logFile => {
15
- _fsExtra.default.ensureFileSync(logFile);
16
- return _fsExtra.default.createWriteStream(logFile, {
17
- flags: 'a'
18
- });
19
- }, logFile => logFile);
20
- this.info = (title, desc) => {
21
- this.log({
22
- level: 'info',
23
- title,
24
- desc
25
- });
26
- };
27
- this.success = (title, desc) => {
28
- this.log({
29
- level: 'success',
30
- title,
31
- desc
32
- });
33
- };
34
- this.error = (title, desc) => {
35
- this.log({
36
- level: 'error',
37
- title,
38
- desc
39
- });
40
- };
41
- this.console = {
42
- info: (title, desc) => {
43
- this.log({
44
- writer: 'console',
45
- level: 'info',
46
- title,
47
- desc
48
- });
49
- },
50
- success: (title, desc) => {
51
- this.log({
52
- writer: 'console',
53
- level: 'success',
54
- title,
55
- desc
56
- });
57
- },
58
- error: (title, desc) => {
59
- this.log({
60
- writer: 'console',
61
- level: 'error',
62
- title,
63
- desc
64
- });
65
- }
66
- };
67
- }
68
- getLogFile(date) {
69
- const year = date.getFullYear();
70
- const month = date.getMonth() + 1;
71
- return _nodePath.default.join(_x.x.dataDir, `log/${year}/${month < 10 ? `0${month}` : month}.log`);
72
- }
73
- get logFile() {
74
- return this.getLogFile(new Date());
75
- }
76
- parseLogLineText(text, keysMap = {}) {
77
- const segments = text.split(/\t+/);
78
- // 没有 traceId 的注入一下
79
- if (segments[1].length < 10) {
80
- segments.splice(1, 0, '');
81
- }
82
- const [time, traceId, level, title, ...desc] = segments;
83
- return {
84
- time: time,
85
- traceId: traceId,
86
- level: level,
87
- title: title,
88
- desc: desc.reduce((res, item, index) => {
89
- if (keysMap[title]) {
90
- res[keysMap[title][index]] = item;
91
- } else {
92
- const i = item.indexOf(':');
93
- res[item.substring(0, i)] = item.substring(i + 1);
94
- }
95
- return res;
96
- }, {})
97
- };
98
- }
99
- log(payload) {
100
- const getContent = () => `${[(0, _date.formatDate)(new Date(), 'yyyy-mm-dd hh:ii:ss'), ...(!_x.x.ctx ? [] : [_x.x.ctx.traceId]), payload.level, payload.title, ...(!payload.desc ? [] : Array.isArray(payload.desc) ? payload.desc : Object.keys(payload.desc).map(key => `${key}:${payload.desc[key]}`))].map(item => String(item).replace(/[\r\n\t]+/g, ' ')).join('\t')}`;
101
- if (payload.writer === 'console') {
102
- console[payload.level === 'error' ? 'error' : 'log'](getContent());
103
- } else {
104
- this.getLogWriter(this.logFile).write(`${getContent()}\n`);
105
- }
106
- }
107
- }
108
- exports.LogService = LogService;
@@ -1,31 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- exports.__esModule = true;
5
- exports.MailService = void 0;
6
- var _nodemailer = _interopRequireDefault(require("nodemailer"));
7
- var _x = require("../x");
8
- class MailService {
9
- constructor(options) {
10
- this.options = options;
11
- this.serviceName = 'mail';
12
- this.transporter = void 0;
13
- }
14
- async send(options) {
15
- if (!this.transporter) {
16
- this.transporter = _nodemailer.default.createTransport({
17
- host: this.options.host,
18
- port: this.options.port,
19
- secure: this.options.secure,
20
- auth: {
21
- user: this.options.user,
22
- pass: this.options.pass
23
- }
24
- });
25
- await this.transporter.verify();
26
- _x.x.dispose.add(() => this.transporter.close());
27
- }
28
- return this.transporter.sendMail(options);
29
- }
30
- }
31
- exports.MailService = MailService;
@@ -1,191 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- exports.__esModule = true;
5
- exports.PayService = void 0;
6
- var _nodeCrypto = _interopRequireDefault(require("node:crypto"));
7
- var _alipaySdk = _interopRequireDefault(require("alipay-sdk"));
8
- var _form = _interopRequireDefault(require("alipay-sdk/lib/form"));
9
- var _got = _interopRequireDefault(require("got"));
10
- var _http_error = require("../core/http_error");
11
- class PayService {
12
- constructor(options) {
13
- this.options = options;
14
- this.serviceName = 'pay';
15
- this.alipaySdk = void 0;
16
- }
17
- async prepareAlipay(options) {
18
- if (!this.alipaySdk) {
19
- this.alipaySdk = new _alipaySdk.default({
20
- appId: this.options.alipay.appId,
21
- privateKey: this.options.alipay.privateKey,
22
- alipayPublicKey: this.options.alipay.publicKey
23
- });
24
- }
25
- const formData = new _form.default();
26
- formData.setMethod('get');
27
- formData.addField('notifyUrl', options.notifyUrl);
28
- if (options.returnUrl) {
29
- formData.addField('returnUrl', options.returnUrl);
30
- }
31
- formData.addField('bizContent', {
32
- outTradeNo: options.tradeNumber,
33
- productCode: 'FAST_INSTANT_TRADE_PAY',
34
- totalAmount: options.totalMoney,
35
- subject: options.goodsName,
36
- goodsType: '0',
37
- passbackParams: 'alipay'
38
- });
39
- const payUrl = await this.alipaySdk.exec('alipay.trade.page.pay', {}, {
40
- formData: formData
41
- });
42
- return {
43
- payUrl: payUrl
44
- };
45
- }
46
- async prepareWepay(options) {
47
- const res = await this.wepayRequest('https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi', {
48
- appid: this.options.wepay.appId,
49
- mchid: this.options.wepay.merchantId,
50
- description: options.goodsName,
51
- out_trade_no: options.tradeNumber,
52
- attach: 'wepay',
53
- notify_url: options.notifyUrl,
54
- amount: {
55
- total: options.totalMoney * 100,
56
- currency: 'CNY'
57
- },
58
- payer: {
59
- openid: options.openid
60
- }
61
- });
62
- if (!res || !res.prepay_id) {
63
- const error = res && res.message || '支付错误';
64
- throw new Error(error);
65
- }
66
- const params = {
67
- appId: this.options.wepay.appId,
68
- timestamp: String(Math.round(Date.now() / 1000)),
69
- nonceStr: Math.random().toString().substr(2, 12),
70
- package: `prepay_id=${res.prepay_id}`,
71
- signType: 'RSA',
72
- paySign: ''
73
- };
74
- params.paySign = this.wepaySign([params.appId, params.timestamp, params.nonceStr, params.package]);
75
- return {
76
- payParams: params
77
- };
78
- }
79
- verifyNotifyData(data) {
80
- try {
81
- if (!data || typeof data !== 'object') {
82
- return false;
83
- }
84
-
85
- // 支付宝
86
- // https://opendocs.alipay.com/open/270/105902
87
- if (data.passback_params === 'alipay') {
88
- if (!this.alipaySdk?.checkNotifySign(data)) {
89
- return false;
90
- }
91
- return {
92
- channelOrderNo: data.trade_no
93
- };
94
- }
95
-
96
- // 微信支付
97
- // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_5.shtml
98
- if (data.resource) {
99
- const params = JSON.parse(this.wepayDecrypt(data.resource));
100
- if (params.attach === 'wepay') {
101
- return {
102
- channelOrderNo: params.transaction_id
103
- };
104
- }
105
- return false;
106
- }
107
- return false;
108
- } catch {
109
- return false;
110
- }
111
- }
112
- verifyNotifyDataOrFail(data, message) {
113
- const res = this.verifyNotifyData(data);
114
- if (!res) {
115
- throw new _http_error.HttpError.BadRequest(message);
116
- }
117
- return res;
118
- }
119
- async getOrderInfo(payload) {
120
- // 微信支付
121
- // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_2.shtml
122
- if (payload.channel === 'wepay') {
123
- const res = await this.wepayRequest(payload.orderNo ? `https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/${payload.orderNo}?mchid=${this.options.wepay.merchantId}` : `https://api.mch.weixin.qq.com/v3/pay/transactions/id/${payload.channelOrderNo}?mchid=${this.options.wepay.merchantId}`);
124
- return {
125
- channelOrderNo: res.transaction_id,
126
- orderNo: res.out_trade_no,
127
- status: res.trade_state === 'SUCCESS' ? 'success' : 'fail'
128
- };
129
- }
130
-
131
- // 支付宝
132
- // https://opendocs.alipay.com/open/028woa?scene=common&pathHash=dbf247eb
133
- const res = await this.alipaySdk.exec('alipay.trade.query', {
134
- biz_content: payload.orderNo ? {
135
- out_trade_no: payload.orderNo
136
- } : {
137
- trade_no: payload.channelOrderNo
138
- }
139
- });
140
- return {
141
- channelOrderNo: res.trade_no,
142
- orderNo: res.out_trade_no,
143
- status: res.trade_status === 'TRADE_SUCCESS' || res.trade_status === 'TRADE_FINISHED' ? 'success' : 'fail'
144
- };
145
- }
146
- wepaySign(data) {
147
- return _nodeCrypto.default.createSign('RSA-SHA256').update(data.map(v => `${v}\n`).join('')).sign(this.options.wepay.privateKey, 'base64');
148
- }
149
- wepayDecrypt(payload) {
150
- const ciphertextBuffer = Buffer.from(payload.ciphertext, 'base64');
151
- const authTag = ciphertextBuffer.slice(ciphertextBuffer.length - 16);
152
- const data = ciphertextBuffer.slice(0, ciphertextBuffer.length - 16);
153
- const decipherIv = _nodeCrypto.default.createDecipheriv('aes-256-gcm', this.options.wepay.secretKey, payload.nonce);
154
- decipherIv.setAuthTag(Buffer.from(authTag));
155
- decipherIv.setAAD(Buffer.from(payload.associated_data));
156
- const decryptStr = decipherIv.update(data, undefined, 'utf8');
157
- decipherIv.final();
158
- return decryptStr;
159
- }
160
- async wepayRequest(url, data) {
161
- const path = url.replace(/^https?:\/\/[^/]+/, '');
162
- const method = data == null ? 'GET' : 'POST';
163
- const body = method === 'POST' ? JSON.stringify(data) : '';
164
- const params = {
165
- method: method,
166
- url: path,
167
- time: String(Math.round(Date.now() / 1000)),
168
- rand: Math.random().toString().substr(2, 12),
169
- body: body,
170
- signature: ''
171
- };
172
- params.signature = this.wepaySign([params.method, params.url, params.time, params.rand, params.body]);
173
- const Authorization = [`WECHATPAY2-SHA256-RSA2048 `, `mchid="${this.options.wepay.merchantId}",`, `nonce_str="${params.rand}",`, `signature="${params.signature}",`, `timestamp="${params.time}",`, `serial_no="${this.options.wepay.certificateSerialNumber}"`].join('');
174
- const res = method === 'POST' ? await _got.default.post(url, {
175
- json: data,
176
- headers: {
177
- Authorization
178
- },
179
- responseType: 'json',
180
- resolveBodyOnly: true
181
- }) : await _got.default.get(url, {
182
- headers: {
183
- Authorization
184
- },
185
- responseType: 'json',
186
- resolveBodyOnly: true
187
- });
188
- return res;
189
- }
190
- }
191
- exports.PayService = PayService;
@@ -1,51 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- exports.__esModule = true;
5
- exports.RandomService = void 0;
6
- var _cuid = require("@paralleldrive/cuid2");
7
- var _randomstring = _interopRequireDefault(require("randomstring"));
8
- class RandomService {
9
- constructor() {
10
- this.serviceName = 'random';
11
- }
12
- /**
13
- * 24位。
14
- *
15
- * @see https://github.com/paralleldrive/cuid2
16
- */
17
- cuid2() {
18
- return (0, _cuid.createId)();
19
- }
20
-
21
- /**
22
- * [0-9 a-z A-Z]
23
- */
24
- generateAlphanumeric(length) {
25
- return _randomstring.default.generate({
26
- charset: 'alphanumeric',
27
- length: length
28
- });
29
- }
30
-
31
- /**
32
- * [a-z A-Z]
33
- */
34
- generateAlphabetic(length) {
35
- return _randomstring.default.generate({
36
- charset: 'alphabetic',
37
- length: length
38
- });
39
- }
40
-
41
- /**
42
- * [0-9]
43
- */
44
- generateNumeric(length) {
45
- return _randomstring.default.generate({
46
- charset: 'numeric',
47
- length: length
48
- });
49
- }
50
- }
51
- exports.RandomService = RandomService;
@@ -1,54 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.RateLimitService = void 0;
5
- var _vtils = require("vtils");
6
- var _http_error = require("../core/http_error");
7
- var _x = require("../x");
8
- class RateLimitService {
9
- constructor() {
10
- this.serviceName = 'rateLimit';
11
- }
12
- async limitByCount(options) {
13
- const cacheKey = `rateLimit_${options.key}`;
14
- const remainingCount = await _x.x.cache.get(cacheKey);
15
- if (remainingCount == null) {
16
- await _x.x.cache.set(cacheKey, options.count, options.ttl);
17
- return options.count;
18
- }
19
- if (remainingCount === 0) {
20
- return 0;
21
- }
22
- await _x.x.cache.decrease(cacheKey);
23
- return remainingCount - 1;
24
- }
25
- async limitByCountOrFail(options) {
26
- const count = await this.limitByCount(options);
27
- if (count === 0) {
28
- throw new _http_error.HttpError.Forbidden(options.message);
29
- }
30
- return count;
31
- }
32
- async limitByManyCount(options) {
33
- for (let i = 0; i < options.limits.length; i++) {
34
- const item = options.limits[i];
35
- const ttl = (0, _vtils.ms)(item.ttl);
36
- const remainingCount = await this.limitByCount({
37
- key: `${options.key}_${ttl}`,
38
- ttl: ttl,
39
- count: item.count
40
- });
41
- if (remainingCount === 0) {
42
- return i;
43
- }
44
- }
45
- return true;
46
- }
47
- async limitByManyCountOrFail(options) {
48
- const pass = await this.limitByManyCount(options);
49
- if (pass !== true) {
50
- throw new _http_error.HttpError.Forbidden(options.limits[pass].message ?? options.message);
51
- }
52
- }
53
- }
54
- exports.RateLimitService = RateLimitService;
@@ -1,12 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.RedisService = void 0;
5
- var _ioredis = require("ioredis");
6
- class RedisService extends _ioredis.Redis {
7
- constructor(...args) {
8
- super(...args);
9
- this.serviceName = 'redis';
10
- }
11
- }
12
- exports.RedisService = RedisService;
@@ -1,61 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.SensitiveWordsService = void 0;
5
- var _vtils = require("vtils");
6
- var _regexp = require("vtils/regexp");
7
- const phoneNumberRegExp = _regexp.phoneNumberRegExpBuilder.build();
8
- const toRegExp = (0, _vtils.memoize)(re => new RegExp(re.substring(1, re.length - 1)), re => re);
9
-
10
- /**
11
- * 敏感词服务。
12
- */
13
- class SensitiveWordsService {
14
- constructor(options) {
15
- this.serviceName = 'sensitiveWords';
16
- this.sensitiveWords = [];
17
- this.sensitiveWords = (0, _vtils.uniq)(options.words.map(word => word.toLowerCase()));
18
- }
19
-
20
- /**
21
- * 文本转换。
22
- */
23
- transform(text) {
24
- return (
25
- // 移除空白字符
26
- (0, _vtils.removeBlankChars)(
27
- // 移除非单词字符
28
- (0, _vtils.removeNonWordChars)(
29
- // 全角转半角
30
- (0, _vtils.toHalfWidthString)(text)))
31
- // 转小写
32
- .toLowerCase()
33
- // 叠词归一
34
- // 排除字母数字以支持qq、手机号等场景
35
- .replace(/([^a-zA-Z0-9])\1+/g, '$1')
36
- );
37
- }
38
-
39
- /**
40
- * 验证文本是否包含敏感词。
41
- */
42
- async validate(text, every) {
43
- text = this.transform(text);
44
- const words = [];
45
- for (const word of this.sensitiveWords) {
46
- if (
47
- // 支持 <手机号>
48
- word === '<手机号>' ? phoneNumberRegExp.test(text) :
49
- // 支持正则
50
- word[0] === '/' && word[word.length - 1] === '/' ? toRegExp(word).test(text) : text.includes(word)) {
51
- words.push(word);
52
- if (!every) break;
53
- }
54
- }
55
- return {
56
- pass: !words.length,
57
- words: words
58
- };
59
- }
60
- }
61
- exports.SensitiveWordsService = SensitiveWordsService;