@xrystal/core 3.32.1 → 3.37.3

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 (262) hide show
  1. package/README.md +651 -136
  2. package/package.json +27 -24
  3. package/tsconfig.base.json +15 -0
  4. package/x/bin/commands/create.mjs +34 -5
  5. package/x/bin/commands/doctor.mjs +115 -25
  6. package/x/bin/commands/hooks.mjs +55 -0
  7. package/x/bin/commands/project.mjs +75 -42
  8. package/x/bin/commands/release.mjs +8 -3
  9. package/x/bin/commands/sync-toolchain.mjs +43 -0
  10. package/x/bin/commands/tmp.mjs +13 -4
  11. package/x/bin/helpers/.generated/.generated-from +1 -0
  12. package/x/bin/helpers/.generated/tmp-schema.mjs +192 -0
  13. package/x/bin/helpers/banner.mjs +66 -12
  14. package/x/bin/helpers/build-config.mjs +342 -0
  15. package/x/bin/helpers/cli-help.mjs +164 -0
  16. package/x/bin/helpers/create-target.mjs +18 -2
  17. package/x/bin/helpers/project-artifacts.mjs +140 -0
  18. package/x/bin/helpers/runtime-info.mjs +172 -0
  19. package/x/bin/helpers/tmp-config.mjs +11 -10
  20. package/x/bin/helpers/tmp-layout.mjs +10 -16
  21. package/x/bin/helpers/tmp-schema.mjs +9 -0
  22. package/x/bin/helpers/toolchain-config.mjs +233 -0
  23. package/x/bin/main-cli.js +31 -3
  24. package/x/bin/scripts/clean-source-types.mjs +19 -0
  25. package/x/bin/scripts/fix-dist-imports.mjs +80 -0
  26. package/x/bin/scripts/install-git-hooks.mjs +86 -0
  27. package/x/bin/scripts/minify-dist.mjs +50 -0
  28. package/x/bin/scripts/prepare-npm-publish.mjs +49 -0
  29. package/x/bin/scripts/unpublish-leaked-versions.mjs +62 -0
  30. package/x/bin/scripts/verify-npm-pack.mjs +45 -0
  31. package/x/bin/scripts/verify-version-bump.mjs +27 -0
  32. package/x/bin/scripts/version-check.mjs +173 -0
  33. package/x/dist/index.d.ts +3 -0
  34. package/x/dist/index.js +1 -0
  35. package/x/dist/loader/clients/index.js +1 -0
  36. package/x/dist/loader/configs/index.js +1 -0
  37. package/{source → x/dist}/loader/controller/index.d.ts +20 -17
  38. package/x/dist/loader/controller/index.js +1 -0
  39. package/x/dist/loader/dto/index.js +1 -0
  40. package/x/dist/loader/events/index.js +1 -0
  41. package/x/dist/loader/index.d.ts +11 -0
  42. package/x/dist/loader/index.js +1 -0
  43. package/{source → x/dist}/loader/kafka/index.d.ts +1 -0
  44. package/x/dist/loader/kafka/index.js +1 -0
  45. package/x/dist/loader/localizations/index.js +1 -0
  46. package/{source → x/dist}/loader/logger/index.d.ts +1 -0
  47. package/x/dist/loader/logger/index.js +2 -0
  48. package/x/dist/loader/service/index.js +1 -0
  49. package/x/dist/loader/system/index.js +1 -0
  50. package/x/dist/project/index.js +1 -0
  51. package/x/dist/utils/constants/defaults.json +44 -0
  52. package/x/dist/utils/constants/index.js +1 -0
  53. package/x/dist/utils/helpers/configs/index.js +1 -0
  54. package/x/dist/utils/helpers/context/controller-store.js +1 -0
  55. package/x/dist/utils/helpers/context/index.js +1 -0
  56. package/{source → x/dist}/utils/helpers/core/index.d.ts +1 -1
  57. package/x/dist/utils/helpers/core/index.js +1 -0
  58. package/x/dist/utils/helpers/core/paths.js +1 -0
  59. package/x/dist/utils/helpers/core/tmp-layout.js +1 -0
  60. package/x/dist/utils/helpers/date/index.js +1 -0
  61. package/x/dist/utils/helpers/dispatch/index.js +1 -0
  62. package/x/dist/utils/helpers/dto/index.js +1 -0
  63. package/x/dist/utils/helpers/filters/index.js +1 -0
  64. package/x/dist/utils/helpers/framework/index.js +1 -0
  65. package/x/dist/utils/helpers/handlers/adapters.js +1 -0
  66. package/x/dist/utils/helpers/handlers/execute.js +1 -0
  67. package/x/dist/utils/helpers/handlers/index.js +1 -0
  68. package/x/dist/utils/helpers/hash/crypto.js +1 -0
  69. package/x/dist/utils/helpers/id/index.js +1 -0
  70. package/x/dist/utils/helpers/index.js +1 -0
  71. package/x/dist/utils/helpers/ip/index.js +1 -0
  72. package/x/dist/utils/helpers/is/index.js +1 -0
  73. package/x/dist/utils/helpers/locales/index.js +1 -0
  74. package/x/dist/utils/helpers/math/index.js +1 -0
  75. package/{source → x/dist}/utils/helpers/middleware/index.d.ts +2 -2
  76. package/x/dist/utils/helpers/middleware/index.js +1 -0
  77. package/x/dist/utils/helpers/objects/index.js +1 -0
  78. package/x/dist/utils/helpers/path/index.js +1 -0
  79. package/{source → x/dist}/utils/helpers/protocol/index.d.ts +2 -10
  80. package/x/dist/utils/helpers/protocol/index.js +1 -0
  81. package/x/dist/utils/helpers/protocol/options.js +1 -0
  82. package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +1 -0
  83. package/x/dist/utils/helpers/runtime/dto-access.js +1 -0
  84. package/x/dist/utils/helpers/runtime/dto-types.js +1 -0
  85. package/{source → x/dist}/utils/helpers/runtime/index.d.ts +1 -0
  86. package/x/dist/utils/helpers/runtime/index.js +1 -0
  87. package/x/dist/utils/helpers/runtime/shutdown.d.ts +3 -0
  88. package/x/dist/utils/helpers/runtime/shutdown.js +1 -0
  89. package/x/dist/utils/helpers/state/index.js +1 -0
  90. package/x/dist/utils/helpers/state/props-from-tmp.js +1 -0
  91. package/x/dist/utils/helpers/state/request-key-guard.js +1 -0
  92. package/x/dist/utils/helpers/state/scopes.js +1 -0
  93. package/x/dist/utils/helpers/string/index.js +1 -0
  94. package/x/dist/utils/helpers/tests/tmp-schema.test.js +1 -0
  95. package/x/dist/utils/helpers/tests/tmp-watch.test.js +1 -0
  96. package/x/dist/utils/helpers/timer/index.js +1 -0
  97. package/x/dist/utils/helpers/tmp/index.d.ts +5 -0
  98. package/x/dist/utils/helpers/tmp/index.js +1 -0
  99. package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -0
  100. package/{source → x/dist}/utils/helpers/tmp/runtime-tmp.d.ts +2 -6
  101. package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -0
  102. package/{source → x/dist}/utils/helpers/tmp/tmp-loader.d.ts +1 -0
  103. package/x/dist/utils/helpers/tmp/tmp-loader.js +1 -0
  104. package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +47 -0
  105. package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -0
  106. package/x/dist/utils/helpers/tmp/tmp-watch.d.ts +1 -0
  107. package/x/dist/utils/helpers/tmp/tmp-watch.js +1 -0
  108. package/x/dist/utils/helpers/validates/index.js +1 -0
  109. package/x/dist/utils/index.js +1 -0
  110. package/x/dist/utils/models/classes/class.clients.js +1 -0
  111. package/x/dist/utils/models/classes/class.interfaces.js +1 -0
  112. package/x/dist/utils/models/classes/class.service-locator.js +1 -0
  113. package/{source → x/dist}/utils/models/classes/class.tmp-file-loader.d.ts +3 -2
  114. package/x/dist/utils/models/classes/class.tmp-file-loader.js +1 -0
  115. package/x/dist/utils/models/classes/class.x.js +1 -0
  116. package/x/dist/utils/models/enums/index.js +1 -0
  117. package/x/dist/utils/models/index.js +1 -0
  118. package/x/dist/utils/models/types/index.js +1 -0
  119. package/x/dist/utils/package-root.js +1 -0
  120. package/x/tmp.yml +51 -42
  121. package/source/index.js +0 -11
  122. package/source/loader/clients/index.js +0 -22
  123. package/source/loader/configs/index.js +0 -88
  124. package/source/loader/controller/index.js +0 -236
  125. package/source/loader/dto/index.js +0 -92
  126. package/source/loader/events/index.js +0 -44
  127. package/source/loader/index.d.ts +0 -11
  128. package/source/loader/index.js +0 -11
  129. package/source/loader/kafka/index.js +0 -137
  130. package/source/loader/localizations/index.js +0 -46
  131. package/source/loader/logger/index.js +0 -217
  132. package/source/loader/service/index.js +0 -7
  133. package/source/loader/system/index.js +0 -25
  134. package/source/project/index.js +0 -70
  135. package/source/utils/constants/defaults.json +0 -15
  136. package/source/utils/constants/defaults.mjs +0 -10
  137. package/source/utils/constants/index.js +0 -22
  138. package/source/utils/helpers/configs/index.js +0 -1
  139. package/source/utils/helpers/context/controller-store.js +0 -12
  140. package/source/utils/helpers/context/index.js +0 -24
  141. package/source/utils/helpers/core/index.js +0 -58
  142. package/source/utils/helpers/core/paths.js +0 -78
  143. package/source/utils/helpers/core/tmp-layout.js +0 -241
  144. package/source/utils/helpers/date/index.js +0 -48
  145. package/source/utils/helpers/dispatch/index.js +0 -53
  146. package/source/utils/helpers/dto/index.js +0 -10
  147. package/source/utils/helpers/filters/index.js +0 -44
  148. package/source/utils/helpers/framework/index.js +0 -17
  149. package/source/utils/helpers/handlers/adapters.js +0 -40
  150. package/source/utils/helpers/handlers/execute.js +0 -82
  151. package/source/utils/helpers/handlers/index.js +0 -31
  152. package/source/utils/helpers/hash/crypto.js +0 -22
  153. package/source/utils/helpers/id/index.js +0 -24
  154. package/source/utils/helpers/index.js +0 -26
  155. package/source/utils/helpers/ip/index.js +0 -21
  156. package/source/utils/helpers/is/index.js +0 -35
  157. package/source/utils/helpers/locales/index.js +0 -82
  158. package/source/utils/helpers/math/index.js +0 -14
  159. package/source/utils/helpers/middleware/index.js +0 -36
  160. package/source/utils/helpers/objects/index.js +0 -55
  161. package/source/utils/helpers/path/index.js +0 -4
  162. package/source/utils/helpers/protocol/index.js +0 -99
  163. package/source/utils/helpers/protocol/options.js +0 -13
  164. package/source/utils/helpers/regex/checkSpecialRegexControl.js +0 -3
  165. package/source/utils/helpers/runtime/dto-access.js +0 -5
  166. package/source/utils/helpers/runtime/index.js +0 -1
  167. package/source/utils/helpers/state/index.js +0 -185
  168. package/source/utils/helpers/state/props-from-tmp.js +0 -44
  169. package/source/utils/helpers/state/request-key-guard.js +0 -42
  170. package/source/utils/helpers/state/scopes.js +0 -69
  171. package/source/utils/helpers/string/index.js +0 -9
  172. package/source/utils/helpers/timer/index.js +0 -5
  173. package/source/utils/helpers/tmp/index.d.ts +0 -3
  174. package/source/utils/helpers/tmp/index.js +0 -3
  175. package/source/utils/helpers/tmp/loader-tmp-sync.js +0 -13
  176. package/source/utils/helpers/tmp/runtime-tmp.js +0 -30
  177. package/source/utils/helpers/tmp/tmp-loader.js +0 -48
  178. package/source/utils/helpers/validates/index.js +0 -20
  179. package/source/utils/index.js +0 -3
  180. package/source/utils/models/classes/class.clients.js +0 -142
  181. package/source/utils/models/classes/class.interfaces.js +0 -10
  182. package/source/utils/models/classes/class.service-locator.js +0 -16
  183. package/source/utils/models/classes/class.tmp-file-loader.js +0 -38
  184. package/source/utils/models/classes/class.x.js +0 -180
  185. package/source/utils/models/enums/index.js +0 -148
  186. package/source/utils/models/index.js +0 -9
  187. package/source/utils/models/types/index.js +0 -2
  188. package/source/utils/models/types/shims.d.ts +0 -123
  189. package/source/utils/package-root.js +0 -5
  190. package/x/tests/cli.test.ts +0 -85
  191. package/x/tests/context.test.ts +0 -25
  192. package/x/tests/dispatch.test.ts +0 -84
  193. package/x/tests/fixtures/locales/en/translation.json +0 -8
  194. package/x/tests/fixtures/locales/tr/translation.json +0 -8
  195. package/x/tests/frameworks.integration.test.ts +0 -185
  196. package/x/tests/helpers/i18n-setup.ts +0 -52
  197. package/x/tests/helpers/middleware.ts +0 -23
  198. package/x/tests/helpers/register-test-dto.ts +0 -52
  199. package/x/tests/i18n.integration.test.ts +0 -77
  200. package/x/tests/i18n.test.ts +0 -96
  201. package/x/tests/middleware.test.ts +0 -83
  202. package/x/tests/project-layout.test.ts +0 -65
  203. package/x/tests/protocol.test.ts +0 -75
  204. package/x/tests/realtime.examples.test.ts +0 -198
  205. package/x/tests/runtime-tmp.test.ts +0 -49
  206. package/x/tests/socket.integration.test.ts +0 -174
  207. package/x/tests/state.test.ts +0 -183
  208. package/x/tests/tmp-layout-guard.test.ts +0 -40
  209. /package/{source → x/dist}/loader/clients/index.d.ts +0 -0
  210. /package/{source → x/dist}/loader/configs/index.d.ts +0 -0
  211. /package/{source → x/dist}/loader/dto/index.d.ts +0 -0
  212. /package/{source → x/dist}/loader/events/index.d.ts +0 -0
  213. /package/{source → x/dist}/loader/localizations/index.d.ts +0 -0
  214. /package/{source → x/dist}/loader/service/index.d.ts +0 -0
  215. /package/{source → x/dist}/loader/system/index.d.ts +0 -0
  216. /package/{source → x/dist}/project/index.d.ts +0 -0
  217. /package/{source → x/dist}/utils/constants/index.d.ts +0 -0
  218. /package/{source → x/dist}/utils/helpers/configs/index.d.ts +0 -0
  219. /package/{source → x/dist}/utils/helpers/context/controller-store.d.ts +0 -0
  220. /package/{source → x/dist}/utils/helpers/context/index.d.ts +0 -0
  221. /package/{source → x/dist}/utils/helpers/core/paths.d.ts +0 -0
  222. /package/{source → x/dist}/utils/helpers/core/tmp-layout.d.ts +0 -0
  223. /package/{source → x/dist}/utils/helpers/date/index.d.ts +0 -0
  224. /package/{source → x/dist}/utils/helpers/dispatch/index.d.ts +0 -0
  225. /package/{source → x/dist}/utils/helpers/dto/index.d.ts +0 -0
  226. /package/{source → x/dist}/utils/helpers/filters/index.d.ts +0 -0
  227. /package/{source → x/dist}/utils/helpers/framework/index.d.ts +0 -0
  228. /package/{source → x/dist}/utils/helpers/handlers/adapters.d.ts +0 -0
  229. /package/{source → x/dist}/utils/helpers/handlers/execute.d.ts +0 -0
  230. /package/{source → x/dist}/utils/helpers/handlers/index.d.ts +0 -0
  231. /package/{source → x/dist}/utils/helpers/hash/crypto.d.ts +0 -0
  232. /package/{source → x/dist}/utils/helpers/id/index.d.ts +0 -0
  233. /package/{source → x/dist}/utils/helpers/index.d.ts +0 -0
  234. /package/{source → x/dist}/utils/helpers/ip/index.d.ts +0 -0
  235. /package/{source → x/dist}/utils/helpers/is/index.d.ts +0 -0
  236. /package/{source → x/dist}/utils/helpers/locales/index.d.ts +0 -0
  237. /package/{source → x/dist}/utils/helpers/math/index.d.ts +0 -0
  238. /package/{source → x/dist}/utils/helpers/objects/index.d.ts +0 -0
  239. /package/{source → x/dist}/utils/helpers/path/index.d.ts +0 -0
  240. /package/{source → x/dist}/utils/helpers/protocol/options.d.ts +0 -0
  241. /package/{source → x/dist}/utils/helpers/regex/checkSpecialRegexControl.d.ts +0 -0
  242. /package/{source → x/dist}/utils/helpers/runtime/dto-access.d.ts +0 -0
  243. /package/{source → x/dist}/utils/helpers/runtime/dto-types.d.ts +0 -0
  244. /package/{source → x/dist}/utils/helpers/state/index.d.ts +0 -0
  245. /package/{source → x/dist}/utils/helpers/state/props-from-tmp.d.ts +0 -0
  246. /package/{source → x/dist}/utils/helpers/state/request-key-guard.d.ts +0 -0
  247. /package/{source → x/dist}/utils/helpers/state/scopes.d.ts +0 -0
  248. /package/{source → x/dist}/utils/helpers/string/index.d.ts +0 -0
  249. /package/{source/index.d.ts → x/dist/utils/helpers/tests/tmp-schema.test.d.ts} +0 -0
  250. /package/{source/utils/helpers/runtime/dto-types.js → x/dist/utils/helpers/tests/tmp-watch.test.d.ts} +0 -0
  251. /package/{source → x/dist}/utils/helpers/timer/index.d.ts +0 -0
  252. /package/{source → x/dist}/utils/helpers/tmp/loader-tmp-sync.d.ts +0 -0
  253. /package/{source → x/dist}/utils/helpers/validates/index.d.ts +0 -0
  254. /package/{source → x/dist}/utils/index.d.ts +0 -0
  255. /package/{source → x/dist}/utils/models/classes/class.clients.d.ts +0 -0
  256. /package/{source → x/dist}/utils/models/classes/class.interfaces.d.ts +0 -0
  257. /package/{source → x/dist}/utils/models/classes/class.service-locator.d.ts +0 -0
  258. /package/{source → x/dist}/utils/models/classes/class.x.d.ts +0 -0
  259. /package/{source → x/dist}/utils/models/enums/index.d.ts +0 -0
  260. /package/{source → x/dist}/utils/models/index.d.ts +0 -0
  261. /package/{source → x/dist}/utils/models/types/index.d.ts +0 -0
  262. /package/{source → x/dist}/utils/package-root.d.ts +0 -0
