@xrystal/core 3.51.6 → 3.52.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/README.md +35 -1
- package/package.json +1 -1
- package/x/bin/commands/create.mjs +44 -0
- package/x/bin/commands/projects.mjs +53 -0
- package/x/bin/commands/sync.mjs +49 -1
- package/x/bin/commands/tmp.mjs +1 -1
- package/x/bin/helpers/.generated/.generated-from +2 -0
- package/x/bin/helpers/.generated/seed-from-tmp.mjs +25 -31
- package/x/bin/helpers/.generated/tmp-schema.mjs +156 -96
- package/x/bin/helpers/.generated/workspace.mjs +402 -0
- package/x/bin/helpers/.generated/xrystal-home-registry.mjs +310 -0
- package/x/bin/helpers/build-config.mjs +3 -2
- package/x/bin/helpers/cli-help.mjs +3 -1
- package/x/bin/helpers/project-artifacts.mjs +9 -0
- package/x/bin/helpers/tmp-config.mjs +13 -12
- package/x/bin/helpers/tmp-layout.mjs +28 -52
- package/x/bin/helpers/tmp-schema.mjs +9 -3
- package/x/bin/helpers/workspace-resolve.mjs +11 -0
- package/x/bin/helpers/workspace-scaffold.mjs +23 -0
- package/x/bin/helpers/xrystal-registry.mjs +13 -0
- package/x/bin/main-cli.js +2 -0
- package/x/dist/index.js +5 -1
- package/x/dist/loader/clients/index.js +22 -1
- package/x/dist/loader/configs/index.js +97 -1
- package/x/dist/loader/controller/index.js +267 -1
- package/x/dist/loader/dto/index.js +92 -1
- package/x/dist/loader/events/index.js +39 -1
- package/x/dist/loader/index.js +13 -1
- package/x/dist/loader/kafka/index.js +142 -1
- package/x/dist/loader/kafka/resolve-ssl.js +23 -1
- package/x/dist/loader/localizations/index.js +46 -1
- package/x/dist/loader/logger/index.js +229 -2
- package/x/dist/loader/mongo/index.js +52 -1
- package/x/dist/loader/mongo/resolve-connect.js +16 -1
- package/x/dist/loader/redis/index.js +57 -1
- package/x/dist/loader/redis/resolve-socket.js +31 -1
- package/x/dist/loader/registry/index.js +1 -1
- package/x/dist/loader/service/index.js +7 -1
- package/x/dist/loader/system/index.js +26 -1
- package/x/dist/project/index.js +51 -1
- package/x/dist/utils/constants/defaults.json +3 -1
- package/x/dist/utils/constants/index.d.ts +1 -0
- package/x/dist/utils/constants/index.js +42 -1
- package/x/dist/utils/constants/package-root.js +6 -1
- package/x/dist/utils/helpers/configs/index.js +1 -1
- package/x/dist/utils/helpers/context/controller-store.js +12 -1
- package/x/dist/utils/helpers/context/index.js +24 -1
- package/x/dist/utils/helpers/core/handlebars-resolve.js +15 -1
- package/x/dist/utils/helpers/core/index.js +46 -1
- package/x/dist/utils/helpers/core/paths.js +78 -1
- package/x/dist/utils/helpers/core/tmp-layout.d.ts +4 -4
- package/x/dist/utils/helpers/core/tmp-layout.js +229 -1
- package/x/dist/utils/helpers/date/index.js +48 -1
- package/x/dist/utils/helpers/dispatch/index.js +53 -1
- package/x/dist/utils/helpers/dto/index.js +10 -1
- package/x/dist/utils/helpers/filters/index.js +44 -1
- package/x/dist/utils/helpers/framework/index.js +18 -1
- package/x/dist/utils/helpers/handlers/adapters.js +41 -1
- package/x/dist/utils/helpers/handlers/execute.js +82 -1
- package/x/dist/utils/helpers/handlers/index.js +31 -1
- package/x/dist/utils/helpers/hash/crypto.js +22 -1
- package/x/dist/utils/helpers/id/index.js +24 -1
- package/x/dist/utils/helpers/index.d.ts +1 -0
- package/x/dist/utils/helpers/index.js +28 -1
- package/x/dist/utils/helpers/ip/index.js +21 -1
- package/x/dist/utils/helpers/is/index.js +35 -1
- package/x/dist/utils/helpers/kafka-loader-options/index.js +14 -1
- package/x/dist/utils/helpers/locales/index.js +82 -1
- package/x/dist/utils/helpers/logger-layer/index.js +33 -1
- package/x/dist/utils/helpers/math/index.js +14 -1
- package/x/dist/utils/helpers/middleware/index.js +36 -1
- package/x/dist/utils/helpers/node-env/index.js +20 -1
- package/x/dist/utils/helpers/objects/index.js +55 -1
- package/x/dist/utils/helpers/path/index.js +5 -1
- package/x/dist/utils/helpers/path/resolve-alias-path.d.ts +1 -1
- package/x/dist/utils/helpers/path/resolve-alias-path.js +62 -1
- package/x/dist/utils/helpers/protocol/index.d.ts +1 -1
- package/x/dist/utils/helpers/protocol/index.js +100 -1
- package/x/dist/utils/helpers/protocol/options.js +13 -1
- package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +3 -1
- package/x/dist/utils/helpers/registry/index.js +103 -1
- package/x/dist/utils/helpers/runtime/dto-access.js +5 -1
- package/x/dist/utils/helpers/runtime/dto-types.js +1 -1
- package/x/dist/utils/helpers/runtime/index.js +2 -1
- package/x/dist/utils/helpers/runtime/shutdown.js +36 -1
- package/x/dist/utils/helpers/state/index.js +185 -1
- package/x/dist/utils/helpers/state/props-from-tmp.js +46 -1
- package/x/dist/utils/helpers/state/request-key-guard.js +43 -1
- package/x/dist/utils/helpers/state/scopes.js +69 -1
- package/x/dist/utils/helpers/string/index.js +9 -1
- package/x/dist/utils/helpers/timer/index.js +5 -1
- package/x/dist/utils/helpers/tmp/index.d.ts +2 -2
- package/x/dist/utils/helpers/tmp/index.js +8 -1
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +14 -1
- package/x/dist/utils/helpers/tmp/path-normalize.js +27 -1
- package/x/dist/utils/helpers/tmp/runtime-tmp.js +42 -1
- package/x/dist/utils/helpers/tmp/seed-from-tmp.d.ts +2 -2
- package/x/dist/utils/helpers/tmp/seed-from-tmp.js +62 -1
- package/x/dist/utils/helpers/tmp/tmp-interpolate.js +22 -1
- package/x/dist/utils/helpers/tmp/tmp-loader.js +56 -1
- package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +35 -23
- package/x/dist/utils/helpers/tmp/tmp-schema.js +211 -1
- package/x/dist/utils/helpers/tmp/tmp-watch.js +23 -1
- package/x/dist/utils/helpers/tmp/toolchain-heal.js +157 -2
- package/x/dist/utils/helpers/validates/index.js +20 -1
- package/x/dist/utils/helpers/workspace/index.d.ts +42 -0
- package/x/dist/utils/helpers/workspace/index.js +222 -0
- package/x/dist/utils/helpers/xrystal-home/registry.d.ts +32 -0
- package/x/dist/utils/helpers/xrystal-home/registry.js +92 -0
- package/x/dist/utils/index.js +3 -1
- package/x/dist/utils/models/classes/class.clients.js +142 -1
- package/x/dist/utils/models/classes/class.interfaces.js +10 -1
- package/x/dist/utils/models/classes/class.service-locator.js +16 -1
- package/x/dist/utils/models/classes/class.tmp-file-loader.js +61 -1
- package/x/dist/utils/models/classes/class.x.js +181 -1
- package/x/dist/utils/models/enums/index.d.ts +9 -1
- package/x/dist/utils/models/enums/index.js +169 -1
- package/x/dist/utils/models/index.js +9 -1
- package/x/dist/utils/models/types/index.js +2 -1
- package/x/tmp.yml +7 -50
|
@@ -1 +1,267 @@
|
|
|
1
|
-
import{Constants
|
|
1
|
+
import { Constants } from '../../utils/constants/index.js';
|
|
2
|
+
import qs from 'qs';
|
|
3
|
+
import Logger from '../../loader/logger/index.js';
|
|
4
|
+
import System from '../../loader/system/index.js';
|
|
5
|
+
import { bindLoaderTmpSync, getClientIp, getConfiguredProtocols, isRealtimeProtocol, LoggerLayerEnum, parseResponseMessage, ProtocolEnum, x, controllerContextStorage, getControllerCtx, runControllerStore, adapterBagFromRequest, isFetchRequest, toHandler, toRealtimeHandler, resolveCtrOptions, } from '../../utils/index.js';
|
|
6
|
+
export { controllerContextStorage, getControllerCtx };
|
|
7
|
+
export const runController = runControllerStore;
|
|
8
|
+
function isRawResponse(value) {
|
|
9
|
+
return value instanceof Response || value instanceof Blob || value instanceof Uint8Array || value instanceof ArrayBuffer;
|
|
10
|
+
}
|
|
11
|
+
function asPayloadRecord(value) {
|
|
12
|
+
if (!value || typeof value !== 'object')
|
|
13
|
+
return null;
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function applyResultMeta(builder, obj) {
|
|
17
|
+
const record = asPayloadRecord(obj);
|
|
18
|
+
if (!record)
|
|
19
|
+
return;
|
|
20
|
+
if (record.statusCode !== undefined)
|
|
21
|
+
return void builder.httpStatus(Number(record.statusCode));
|
|
22
|
+
if (record.code !== undefined) {
|
|
23
|
+
const code = Number(record.code);
|
|
24
|
+
if (code >= 100)
|
|
25
|
+
builder.httpStatus(code);
|
|
26
|
+
else
|
|
27
|
+
builder.code(code);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function extractPayload(obj) {
|
|
31
|
+
const record = asPayloadRecord(obj);
|
|
32
|
+
if (!record)
|
|
33
|
+
return { data: undefined, extraData: undefined, message: undefined };
|
|
34
|
+
const payload = asPayloadRecord(record.payload);
|
|
35
|
+
if (payload) {
|
|
36
|
+
return {
|
|
37
|
+
data: payload.data !== undefined ? payload.data : payload,
|
|
38
|
+
extraData: payload.extraData,
|
|
39
|
+
message: record.message,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
if (record.data !== undefined || record.extraData !== undefined) {
|
|
43
|
+
return { data: record.data, extraData: record.extraData, message: record.message };
|
|
44
|
+
}
|
|
45
|
+
const hasMeta = record.status !== undefined || record.message !== undefined || record.code !== undefined || record.statusCode !== undefined;
|
|
46
|
+
if (!hasMeta && Object.keys(record).length > 0) {
|
|
47
|
+
return { data: record, extraData: undefined, message: record.message };
|
|
48
|
+
}
|
|
49
|
+
return { data: undefined, extraData: undefined, message: record.message };
|
|
50
|
+
}
|
|
51
|
+
function isReadableBodyStream(value) {
|
|
52
|
+
return value instanceof ReadableStream
|
|
53
|
+
|| (typeof value === 'object' && value !== null && typeof value.getReader === 'function');
|
|
54
|
+
}
|
|
55
|
+
function headerValue(value) {
|
|
56
|
+
if (Array.isArray(value))
|
|
57
|
+
return value[0] ?? '';
|
|
58
|
+
return value ?? '';
|
|
59
|
+
}
|
|
60
|
+
export function resolveBuilder(store) {
|
|
61
|
+
const attached = store.ctx?.builder ?? store.res?.builder ?? store.socket?.builder;
|
|
62
|
+
if (attached)
|
|
63
|
+
return attached;
|
|
64
|
+
throw new Error(`[${Constants.packageName}] use dtoMiddleware() — builder attaches at request start via @xrystal/dto adapter`);
|
|
65
|
+
}
|
|
66
|
+
export class BaseController {
|
|
67
|
+
system = x.get(System);
|
|
68
|
+
logger = x.get(Logger);
|
|
69
|
+
supportedProtocols = [ProtocolEnum.HTTP, ProtocolEnum.WEBSOCKET];
|
|
70
|
+
get store() {
|
|
71
|
+
return getControllerCtx();
|
|
72
|
+
}
|
|
73
|
+
get protocol() {
|
|
74
|
+
return this.store?.protocol || ProtocolEnum.HTTP;
|
|
75
|
+
}
|
|
76
|
+
get req() {
|
|
77
|
+
const store = this.store;
|
|
78
|
+
const ctx = store?.ctx || {};
|
|
79
|
+
const req = store?.req || {};
|
|
80
|
+
const fetchRequest = isFetchRequest(ctx.request) ? ctx.request : undefined;
|
|
81
|
+
const ctxReq = adapterBagFromRequest(ctx.request);
|
|
82
|
+
const headerSource = ctx.headers ?? req.headers ?? fetchRequest?.headers ?? ctxReq?.headers;
|
|
83
|
+
const headers = headerSource instanceof Headers
|
|
84
|
+
? Object.fromEntries(headerSource.entries())
|
|
85
|
+
: (headerSource ?? {});
|
|
86
|
+
const url = fetchRequest?.url ?? ctxReq?.url ?? req.url ?? ctx.url ?? "";
|
|
87
|
+
let query = (store?.metadata?.parsedQuery || ctx.query || req.query || ctxReq?.query || {});
|
|
88
|
+
if (!Object.keys(query).length && url.includes('?'))
|
|
89
|
+
query = qs.parse(url.split('?')[1]);
|
|
90
|
+
let cookies = (ctx.cookies || req.cookies || ctxReq?.cookies || {});
|
|
91
|
+
const cookieHeader = headers.cookie;
|
|
92
|
+
if (!Object.keys(cookies).length && typeof cookieHeader === 'string') {
|
|
93
|
+
cookies = Object.fromEntries(cookieHeader.split(';').map((part) => {
|
|
94
|
+
const [k, v] = part.trim().split('=');
|
|
95
|
+
return [decodeURIComponent(k), decodeURIComponent(v || '')];
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
url,
|
|
100
|
+
method: (ctx.method || req.method || fetchRequest?.method || ctxReq?.method || '').toUpperCase(),
|
|
101
|
+
headers,
|
|
102
|
+
body: store?.metadata?.parsedBody || ctx.body || req.body || ctxReq?.body || {},
|
|
103
|
+
query,
|
|
104
|
+
params: { ...req.params, ...ctx.params, ...ctxReq?.params, ...ctxReq?.routeParams },
|
|
105
|
+
cookies,
|
|
106
|
+
ip: getClientIp(req, ctx),
|
|
107
|
+
lang: ctx.lang || req.lang || 'en',
|
|
108
|
+
requestId: store?.requestId ?? ctx.requestId ?? req.ctx?.requestId ?? String(headers['x-request-id'] ?? headers['x-correlation-id'] ?? ''),
|
|
109
|
+
startTime: (ctx.startTime ?? req.ctx?.startTime ?? Date.now()),
|
|
110
|
+
t: (ctx.t || req.t || ((k) => k)),
|
|
111
|
+
accounts: ctx.accounts || req.accounts || ctx.user,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
get res() {
|
|
115
|
+
const store = this.store;
|
|
116
|
+
if (!store)
|
|
117
|
+
throw new Error(`[${Constants.packageName}] controller context missing`);
|
|
118
|
+
const locals = store.metadata?.locals ?? {};
|
|
119
|
+
return { builder: resolveBuilder(store), locals: locals };
|
|
120
|
+
}
|
|
121
|
+
async parseRequestBody() {
|
|
122
|
+
const store = this.store;
|
|
123
|
+
if (!store)
|
|
124
|
+
return;
|
|
125
|
+
const ctxRequest = store.ctx?.request;
|
|
126
|
+
const raw = store.req || ctxRequest || store.ctx?.req;
|
|
127
|
+
const base = this.req;
|
|
128
|
+
const type = headerValue(base.headers['content-type']).toLowerCase();
|
|
129
|
+
const length = parseInt(headerValue(base.headers['content-length']) || '-1', 10);
|
|
130
|
+
let body = base.body;
|
|
131
|
+
const parse = (text) => {
|
|
132
|
+
if (!text)
|
|
133
|
+
return {};
|
|
134
|
+
if (type.includes('application/json'))
|
|
135
|
+
try {
|
|
136
|
+
return JSON.parse(text);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return text;
|
|
140
|
+
}
|
|
141
|
+
if (type.includes('application/x-www-form-urlencoded'))
|
|
142
|
+
return qs.parse(text);
|
|
143
|
+
try {
|
|
144
|
+
return JSON.parse(text);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
try {
|
|
148
|
+
return qs.parse(text);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return text;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const isStream = isReadableBodyStream;
|
|
156
|
+
const ready = body && typeof body === 'object' && !isStream(body) && Object.keys(body).length > 0;
|
|
157
|
+
if (!isRealtimeProtocol(this.protocol) && !['GET', 'HEAD', 'OPTIONS'].includes(base.method) && !ready) {
|
|
158
|
+
if (raw instanceof Request && (isStream(body) || length > 0)) {
|
|
159
|
+
try {
|
|
160
|
+
body = parse(await raw.clone().text());
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
if (typeof body === 'string')
|
|
164
|
+
body = parse(body);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
else if (raw && typeof raw === 'object' && 'on' in raw && typeof raw.on === 'function' && length !== 0) {
|
|
168
|
+
const stream = raw;
|
|
169
|
+
body = await new Promise((resolve) => {
|
|
170
|
+
let text = '';
|
|
171
|
+
const timer = setTimeout(() => resolve({}), 200);
|
|
172
|
+
stream.on('data', (chunk) => { text += String(chunk); });
|
|
173
|
+
stream.on('end', () => { clearTimeout(timer); resolve(parse(text)); });
|
|
174
|
+
stream.on('error', () => { clearTimeout(timer); resolve({}); });
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
else if (typeof body === 'string' && body.length) {
|
|
178
|
+
body = parse(body);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (typeof FormData !== 'undefined' && body instanceof FormData) {
|
|
182
|
+
body = Object.fromEntries(body.entries());
|
|
183
|
+
}
|
|
184
|
+
if (!store.metadata)
|
|
185
|
+
store.metadata = { locals: {} };
|
|
186
|
+
store.metadata.parsedBody = body || {};
|
|
187
|
+
store.metadata.parsedQuery = base.query;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
export default class Controller extends BaseController {
|
|
191
|
+
async onInit() {
|
|
192
|
+
await this.syncFromTmp();
|
|
193
|
+
bindLoaderTmpSync(this);
|
|
194
|
+
}
|
|
195
|
+
syncFromTmp = () => {
|
|
196
|
+
this.supportedProtocols = getConfiguredProtocols();
|
|
197
|
+
};
|
|
198
|
+
parseMessage(msg, t, isError = false) {
|
|
199
|
+
return parseResponseMessage(msg, t, isError);
|
|
200
|
+
}
|
|
201
|
+
args(builder) {
|
|
202
|
+
const req = this.req;
|
|
203
|
+
const locals = this.store.metadata?.locals ?? {};
|
|
204
|
+
return { req, res: { builder, locals }, builder, body: req.body, query: req.query, queries: req.query, params: req.params, cookies: req.cookies, locals, t: req.t };
|
|
205
|
+
}
|
|
206
|
+
fail(builder, source, t) {
|
|
207
|
+
applyResultMeta(builder, source);
|
|
208
|
+
const { data, extraData } = extractPayload(source);
|
|
209
|
+
const record = asPayloadRecord(source);
|
|
210
|
+
const message = this.parseMessage(record?.message ?? source, t, true);
|
|
211
|
+
const extras = data !== undefined || extraData !== undefined ? { data, extraData } : undefined;
|
|
212
|
+
const terminal = data !== undefined ? builder.as.fail(data, message, extras) : builder.as.fail(message, extras);
|
|
213
|
+
return terminal.build();
|
|
214
|
+
}
|
|
215
|
+
ok(builder, resResult, logicResult, t) {
|
|
216
|
+
let message = 'success_process';
|
|
217
|
+
let source = resResult !== undefined ? resResult : logicResult;
|
|
218
|
+
if (typeof resResult === 'string') {
|
|
219
|
+
message = resResult;
|
|
220
|
+
source = logicResult;
|
|
221
|
+
}
|
|
222
|
+
const { data, extraData, message: custom } = extractPayload(source);
|
|
223
|
+
if (typeof custom === 'string')
|
|
224
|
+
message = custom;
|
|
225
|
+
applyResultMeta(builder, source);
|
|
226
|
+
return builder.as.ok(data, this.parseMessage(message, t, false), extraData !== undefined ? { extraData } : undefined).build();
|
|
227
|
+
}
|
|
228
|
+
async schema({ checks, logic, response }) {
|
|
229
|
+
const builder = resolveBuilder(this.store);
|
|
230
|
+
try {
|
|
231
|
+
await this.parseRequestBody();
|
|
232
|
+
const args = this.args(builder);
|
|
233
|
+
const typedArgs = args;
|
|
234
|
+
if (checks) {
|
|
235
|
+
const check = await checks(typedArgs);
|
|
236
|
+
if (check !== true)
|
|
237
|
+
return this.fail(builder, check, typedArgs.req.t);
|
|
238
|
+
}
|
|
239
|
+
let result = logic ? await logic(typedArgs) : {};
|
|
240
|
+
const resultRecord = asPayloadRecord(result);
|
|
241
|
+
if (resultRecord && typeof resultRecord.response === 'function') {
|
|
242
|
+
result = await resultRecord.response();
|
|
243
|
+
}
|
|
244
|
+
if (isRawResponse(result))
|
|
245
|
+
return result;
|
|
246
|
+
if (resultRecord?.status === false)
|
|
247
|
+
return this.fail(builder, result, typedArgs.req.t);
|
|
248
|
+
const out = response ? await response({ ...typedArgs, logicResult: result }) : result;
|
|
249
|
+
if (isRawResponse(out))
|
|
250
|
+
return out;
|
|
251
|
+
return this.ok(builder, out, result, typedArgs.req.t);
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
255
|
+
this.logger?.log(LoggerLayerEnum.ERROR, `Controller Error: ${message}`);
|
|
256
|
+
return builder.as.internalServerError(this.parseMessage(message, this.req.t, true)).build();
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
ctr(definition, opts) {
|
|
260
|
+
const { framework, protocol } = resolveCtrOptions(opts);
|
|
261
|
+
const action = () => this.schema(definition);
|
|
262
|
+
if (isRealtimeProtocol(protocol)) {
|
|
263
|
+
return toRealtimeHandler(action, protocol);
|
|
264
|
+
}
|
|
265
|
+
return toHandler(action, framework);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
@@ -1 +1,92 @@
|
|
|
1
|
-
import{DTO
|
|
1
|
+
import { DTO } from '@xrystal/dto/dto';
|
|
2
|
+
import { bindLoaderTmpSync } from '../../utils/index.js';
|
|
3
|
+
import { FrameworkEnum, parseFramework } from '../../utils/index.js';
|
|
4
|
+
export const DEFAULT_DTO_CONFIG = {
|
|
5
|
+
withDefaultHeaders: true,
|
|
6
|
+
};
|
|
7
|
+
function mergeDtoConfig(base, patch) {
|
|
8
|
+
return {
|
|
9
|
+
...base,
|
|
10
|
+
...patch,
|
|
11
|
+
codes: patch.codes ? { ...base.codes, ...patch.codes } : base.codes,
|
|
12
|
+
defaultHeaders: patch.defaultHeaders
|
|
13
|
+
? { ...base.defaultHeaders, ...patch.defaultHeaders }
|
|
14
|
+
: base.defaultHeaders,
|
|
15
|
+
socket: patch.socket ? { ...base.socket, ...patch.socket } : base.socket,
|
|
16
|
+
hooks: patch.hooks ?? base.hooks,
|
|
17
|
+
plugins: patch.plugins ? [...(base.plugins ?? []), ...patch.plugins] : base.plugins,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export default class DtoRuntime {
|
|
21
|
+
_runtime;
|
|
22
|
+
_system;
|
|
23
|
+
_config = { ...DEFAULT_DTO_CONFIG };
|
|
24
|
+
_framework = FrameworkEnum.ELYSIA;
|
|
25
|
+
_bootConfig = {};
|
|
26
|
+
constructor({ system }) {
|
|
27
|
+
this._system = system;
|
|
28
|
+
}
|
|
29
|
+
async onInit(props = {}) {
|
|
30
|
+
this._bootConfig = props.config ?? {};
|
|
31
|
+
await this.syncFromTmp();
|
|
32
|
+
bindLoaderTmpSync(this);
|
|
33
|
+
}
|
|
34
|
+
syncFromTmp = async () => {
|
|
35
|
+
this._framework = parseFramework(this._system?.tmp?.configs?.service?.framework);
|
|
36
|
+
this.applyConfig(DEFAULT_DTO_CONFIG, this._system?.tmp?.configs?.service?.loaders?.dto ?? {}, this._bootConfig, { rebuild: true });
|
|
37
|
+
};
|
|
38
|
+
get instance() {
|
|
39
|
+
return this._runtime;
|
|
40
|
+
}
|
|
41
|
+
get config() {
|
|
42
|
+
return this._config;
|
|
43
|
+
}
|
|
44
|
+
get framework() {
|
|
45
|
+
return this._framework;
|
|
46
|
+
}
|
|
47
|
+
configure(config = {}, options = {}) {
|
|
48
|
+
this.applyConfig(this._config, config, options);
|
|
49
|
+
return this;
|
|
50
|
+
}
|
|
51
|
+
use(...plugins) {
|
|
52
|
+
this._runtime.use(...plugins);
|
|
53
|
+
this._config = mergeDtoConfig(this._config, { plugins });
|
|
54
|
+
return this;
|
|
55
|
+
}
|
|
56
|
+
express() {
|
|
57
|
+
return this._runtime.express();
|
|
58
|
+
}
|
|
59
|
+
elysia() {
|
|
60
|
+
return this._runtime.elysia();
|
|
61
|
+
}
|
|
62
|
+
node() {
|
|
63
|
+
return this._runtime.node();
|
|
64
|
+
}
|
|
65
|
+
websocket() {
|
|
66
|
+
return this._runtime.websocket();
|
|
67
|
+
}
|
|
68
|
+
socketIo() {
|
|
69
|
+
return this._runtime.socketIo();
|
|
70
|
+
}
|
|
71
|
+
attachWebSocket(socket, requestId) {
|
|
72
|
+
return this._runtime.attachWebSocket(socket, requestId);
|
|
73
|
+
}
|
|
74
|
+
attachSocketIo(socket) {
|
|
75
|
+
return this._runtime.attachSocketIo(socket);
|
|
76
|
+
}
|
|
77
|
+
fetch() {
|
|
78
|
+
return this._runtime.fetch();
|
|
79
|
+
}
|
|
80
|
+
forRequest(request) {
|
|
81
|
+
return this._runtime.forRequest(request);
|
|
82
|
+
}
|
|
83
|
+
applyConfig(...sources) {
|
|
84
|
+
const last = sources[sources.length - 1];
|
|
85
|
+
const options = last && 'rebuild' in last ? sources.pop() : {};
|
|
86
|
+
const merged = sources.reduce((acc, part) => mergeDtoConfig(acc, part), { ...DEFAULT_DTO_CONFIG });
|
|
87
|
+
this._config = merged;
|
|
88
|
+
if (!this._runtime || options.rebuild !== false) {
|
|
89
|
+
this._runtime = new DTO(this._config);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -1 +1,39 @@
|
|
|
1
|
-
import{LoggerLayerEnum
|
|
1
|
+
import { LoggerLayerEnum, registerGracefulShutdown } from '../../utils/index.js';
|
|
2
|
+
export default class Events {
|
|
3
|
+
#logger;
|
|
4
|
+
constructor({ logger }) {
|
|
5
|
+
this.#logger = logger;
|
|
6
|
+
}
|
|
7
|
+
onInit = ({}) => {
|
|
8
|
+
this._globalLoader();
|
|
9
|
+
this._DILoader();
|
|
10
|
+
};
|
|
11
|
+
_globalLoader = () => {
|
|
12
|
+
process.on("uncaughtException", (error, origin) => {
|
|
13
|
+
this.#logger.log({
|
|
14
|
+
level: LoggerLayerEnum.CRITICAL,
|
|
15
|
+
message: `Uncaught Exception: ${error.message}`,
|
|
16
|
+
payload: {
|
|
17
|
+
stack: error.stack,
|
|
18
|
+
origin: origin
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
process.on("unhandledRejection", (reason, promise) => {
|
|
23
|
+
const error = reason instanceof Error ? reason : new Error(String(reason));
|
|
24
|
+
this.#logger.log({
|
|
25
|
+
level: LoggerLayerEnum.CRITICAL,
|
|
26
|
+
message: `Unhandled Rejection: ${error.message}`,
|
|
27
|
+
payload: {
|
|
28
|
+
stack: error.stack,
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
_DILoader = () => {
|
|
34
|
+
registerGracefulShutdown();
|
|
35
|
+
};
|
|
36
|
+
get global() {
|
|
37
|
+
return this._globalLoader();
|
|
38
|
+
}
|
|
39
|
+
}
|
package/x/dist/loader/index.js
CHANGED
|
@@ -1 +1,13 @@
|
|
|
1
|
-
import System from "./system/index.js";
|
|
1
|
+
import System from "./system/index.js";
|
|
2
|
+
import Configs from "./configs/index.js";
|
|
3
|
+
import KafkaForCore from "./kafka/index.js";
|
|
4
|
+
import RedisForCore from "./redis/index.js";
|
|
5
|
+
import MongoForCore from "./mongo/index.js";
|
|
6
|
+
import Logger from "./logger/index.js";
|
|
7
|
+
import Events from "./events/index.js";
|
|
8
|
+
import Localizations from "./localizations/index.js";
|
|
9
|
+
import DtoRuntime from "./dto/index.js";
|
|
10
|
+
import Controller from "./controller/index.js";
|
|
11
|
+
import Service from "./service/index.js";
|
|
12
|
+
import Clients from "./clients/index.js";
|
|
13
|
+
export { System, Configs, Logger, Events, Localizations, DtoRuntime, Controller, Service, Clients, KafkaForCore, RedisForCore, MongoForCore };
|
|
@@ -1 +1,142 @@
|
|
|
1
|
-
export
|
|
1
|
+
export { resolveKafkaJsSsl } from './resolve-ssl.js';
|
|
2
|
+
import { Kafka as KafkaClient, logLevel } from "kafkajs";
|
|
3
|
+
import { bindLoaderTmpSync } from '../../utils/helpers/tmp/loader-tmp-sync.js';
|
|
4
|
+
import { resolveKafkaJsSsl } from './resolve-ssl.js';
|
|
5
|
+
import { readKafkaLoaderOptions } from '../../utils/helpers/kafka-loader-options/index.js';
|
|
6
|
+
export default class KafkaForCore {
|
|
7
|
+
_instance;
|
|
8
|
+
_producer;
|
|
9
|
+
clientId = "";
|
|
10
|
+
brokers = "";
|
|
11
|
+
username = null;
|
|
12
|
+
password = null;
|
|
13
|
+
#system;
|
|
14
|
+
#configs;
|
|
15
|
+
constructor({ system, configs, }) {
|
|
16
|
+
this.#system = system;
|
|
17
|
+
this.#configs = configs;
|
|
18
|
+
}
|
|
19
|
+
onDispose = async () => {
|
|
20
|
+
await this.teardownKafka();
|
|
21
|
+
};
|
|
22
|
+
onInit = async () => {
|
|
23
|
+
await this.syncFromTmp();
|
|
24
|
+
bindLoaderTmpSync(this);
|
|
25
|
+
};
|
|
26
|
+
syncFromTmp = async () => {
|
|
27
|
+
await this.teardownKafka();
|
|
28
|
+
this.clientId = this.#configs.all?.kafkaClientId;
|
|
29
|
+
this.brokers = this.#configs.all?.kafkaBrokers;
|
|
30
|
+
this.username = this.#configs.all?.kafkaUsername;
|
|
31
|
+
this.password = this.#configs.all?.kafkaPassword;
|
|
32
|
+
const kafkaOpts = readKafkaLoaderOptions(this.#system?.tmp?.configs?.service?.loaders);
|
|
33
|
+
if (!kafkaOpts.enabled) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const brokersArray = (Array.isArray(this.brokers) ? this.brokers : (this.brokers?.split(',') ?? []))
|
|
37
|
+
.map(b => b?.trim())
|
|
38
|
+
.filter(Boolean);
|
|
39
|
+
if (brokersArray.length === 0) {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await this.kafkaLoader({
|
|
43
|
+
clientId: this.clientId,
|
|
44
|
+
brokers: brokersArray,
|
|
45
|
+
username: this.username,
|
|
46
|
+
password: this.password,
|
|
47
|
+
});
|
|
48
|
+
await this.initializeKafkaInfrastructure();
|
|
49
|
+
};
|
|
50
|
+
teardownKafka = async () => {
|
|
51
|
+
if (this._producer) {
|
|
52
|
+
try {
|
|
53
|
+
await this._producer.disconnect();
|
|
54
|
+
}
|
|
55
|
+
catch { }
|
|
56
|
+
this._producer = undefined;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
kafkaLoader = async ({ clientId, brokers, username, password }) => {
|
|
60
|
+
const kafkaConfig = {
|
|
61
|
+
clientId,
|
|
62
|
+
brokers,
|
|
63
|
+
sasl: (username && password) ? { mechanism: 'plain', username, password } : undefined,
|
|
64
|
+
ssl: resolveKafkaJsSsl(brokers),
|
|
65
|
+
logLevel: logLevel.ERROR,
|
|
66
|
+
logCreator: () => {
|
|
67
|
+
return ({ level, log }) => {
|
|
68
|
+
console.error(`Kafka ${log.message}`);
|
|
69
|
+
};
|
|
70
|
+
},
|
|
71
|
+
retry: {
|
|
72
|
+
initialRetryTime: 100,
|
|
73
|
+
retries: 8
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
try {
|
|
77
|
+
const kafka = new KafkaClient(kafkaConfig);
|
|
78
|
+
this._instance = kafka;
|
|
79
|
+
this._producer = kafka.producer();
|
|
80
|
+
await this.producer.connect();
|
|
81
|
+
return kafka;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
console.error(`Kafka ${error}`);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
initializeKafkaInfrastructure = async () => {
|
|
88
|
+
const kafkaOpts = readKafkaLoaderOptions(this.#system?.tmp?.configs?.service?.loaders);
|
|
89
|
+
const kafkaBrokers = this.#configs.all.kafkaBrokers;
|
|
90
|
+
const kafkaTopics = [
|
|
91
|
+
...new Set([
|
|
92
|
+
...this.#configs.all.kafkaTopics
|
|
93
|
+
])
|
|
94
|
+
];
|
|
95
|
+
if (!kafkaOpts.enabled || !kafkaBrokers) {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const topicsToCreate = Array.isArray(kafkaTopics) ? kafkaTopics : [];
|
|
99
|
+
if (topicsToCreate.length === 0)
|
|
100
|
+
return;
|
|
101
|
+
const admin = this._instance.admin();
|
|
102
|
+
try {
|
|
103
|
+
await admin.connect();
|
|
104
|
+
const existingTopics = await admin.listTopics();
|
|
105
|
+
const newTopics = topicsToCreate
|
|
106
|
+
.filter(topic => !existingTopics.includes(topic))
|
|
107
|
+
.map(topic => ({
|
|
108
|
+
topic,
|
|
109
|
+
numPartitions: 1,
|
|
110
|
+
replicationFactor: 1
|
|
111
|
+
}));
|
|
112
|
+
if (newTopics.length > 0) {
|
|
113
|
+
await admin.createTopics({
|
|
114
|
+
waitForLeaders: true,
|
|
115
|
+
topics: newTopics
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
//console.log('Core kafka error', error)
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
await admin.disconnect();
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
// => Helpers
|
|
127
|
+
sendMessage = async (topic, message) => {
|
|
128
|
+
if (!this.producer)
|
|
129
|
+
throw new Error("Producer not ready");
|
|
130
|
+
await this.producer.send({
|
|
131
|
+
topic,
|
|
132
|
+
messages: [{ value: JSON.stringify(message) }],
|
|
133
|
+
acks: 0
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
get producer() {
|
|
137
|
+
return this._producer;
|
|
138
|
+
}
|
|
139
|
+
get instance() {
|
|
140
|
+
return this._instance;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -1 +1,23 @@
|
|
|
1
|
-
import
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
/** Bare-metal SASL_SSL (9095) from KAFKA_SSL + KAFKA_SSL_CA / bare-metal Kafka TLS */
|
|
3
|
+
export function resolveKafkaJsSsl(brokers = []) {
|
|
4
|
+
const envSsl = process.env.KAFKA_SSL === 'true';
|
|
5
|
+
const portSsl = brokers.some((b) => /:9095\b/.test(b));
|
|
6
|
+
if (!envSsl && !portSsl) {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
const caPath = process.env.KAFKA_SSL_CA || '/etc/tls/infra/ca.crt';
|
|
10
|
+
try {
|
|
11
|
+
if (caPath && fs.existsSync(caPath)) {
|
|
12
|
+
return {
|
|
13
|
+
ca: [fs.readFileSync(caPath, 'utf-8')],
|
|
14
|
+
// Private CA + ts_ip broker — match infra kafka-test (no hostname verify)
|
|
15
|
+
rejectUnauthorized: false,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// fall through — still enable TLS without custom CA
|
|
21
|
+
}
|
|
22
|
+
return { rejectUnauthorized: false };
|
|
23
|
+
}
|
|
@@ -1 +1,46 @@
|
|
|
1
|
-
import
|
|
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/index.js';
|
|
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.service.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
|
+
}
|