@@ -1,137 +0,0 @@
1
- import { Kafka as KafkaClient, logLevel } from "kafkajs";
2
- import { bindLoaderTmpSync } from '../../utils';
3
- export default class KafkaForCore {
4
- _instance;
5
- _producer;
6
- clientId = "";
7
- brokers = "";
8
- username = null;
9
- password = null;
10
- #system;
11
- #configs;
12
- constructor({ system, configs, }) {
13
- this.#system = system;
14
- this.#configs = configs;
15
- }
16
- onInit = async () => {
17
- await this.syncFromTmp();
18
- bindLoaderTmpSync(this);
19
- };
20
- syncFromTmp = async () => {
21
- await this.teardownKafka();
22
- this.clientId = this.#configs.all?.kafkaClientId;
23
- this.brokers = this.#configs.all?.kafkaBrokers;
24
- this.username = this.#configs.all?.kafkaUsername;
25
- this.password = this.#configs.all?.kafkaPassword;
26
- if (this.#configs.all.isKafkaPassive) {
27
- return;
28
- }
29
- const brokersArray = (Array.isArray(this.brokers) ? this.brokers : (this.brokers?.split(',') ?? []))
30
- .map(b => b?.trim())
31
- .filter(Boolean);
32
- if (brokersArray.length === 0) {
33
- throw new Error('Broker list error');
34
- }
35
- await this.kafkaLoader({
36
- clientId: this.clientId,
37
- brokers: brokersArray,
38
- username: this.username,
39
- password: this.password,
40
- });
41
- await this.initializeKafkaInfrastructure();
42
- };
43
- teardownKafka = async () => {
44
- if (this._producer) {
45
- try {
46
- await this._producer.disconnect();
47
- }
48
- catch { }
49
- this._producer = undefined;
50
- }
51
- };
52
- kafkaLoader = async ({ clientId, brokers, username, password }) => {
53
- const kafkaConfig = {
54
- clientId,
55
- brokers,
56
- sasl: (username && password) ? { mechanism: 'plain', username, password } : undefined,
57
- ssl: false,
58
- logLevel: logLevel.ERROR,
59
- logCreator: () => {
60
- return ({ level, log }) => {
61
- console.error(`Kafka ${log.message}`);
62
- };
63
- },
64
- retry: {
65
- initialRetryTime: 100,
66
- retries: 8
67
- }
68
- };
69
- try {
70
- const kafka = new KafkaClient(kafkaConfig);
71
- this._instance = kafka;
72
- this._producer = kafka.producer();
73
- await this.producer.connect();
74
- return kafka;
75
- }
76
- catch (error) {
77
- console.error(`Kafka ${error}`);
78
- }
79
- };
80
- initializeKafkaInfrastructure = async () => {
81
- const { kafkaBrokers, kafkaTopics, isKafkaPassive, } = {
82
- isKafkaPassive: process.env.IS_KAFKA_PASSIVE === 'true' ? true : false,
83
- kafkaBrokers: process.env?.KAFKA_BROKERS,
84
- kafkaTopics: [
85
- ...new Set([
86
- ...this.#configs.all.kafkaTopics
87
- ])
88
- ],
89
- };
90
- if (isKafkaPassive === true || !kafkaBrokers) {
91
- return;
92
- }
93
- const topicsToCreate = Array.isArray(kafkaTopics) ? kafkaTopics : [];
94
- if (topicsToCreate.length === 0)
95
- return;
96
- const admin = this._instance.admin();
97
- try {
98
- await admin.connect();
99
- const existingTopics = await admin.listTopics();
100
- const newTopics = topicsToCreate
101
- .filter(topic => !existingTopics.includes(topic))
102
- .map(topic => ({
103
- topic,
104
- numPartitions: 1,
105
- replicationFactor: 1
106
- }));
107
- if (newTopics.length > 0) {
108
- await admin.createTopics({
109
- waitForLeaders: true,
110
- topics: newTopics
111
- });
112
- }
113
- }
114
- catch (error) {
115
- //console.log('Core kafka error', error)
116
- }
117
- finally {
118
- await admin.disconnect();
119
- }
120
- };
121
- // => Helpers
122
- sendMessage = async (topic, message) => {
123
- if (!this.producer)
124
- throw new Error("Producer not ready");
125
- await this.producer.send({
126
- topic,
127
- messages: [{ value: JSON.stringify(message) }],
128
- acks: 0
129
- });
130
- };
131
- get producer() {
132
- return this._producer;
133
- }
134
- get instance() {
135
- return this._instance;
136
- }
137
- }
@@ -1,46 +0,0 @@
1
- import path from "path";
2
- import i18next from "i18next";
3
- import Backend from 'i18next-fs-backend';
4
- import * as middleware from 'i18next-http-middleware';
5
- import { bindLoaderTmpSync } from '../../utils';
6
- export default class Localizations {
7
- _instance = null;
8
- #system;
9
- #configs;
10
- constructor({ system, configs, }) {
11
- this.#system = system;
12
- this.#configs = configs;
13
- }
14
- onInit = async () => {
15
- await this.syncFromTmp();
16
- bindLoaderTmpSync(this);
17
- };
18
- syncFromTmp = async () => {
19
- this._instance = null;
20
- const localization = this.#system.tmp.configs.loaders.localization;
21
- this.i18next({
22
- loadPath: path.join(this.#system.tmp.configs.rootFolderPath, localization.loadPath),
23
- fallbackLang: localization.fallbackLang,
24
- preloadLang: localization.preloadLangs,
25
- });
26
- };
27
- i18next = ({ loadPath, fallbackLang, preloadLang, }) => {
28
- if (this._instance) {
29
- return this._instance;
30
- }
31
- i18next
32
- .use(Backend)
33
- .use(middleware.LanguageDetector)
34
- .init({
35
- fallbackLng: fallbackLang,
36
- preload: preloadLang,
37
- backend: { loadPath: `${loadPath}/{{lng}}.json` }
38
- });
39
- if (i18next)
40
- this._instance = i18next;
41
- return i18next;
42
- };
43
- get instance() {
44
- return this._instance;
45
- }
46
- }
@@ -1,217 +0,0 @@
1
- import winston, { format } from "winston";
2
- import Transport from "winston-transport";
3
- import "winston-daily-rotate-file";
4
- import path from "node:path";
5
- import { Partitioners } from "kafkajs";
6
- import { LoggerLayerEnum } from '../../utils';
7
- import { LogDTO } from "../../utils";
8
- import { bindLoaderTmpSync } from '../../utils';
9
- import { getRequestId } from "../../utils";
10
- class KafkaTransport extends Transport {
11
- service;
12
- constructor(opts, service) {
13
- super(opts);
14
- this.service = service;
15
- }
16
- log(info, callback) {
17
- setImmediate(() => this.emit("logged", info));
18
- this.service["logToKafka"](info).finally(() => callback());
19
- }
20
- }
21
- const customLevels = {
22
- critical: LoggerLayerEnum.CRITICAL,
23
- error: LoggerLayerEnum.ERROR,
24
- warn: LoggerLayerEnum.WARN,
25
- info: LoggerLayerEnum.INFO,
26
- http: LoggerLayerEnum.HTTP,
27
- debug: LoggerLayerEnum.DEBUG,
28
- };
29
- const customColors = {
30
- critical: "red",
31
- error: "magenta",
32
- warn: "yellow",
33
- info: "green",
34
- http: "cyan",
35
- debug: "blue"
36
- };
37
- export default class Logger {
38
- serviceName = "";
39
- isKafkaReady = false;
40
- kafkaProducer = null;
41
- kafkaLogsTopic = "";
42
- winston;
43
- #system;
44
- #configs;
45
- #kafka;
46
- constructor({ system, configs, kafkaForCore, }) {
47
- this.#system = system;
48
- this.#configs = configs;
49
- this.#kafka = kafkaForCore;
50
- }
51
- onInit = async () => {
52
- await this.syncFromTmp();
53
- bindLoaderTmpSync(this);
54
- };
55
- syncFromTmp = async () => {
56
- await this.teardownLogger();
57
- this.serviceName = ((this.#system?.tmp?.configs?.service ?? '') ?? '');
58
- this.kafkaLogsTopic = this.#configs?.all?.kafkaLogsTopic;
59
- winston.addColors(customColors);
60
- const loggersConfigs = this.#system?.tmp?.configs?.loaders?.loggers;
61
- const { kafkaBrokers, isKafkaPassive } = this.#configs.all;
62
- const brokers = kafkaBrokers ? String(kafkaBrokers).split(',').map((b) => b.trim()) : [];
63
- const isKafkaEnabled = isKafkaPassive === false && brokers.length > 0;
64
- if (isKafkaEnabled && this.#kafka.instance) {
65
- this.kafkaProducer = this.#kafka.instance.producer({
66
- createPartitioner: Partitioners.DefaultPartitioner,
67
- retry: { initialRetryTime: 500, retries: 5 },
68
- });
69
- try {
70
- await this.kafkaProducer?.connect();
71
- this.isKafkaReady = true;
72
- }
73
- catch {
74
- this.isKafkaReady = false;
75
- }
76
- }
77
- const logPath = loggersConfigs?.loadPath || 'logs';
78
- const loggerLevel = loggersConfigs?.logLevel || loggersConfigs?.loggerLevel || 'info';
79
- this.winstonLoader({
80
- loadPath: path.join(this.#configs.all.rootFolderPath, logPath),
81
- loggerLevel,
82
- });
83
- };
84
- teardownLogger = async () => {
85
- if (this.kafkaProducer) {
86
- try {
87
- await this.kafkaProducer.disconnect();
88
- }
89
- catch { }
90
- this.kafkaProducer = null;
91
- }
92
- this.isKafkaReady = false;
93
- if (this.winston) {
94
- this.winston.clear();
95
- this.winston.close();
96
- }
97
- };
98
- winstonLoader = ({ loadPath, loggerLevel }) => {
99
- const { combine, timestamp, json, errors } = format;
100
- const tracing = this.getTracingFormat();
101
- const jsonFileFormat = combine(tracing, timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), errors({ stack: true }), json({ replacer: this.safeReplacer }));
102
- const transports = [
103
- new winston.transports.Console({
104
- format: this.getConsoleFormat()
105
- }),
106
- new winston.transports.DailyRotateFile({
107
- filename: path.resolve(loadPath, "error", "%DATE%_error.log"),
108
- level: "error",
109
- format: jsonFileFormat,
110
- maxSize: "2mb",
111
- maxFiles: "7d"
112
- }),
113
- new winston.transports.DailyRotateFile({
114
- filename: path.resolve(loadPath, "critical", "%DATE%_critical.log"),
115
- level: "critical",
116
- format: jsonFileFormat,
117
- maxSize: "2mb",
118
- maxFiles: "14d"
119
- })
120
- ];
121
- if (this.isKafkaReady && this.kafkaProducer) {
122
- transports.push(new KafkaTransport({ level: loggerLevel }, this));
123
- }
124
- this.winston = winston.createLogger({
125
- level: loggerLevel,
126
- levels: customLevels,
127
- format: tracing,
128
- transports
129
- });
130
- return this.winston;
131
- };
132
- safeReplacer = (key, value) => {
133
- if (value instanceof Headers)
134
- return Object.fromEntries(value.entries());
135
- if (value instanceof Error)
136
- return { message: value.message, stack: value.stack };
137
- return value;
138
- };
139
- getTracingFormat = format((info) => {
140
- if (info.id)
141
- return info;
142
- const id = getRequestId();
143
- if (id)
144
- info.id = id;
145
- return info;
146
- });
147
- getConsoleFormat() {
148
- return format.combine(this.getTracingFormat(), format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), format.colorize({ all: true }), format.printf((info) => {
149
- const msg = typeof info.message === "object"
150
- ? JSON.stringify(info.message, this.safeReplacer)
151
- : info.message;
152
- const idPart = info.id ? ` : id: ${info.id}` : "";
153
- const payloadPart = info.payload ? `\nPayload: ${JSON.stringify(info.payload, this.safeReplacer)}` : "";
154
- const codePart = info.code ? ` [Code: ${info.code}]` : "";
155
- return `${info.timestamp} [${this.serviceName}] ${info.level}${codePart}: ${msg}${idPart}${payloadPart}`;
156
- }));
157
- }
158
- normalizeLevel(level) {
159
- return typeof level === 'string' ? level.toLowerCase() : LoggerLayerEnum[level].toLowerCase();
160
- }
161
- normalizeMessage(message) {
162
- if (message === undefined || message === null)
163
- return undefined;
164
- return typeof message === 'string' ? message : JSON.stringify(message, this.safeReplacer);
165
- }
166
- buildLogBody(params) {
167
- return LogDTO.schema({
168
- level: this.normalizeLevel(params.level),
169
- service: this.serviceName,
170
- message: this.normalizeMessage(params.message),
171
- payload: params.payload,
172
- code: params.code,
173
- timestamp: params.timestamp ?? new Date().toISOString(),
174
- id: params.id ?? getRequestId() ?? undefined,
175
- env: this.#configs.all.env,
176
- }).build();
177
- }
178
- async logToKafka(info) {
179
- if (!this.kafkaProducer || !this.isKafkaReady)
180
- return;
181
- try {
182
- const body = this.buildLogBody({
183
- level: info.level,
184
- message: info.message,
185
- payload: info.payload,
186
- code: info.code,
187
- id: info.id,
188
- timestamp: info.timestamp,
189
- });
190
- await this.kafkaProducer.send({
191
- topic: this.kafkaLogsTopic,
192
- messages: [{
193
- value: JSON.stringify(body, this.safeReplacer)
194
- }],
195
- acks: 1
196
- });
197
- }
198
- catch (err) {
199
- this.isKafkaReady = false;
200
- }
201
- }
202
- log(arg1, arg2, arg3, arg4) {
203
- const isObj = typeof arg1 === 'object' && arg1 !== null && 'level' in arg1;
204
- const input = isObj
205
- ? arg1
206
- : { level: arg1, message: arg2, payload: arg3, code: arg4 };
207
- const body = this.buildLogBody(input);
208
- this.winston.log(body.level, body.message, {
209
- id: body.id,
210
- payload: body.payload,
211
- code: body.code,
212
- service: body.service,
213
- timestamp: body.timestamp,
214
- env: body.env,
215
- });
216
- }
217
- }
@@ -1,7 +0,0 @@
1
- export class BaseService {
2
- }
3
- export default class Service extends BaseService {
4
- constructor() { super(); }
5
- async onInit() {
6
- }
7
- }
@@ -1,25 +0,0 @@
1
- import { G, notifyRuntimeTmpChange, onTmpReload, setRuntimeTmpConfigs, } from '../../utils';
2
- export default class System {
3
- _core = {};
4
- _tmp = {};
5
- cwd = process.cwd();
6
- g = G;
7
- onInit = async ({ core, }) => {
8
- this._core = core;
9
- await this.applyTmp(this._core._);
10
- onTmpReload((tmp) => void this.applyTmp(tmp));
11
- };
12
- async applyTmp(tmp) {
13
- this._tmp = tmp;
14
- const configs = (tmp.configs ?? {});
15
- setRuntimeTmpConfigs(configs);
16
- this.g.configureFromTmp(tmp);
17
- await notifyRuntimeTmpChange(configs);
18
- }
19
- get core() {
20
- return this._core;
21
- }
22
- get tmp() {
23
- return this._tmp;
24
- }
25
- }
@@ -1,70 +0,0 @@
1
- import path from 'path';
2
- import { System, Configs, Logger, Events, Localizations, DtoRuntime, Clients, Controller, KafkaForCore } from '../loader';
3
- import { Constants, getCore, x, } from '../utils';
4
- //
5
- export const core = getCore();
6
- export const coreInit = async (params) => {
7
- const { locales } = params;
8
- if (locales)
9
- globalThis.__LOCAL_MESSAGES__ = locales;
10
- };
11
- let coreHasRun = false;
12
- const coreLoader = async ({}) => {
13
- if (coreHasRun)
14
- return {};
15
- try {
16
- await (await x.load([
17
- path.join(__dirname, '..', 'loader', '**/*.{ts,js}'),
18
- ], {
19
- exclude: [
20
- path.join(__dirname, '..', 'utils', '**/class.x.{ts,js}'),
21
- ]
22
- }))
23
- .initialize([
24
- {
25
- service: System,
26
- props: {
27
- core
28
- }
29
- },
30
- {
31
- service: Configs,
32
- props: {}
33
- },
34
- {
35
- service: KafkaForCore,
36
- props: {}
37
- },
38
- {
39
- service: Logger,
40
- props: {}
41
- },
42
- {
43
- service: Events,
44
- props: {}
45
- },
46
- {
47
- service: Localizations,
48
- props: {}
49
- },
50
- {
51
- service: DtoRuntime,
52
- props: {}
53
- },
54
- {
55
- service: Controller,
56
- props: {}
57
- },
58
- {
59
- service: Clients,
60
- props: {}
61
- },
62
- ]);
63
- coreHasRun = true;
64
- }
65
- catch (error) {
66
- const errorMessage = error instanceof Error ? error.message : String(error);
67
- console.error(`[${Constants.packageName} core failure]: ${errorMessage}`);
68
- }
69
- };
70
- export default coreLoader;
@@ -1,15 +0,0 @@
1
- {
2
- "packageName": "@xrystal/core",
3
- "packageRootFolder": "x",
4
- "tmpBaseName": "tmp",
5
- "tmpExtension": ".yml",
6
- "mainSourceFolder": "./source",
7
- "layoutPaths": {
8
- "tests": "tests",
9
- "environments": "environments",
10
- "dist": "dist"
11
- },
12
- "publicFolderName": "public",
13
- "kafkaLogsTopic": "log",
14
- "templateRepoUri": "https://github.com/xdloper/xastral-general-project-tmp.git"
15
- }
@@ -1,10 +0,0 @@
1
- import defaults from './defaults.json' with { type: 'json' }
2
-
3
- export const packageDefaults = Object.freeze({
4
- ...defaults,
5
- layoutPaths: Object.freeze({ ...defaults.layoutPaths }),
6
- })
7
-
8
- export const coreVersionPattern = /^\d{2}\.\d{2}\.\d{2}-v\d+$/
9
-
10
- export const semverVersionPattern = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/
@@ -1,22 +0,0 @@
1
- import path from 'node:path';
2
- import { packageRootDir } from '../../utils/package-root';
3
- import defaults from './defaults.json';
4
- export const packageDefaults = Object.freeze({
5
- ...defaults,
6
- layoutPaths: Object.freeze({ ...defaults.layoutPaths }),
7
- });
8
- export const coreVersionPattern = /^\d{2}\.\d{2}\.\d{2}-v\d+$/;
9
- export const semverVersionPattern = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;
10
- const tmpFileName = `${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;
11
- export class Constants {
12
- static packageName = packageDefaults.packageName;
13
- static packageRootFolder = packageDefaults.packageRootFolder;
14
- static tmpBaseName = packageDefaults.tmpBaseName;
15
- static tmpExtension = packageDefaults.tmpExtension;
16
- static mainSourceFolder = packageDefaults.mainSourceFolder;
17
- static layoutPaths = packageDefaults.layoutPaths;
18
- static publicFolderName = packageDefaults.publicFolderName;
19
- static kafkaLogsTopic = packageDefaults.kafkaLogsTopic;
20
- static templateRepoUri = packageDefaults.templateRepoUri;
21
- static bundledCoreTmpPath = path.join(packageRootDir, packageDefaults.packageRootFolder, tmpFileName);
22
- }
@@ -1 +0,0 @@
1
- export const configs = {};
@@ -1,12 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- export const controllerContextStorage = new AsyncLocalStorage();
3
- export const getControllerCtx = () => controllerContextStorage.getStore();
4
- export const runControllerStore = (context, action) => controllerContextStorage.run(context, action);
5
- export function isFetchRequest(value) {
6
- return typeof value === 'object' && value !== null && value instanceof Request;
7
- }
8
- export function adapterBagFromRequest(value) {
9
- if (!value || isFetchRequest(value))
10
- return undefined;
11
- return value;
12
- }
@@ -1,24 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- export const runContextStorage = new AsyncLocalStorage();
3
- export function getRunContext() {
4
- return runContextStorage.getStore();
5
- }
6
- export function getRequestId() {
7
- return getRunContext()?.requestId;
8
- }
9
- export function runWithContext(context, fn) {
10
- return runContextStorage.run(context, fn);
11
- }
12
- export function runWithRequestId(requestId, fn, kind = 'http') {
13
- return runWithContext({ requestId, kind }, fn);
14
- }
15
- export function runWithTrace(id, fn, label) {
16
- return runWithContext({ requestId: id, kind: 'job', label }, fn);
17
- }
18
- export function patchRunContext(patch) {
19
- const current = getRunContext();
20
- if (!current)
21
- return;
22
- Object.assign(current, patch);
23
- }
24
- export { controllerContextStorage, getControllerCtx, runControllerStore, adapterBagFromRequest, isFetchRequest, } from '../../../utils/helpers/context/controller-store';
@@ -1,58 +0,0 @@
1
- import Handlebars from 'handlebars';
2
- import { Constants, ProtocolEnum, TmpFileLoader } from '../../../utils/index.js';
3
- import { controllerContextStorage } from '../../../utils/helpers/context/controller-store';
4
- import { getTmpSnapshot } from '../../../utils/helpers/tmp/tmp-loader';
5
- import { findFileRecursively } from '../../../utils/helpers/core/paths';
6
- import { parseProtocol } from '../../../utils/helpers/protocol/index.js';
7
- export * from '../../../utils/helpers/core/paths';
8
- export * from '../../../utils/helpers/core/tmp-layout';
9
- export const getCore = () => ({
10
- _: getTmpSnapshot(),
11
- });
12
- export const getTmpConfig = ({ root = process.cwd(), tmpFileName = Constants.tmpBaseName, ext = Constants.tmpExtension, } = {}) => {
13
- const filePath = findFileRecursively(root, tmpFileName, ext);
14
- if (!filePath) {
15
- throw new Error(`${tmpFileName}${ext.startsWith('.') ? ext : `.${ext}`} file not found`);
16
- }
17
- const loader = new TmpFileLoader({ filePath });
18
- return loader.getResolvedTmpFile();
19
- };
20
- export function resolveObjWithHandlebars(obj, context) {
21
- if (typeof obj === "string") {
22
- const compileResult = Handlebars.compile(obj);
23
- return compileResult(context);
24
- }
25
- else if (typeof obj === "object" && obj !== null) {
26
- for (const key in obj) {
27
- obj[key] = resolveObjWithHandlebars(obj[key], context);
28
- }
29
- }
30
- return obj;
31
- }
32
- export const withProtocol = async (callback, protocol = ProtocolEnum.HTTP) => {
33
- const resolved = parseProtocol(protocol);
34
- const store = controllerContextStorage.getStore();
35
- if (store)
36
- store.protocol = resolved;
37
- return await callback();
38
- };
39
- export const protocol = async (callback, proto = ProtocolEnum.HTTP) => withProtocol(callback, proto);
40
- export const argvsConverter = (argvs) => {
41
- const reelArgvs = argvs?.slice(2);
42
- const reelConvertedArgvs = {};
43
- reelArgvs.forEach((argv) => {
44
- if (argv.startsWith('--')) {
45
- console.log(argv);
46
- const [key, value] = argv.split('=');
47
- reelConvertedArgvs[key.replace('--', '')] = value || '';
48
- }
49
- });
50
- return reelConvertedArgvs;
51
- };
52
- export const findExt = (filename) => {
53
- const split = filename.split('.');
54
- return split[split.length - 1];
55
- };
56
- export const changeExtensions = (filename, repalceExt) => {
57
- return filename.replace(findExt(filename), repalceExt);
58
- };