@adaas/a-utils 0.1.19 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +45 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.mts +116 -1
- package/dist/index.d.ts +116 -1
- package/dist/index.mjs +44 -3084
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +22 -2
- package/tsup.config.ts +30 -13
- package/dist/index.js +0 -3110
- package/dist/index.js.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,3085 +1,45 @@
|
|
|
1
|
-
import { A_Feature, A_Inject, A_Scope, A_Error, A_Dependency, A_Concept, A_Container, A_TypeGuards, A_Fragment, A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY, A_CommonHelper, A_FormatterHelper, A_Component, A_Context, A_IdentityHelper, A_Entity, A_ScopeError } from '@adaas/a-concept';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
error: this.error?.toJSON()
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
|
|
48
|
-
// src/lib/A-Channel/A-Channel.error.ts
|
|
49
|
-
var A_ChannelError = class extends A_Error {
|
|
50
|
-
/**
|
|
51
|
-
* Channel Error allows to keep track of errors within a channel if something goes wrong
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
* @param originalError
|
|
55
|
-
* @param context
|
|
56
|
-
*/
|
|
57
|
-
constructor(originalError, context) {
|
|
58
|
-
if (A_TypeGuards.isString(context))
|
|
59
|
-
super(originalError, context);
|
|
60
|
-
else
|
|
61
|
-
super(originalError);
|
|
62
|
-
if (context instanceof A_OperationContext)
|
|
63
|
-
this._context = context;
|
|
64
|
-
}
|
|
65
|
-
/***
|
|
66
|
-
* Returns Context of the error
|
|
67
|
-
*/
|
|
68
|
-
get context() {
|
|
69
|
-
return this._context;
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
// ==========================================================
|
|
73
|
-
// ==================== Error Types =========================
|
|
74
|
-
// ==========================================================
|
|
75
|
-
A_ChannelError.MethodNotImplemented = "A-Channel Method Not Implemented";
|
|
76
|
-
|
|
77
|
-
// src/lib/A-Channel/A-Channel.constants.ts
|
|
78
|
-
var A_ChannelFeatures = /* @__PURE__ */ ((A_ChannelFeatures2) => {
|
|
79
|
-
A_ChannelFeatures2["onTimeout"] = "onTimeout";
|
|
80
|
-
A_ChannelFeatures2["onRetry"] = "onRetry";
|
|
81
|
-
A_ChannelFeatures2["onCircuitBreakerOpen"] = "onCircuitBreakerOpen";
|
|
82
|
-
A_ChannelFeatures2["onCache"] = "onCache";
|
|
83
|
-
A_ChannelFeatures2["onConnect"] = "onConnect";
|
|
84
|
-
A_ChannelFeatures2["onDisconnect"] = "onDisconnect";
|
|
85
|
-
A_ChannelFeatures2["onBeforeRequest"] = "onBeforeRequest";
|
|
86
|
-
A_ChannelFeatures2["onRequest"] = "onRequest";
|
|
87
|
-
A_ChannelFeatures2["onAfterRequest"] = "onAfterRequest";
|
|
88
|
-
A_ChannelFeatures2["onError"] = "onError";
|
|
89
|
-
A_ChannelFeatures2["onSend"] = "onSend";
|
|
90
|
-
A_ChannelFeatures2["onConsume"] = "onConsume";
|
|
91
|
-
return A_ChannelFeatures2;
|
|
92
|
-
})(A_ChannelFeatures || {});
|
|
93
|
-
var A_ChannelRequestStatuses = /* @__PURE__ */ ((A_ChannelRequestStatuses2) => {
|
|
94
|
-
A_ChannelRequestStatuses2["PENDING"] = "PENDING";
|
|
95
|
-
A_ChannelRequestStatuses2["SUCCESS"] = "SUCCESS";
|
|
96
|
-
A_ChannelRequestStatuses2["FAILED"] = "FAILED";
|
|
97
|
-
return A_ChannelRequestStatuses2;
|
|
98
|
-
})(A_ChannelRequestStatuses || {});
|
|
99
|
-
|
|
100
|
-
// src/lib/A-Channel/A-ChannelRequest.context.ts
|
|
101
|
-
var A_ChannelRequest = class extends A_OperationContext {
|
|
102
|
-
constructor(params) {
|
|
103
|
-
super("request", params);
|
|
104
|
-
}
|
|
105
|
-
get status() {
|
|
106
|
-
return this.result?.status;
|
|
107
|
-
}
|
|
108
|
-
get data() {
|
|
109
|
-
return this.result?.data;
|
|
110
|
-
}
|
|
111
|
-
succeed(result) {
|
|
112
|
-
const existed = this.result;
|
|
113
|
-
super.succeed({
|
|
114
|
-
...existed,
|
|
115
|
-
data: result,
|
|
116
|
-
status: "SUCCESS" /* SUCCESS */
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
};
|
|
120
|
-
|
|
121
|
-
// src/lib/A-Channel/A-Channel.component.ts
|
|
122
|
-
var A_Channel = class extends A_Component {
|
|
123
|
-
/**
|
|
124
|
-
* Creates a new A_Channel instance.
|
|
125
|
-
*
|
|
126
|
-
* The channel must be registered with A_Context before use:
|
|
127
|
-
* ```typescript
|
|
128
|
-
* const channel = new A_Channel();
|
|
129
|
-
* A_Context.root.register(channel);
|
|
130
|
-
* ```
|
|
131
|
-
*/
|
|
132
|
-
constructor() {
|
|
133
|
-
super();
|
|
134
|
-
/**
|
|
135
|
-
* Indicates whether the channel is currently processing requests.
|
|
136
|
-
* This flag is managed automatically during request/send operations.
|
|
137
|
-
*
|
|
138
|
-
* @readonly
|
|
139
|
-
*/
|
|
140
|
-
this._processing = false;
|
|
141
|
-
/**
|
|
142
|
-
* Internal cache storage for channel-specific data.
|
|
143
|
-
* Can be used by custom implementations for caching responses,
|
|
144
|
-
* connection pools, or other channel-specific state.
|
|
145
|
-
*
|
|
146
|
-
* @protected
|
|
147
|
-
*/
|
|
148
|
-
this._cache = /* @__PURE__ */ new Map();
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* Indicates whether the channel is currently processing requests.
|
|
152
|
-
*
|
|
153
|
-
* @returns {boolean} True if channel is processing, false otherwise
|
|
154
|
-
*/
|
|
155
|
-
get processing() {
|
|
156
|
-
return this._processing;
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Promise that resolves when the channel is fully initialized.
|
|
160
|
-
*
|
|
161
|
-
* Automatically calls the onConnect lifecycle hook if not already called.
|
|
162
|
-
* This ensures the channel is ready for communication operations.
|
|
163
|
-
*
|
|
164
|
-
* @returns {Promise<void>} Promise that resolves when initialization is complete
|
|
165
|
-
*/
|
|
166
|
-
get initialize() {
|
|
167
|
-
if (!this._initialized) {
|
|
168
|
-
this._initialized = this.connect();
|
|
169
|
-
}
|
|
170
|
-
return this._initialized;
|
|
171
|
-
}
|
|
172
|
-
async onConnect(...args) {
|
|
173
|
-
}
|
|
174
|
-
async onDisconnect(...args) {
|
|
175
|
-
}
|
|
176
|
-
async onBeforeRequest(...args) {
|
|
177
|
-
}
|
|
178
|
-
async onRequest(...args) {
|
|
179
|
-
}
|
|
180
|
-
async onAfterRequest(...args) {
|
|
181
|
-
}
|
|
182
|
-
async onError(...args) {
|
|
183
|
-
}
|
|
184
|
-
async onSend(...args) {
|
|
185
|
-
}
|
|
186
|
-
// ==========================================================
|
|
187
|
-
// ================= Public API Methods ===================
|
|
188
|
-
// ==========================================================
|
|
189
|
-
/**
|
|
190
|
-
* Initializes the channel by calling the onConnect lifecycle hook.
|
|
191
|
-
*
|
|
192
|
-
* This method is called automatically when accessing the `initialize` property.
|
|
193
|
-
* You can also call it manually if needed.
|
|
194
|
-
*
|
|
195
|
-
* @returns {Promise<void>} Promise that resolves when connection is established
|
|
196
|
-
*/
|
|
197
|
-
async connect() {
|
|
198
|
-
await this.call("onConnect" /* onConnect */);
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Disconnects the channel by calling the onDisconnect lifecycle hook.
|
|
202
|
-
*
|
|
203
|
-
* Use this method to properly cleanup resources when the channel is no longer needed.
|
|
204
|
-
*
|
|
205
|
-
* @returns {Promise<void>} Promise that resolves when cleanup is complete
|
|
206
|
-
*/
|
|
207
|
-
async disconnect() {
|
|
208
|
-
await this.call("onDisconnect" /* onDisconnect */);
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Sends a request and waits for a response (Request/Response pattern).
|
|
212
|
-
*
|
|
213
|
-
* This method follows the complete request lifecycle:
|
|
214
|
-
* 1. Ensures channel is initialized
|
|
215
|
-
* 2. Creates request scope and context
|
|
216
|
-
* 3. Calls onBeforeRequest hook
|
|
217
|
-
* 4. Calls onRequest hook (main processing)
|
|
218
|
-
* 5. Calls onAfterRequest hook
|
|
219
|
-
* 6. Returns the response context
|
|
220
|
-
*
|
|
221
|
-
* If any step fails, the onError hook is called and the error is captured
|
|
222
|
-
* in the returned context.
|
|
223
|
-
*
|
|
224
|
-
* @template _ParamsType The type of request parameters
|
|
225
|
-
* @template _ResultType The type of response data
|
|
226
|
-
* @param params The request parameters
|
|
227
|
-
* @returns {Promise<A_ChannelRequest<_ParamsType, _ResultType>>} Request context with response
|
|
228
|
-
*
|
|
229
|
-
* @example
|
|
230
|
-
* ```typescript
|
|
231
|
-
* // Basic usage
|
|
232
|
-
* const response = await channel.request({ action: 'getData', id: 123 });
|
|
233
|
-
*
|
|
234
|
-
* // Typed usage
|
|
235
|
-
* interface UserRequest { userId: string; }
|
|
236
|
-
* interface UserResponse { name: string; email: string; }
|
|
237
|
-
*
|
|
238
|
-
* const userResponse = await channel.request<UserRequest, UserResponse>({
|
|
239
|
-
* userId: 'user-123'
|
|
240
|
-
* });
|
|
241
|
-
*
|
|
242
|
-
* if (!userResponse.failed) {
|
|
243
|
-
* console.log('User:', userResponse.data.name);
|
|
244
|
-
* }
|
|
245
|
-
* ```
|
|
246
|
-
*/
|
|
247
|
-
async request(params) {
|
|
248
|
-
await this.initialize;
|
|
249
|
-
this._processing = true;
|
|
250
|
-
const requestScope = new A_Scope({
|
|
251
|
-
name: `a-channel@scope:request:${A_IdentityHelper.generateTimeId()}`
|
|
252
|
-
});
|
|
253
|
-
const context = new A_ChannelRequest(params);
|
|
254
|
-
try {
|
|
255
|
-
requestScope.register(context);
|
|
256
|
-
await this.call("onBeforeRequest" /* onBeforeRequest */, requestScope);
|
|
257
|
-
await this.call("onRequest" /* onRequest */, requestScope);
|
|
258
|
-
await this.call("onAfterRequest" /* onAfterRequest */, requestScope);
|
|
259
|
-
this._processing = false;
|
|
260
|
-
return context;
|
|
261
|
-
} catch (error) {
|
|
262
|
-
this._processing = false;
|
|
263
|
-
const channelError = new A_ChannelError(error);
|
|
264
|
-
context.fail(channelError);
|
|
265
|
-
requestScope.register(channelError);
|
|
266
|
-
await this.call("onError" /* onError */, requestScope);
|
|
267
|
-
requestScope.destroy();
|
|
268
|
-
throw channelError;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
/**
|
|
272
|
-
* Sends a fire-and-forget message (Send pattern).
|
|
273
|
-
*
|
|
274
|
-
* This method is used for one-way communication where no response is expected:
|
|
275
|
-
* - Event broadcasting
|
|
276
|
-
* - Notification sending
|
|
277
|
-
* - Message queuing
|
|
278
|
-
* - Logging operations
|
|
279
|
-
*
|
|
280
|
-
* The method follows this lifecycle:
|
|
281
|
-
* 1. Ensures channel is initialized
|
|
282
|
-
* 2. Creates send scope and context
|
|
283
|
-
* 3. Calls onSend hook
|
|
284
|
-
* 4. Completes without returning data
|
|
285
|
-
*
|
|
286
|
-
* If the operation fails, the onError hook is called but no error is thrown
|
|
287
|
-
* to the caller (fire-and-forget semantics).
|
|
288
|
-
*
|
|
289
|
-
* @template _ParamsType The type of message parameters
|
|
290
|
-
* @param message The message to send
|
|
291
|
-
* @returns {Promise<void>} Promise that resolves when send is complete
|
|
292
|
-
*
|
|
293
|
-
* @example
|
|
294
|
-
* ```typescript
|
|
295
|
-
* // Send notification
|
|
296
|
-
* await channel.send({
|
|
297
|
-
* type: 'user.login',
|
|
298
|
-
* userId: 'user-123',
|
|
299
|
-
* timestamp: new Date().toISOString()
|
|
300
|
-
* });
|
|
301
|
-
*
|
|
302
|
-
* // Send to message queue
|
|
303
|
-
* await channel.send({
|
|
304
|
-
* queue: 'email-queue',
|
|
305
|
-
* payload: {
|
|
306
|
-
* to: 'user@example.com',
|
|
307
|
-
* subject: 'Welcome!',
|
|
308
|
-
* body: 'Welcome to our service!'
|
|
309
|
-
* }
|
|
310
|
-
* });
|
|
311
|
-
* ```
|
|
312
|
-
*/
|
|
313
|
-
async send(message) {
|
|
314
|
-
await this.initialize;
|
|
315
|
-
this._processing = true;
|
|
316
|
-
const requestScope = new A_Scope({
|
|
317
|
-
name: `a-channel@scope:send:${A_IdentityHelper.generateTimeId()}`
|
|
318
|
-
});
|
|
319
|
-
const context = new A_OperationContext("send", message);
|
|
320
|
-
try {
|
|
321
|
-
requestScope.inherit(A_Context.scope(this));
|
|
322
|
-
requestScope.register(context);
|
|
323
|
-
await this.call("onSend" /* onSend */, requestScope);
|
|
324
|
-
this._processing = false;
|
|
325
|
-
} catch (error) {
|
|
326
|
-
this._processing = false;
|
|
327
|
-
const channelError = new A_ChannelError(error);
|
|
328
|
-
requestScope.register(channelError);
|
|
329
|
-
context.fail(channelError);
|
|
330
|
-
await this.call("onError" /* onError */, requestScope);
|
|
331
|
-
requestScope.destroy();
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* @deprecated This method is deprecated and will be removed in future versions.
|
|
336
|
-
* Use request() or send() methods instead depending on your communication pattern.
|
|
337
|
-
*
|
|
338
|
-
* For request/response pattern: Use request()
|
|
339
|
-
* For fire-and-forget pattern: Use send()
|
|
340
|
-
* For consumer patterns: Implement custom consumer logic using request() in a loop
|
|
341
|
-
*/
|
|
342
|
-
async consume() {
|
|
343
|
-
await this.initialize;
|
|
344
|
-
this._processing = true;
|
|
345
|
-
const requestScope = new A_Scope({ name: `a-channel@scope:consume:${A_IdentityHelper.generateTimeId()}` });
|
|
346
|
-
const context = new A_OperationContext("consume", {});
|
|
347
|
-
try {
|
|
348
|
-
requestScope.inherit(A_Context.scope(this));
|
|
349
|
-
requestScope.register(context);
|
|
350
|
-
await this.call("onConsume" /* onConsume */, requestScope);
|
|
351
|
-
this._processing = false;
|
|
352
|
-
return context;
|
|
353
|
-
} catch (error) {
|
|
354
|
-
this._processing = false;
|
|
355
|
-
const channelError = new A_ChannelError(error);
|
|
356
|
-
context.fail(channelError);
|
|
357
|
-
await this.call("onError" /* onError */, requestScope);
|
|
358
|
-
return context;
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
};
|
|
362
|
-
__decorateClass([
|
|
363
|
-
A_Feature.Extend({
|
|
364
|
-
name: "onConnect" /* onConnect */
|
|
365
|
-
})
|
|
366
|
-
], A_Channel.prototype, "onConnect", 1);
|
|
367
|
-
__decorateClass([
|
|
368
|
-
A_Feature.Extend({
|
|
369
|
-
name: "onDisconnect" /* onDisconnect */
|
|
370
|
-
})
|
|
371
|
-
], A_Channel.prototype, "onDisconnect", 1);
|
|
372
|
-
__decorateClass([
|
|
373
|
-
A_Feature.Extend({
|
|
374
|
-
name: "onBeforeRequest" /* onBeforeRequest */
|
|
375
|
-
})
|
|
376
|
-
], A_Channel.prototype, "onBeforeRequest", 1);
|
|
377
|
-
__decorateClass([
|
|
378
|
-
A_Feature.Extend({
|
|
379
|
-
name: "onRequest" /* onRequest */
|
|
380
|
-
})
|
|
381
|
-
], A_Channel.prototype, "onRequest", 1);
|
|
382
|
-
__decorateClass([
|
|
383
|
-
A_Feature.Extend({
|
|
384
|
-
name: "onAfterRequest" /* onAfterRequest */
|
|
385
|
-
})
|
|
386
|
-
], A_Channel.prototype, "onAfterRequest", 1);
|
|
387
|
-
__decorateClass([
|
|
388
|
-
A_Feature.Extend({
|
|
389
|
-
name: "onError" /* onError */
|
|
390
|
-
})
|
|
391
|
-
], A_Channel.prototype, "onError", 1);
|
|
392
|
-
__decorateClass([
|
|
393
|
-
A_Feature.Extend({
|
|
394
|
-
name: "onSend" /* onSend */
|
|
395
|
-
})
|
|
396
|
-
], A_Channel.prototype, "onSend", 1);
|
|
397
|
-
|
|
398
|
-
// src/lib/A-Command/A-Command.constants.ts
|
|
399
|
-
var A_Command_Status = /* @__PURE__ */ ((A_Command_Status2) => {
|
|
400
|
-
A_Command_Status2["CREATED"] = "CREATED";
|
|
401
|
-
A_Command_Status2["INITIALIZED"] = "INITIALIZED";
|
|
402
|
-
A_Command_Status2["COMPILED"] = "COMPILED";
|
|
403
|
-
A_Command_Status2["EXECUTING"] = "EXECUTING";
|
|
404
|
-
A_Command_Status2["COMPLETED"] = "COMPLETED";
|
|
405
|
-
A_Command_Status2["FAILED"] = "FAILED";
|
|
406
|
-
return A_Command_Status2;
|
|
407
|
-
})(A_Command_Status || {});
|
|
408
|
-
var A_CommandTransitions = /* @__PURE__ */ ((A_CommandTransitions2) => {
|
|
409
|
-
A_CommandTransitions2["CREATED_TO_INITIALIZED"] = "created_initialized";
|
|
410
|
-
A_CommandTransitions2["INITIALIZED_TO_EXECUTING"] = "initialized_executing";
|
|
411
|
-
A_CommandTransitions2["EXECUTING_TO_COMPLETED"] = "executing_completed";
|
|
412
|
-
A_CommandTransitions2["EXECUTING_TO_FAILED"] = "executing_failed";
|
|
413
|
-
return A_CommandTransitions2;
|
|
414
|
-
})(A_CommandTransitions || {});
|
|
415
|
-
var A_CommandFeatures = /* @__PURE__ */ ((A_CommandFeatures2) => {
|
|
416
|
-
A_CommandFeatures2["onInit"] = "onInit";
|
|
417
|
-
A_CommandFeatures2["onBeforeExecute"] = "onBeforeExecute";
|
|
418
|
-
A_CommandFeatures2["onExecute"] = "onExecute";
|
|
419
|
-
A_CommandFeatures2["onAfterExecute"] = "onAfterExecute";
|
|
420
|
-
A_CommandFeatures2["onComplete"] = "onComplete";
|
|
421
|
-
A_CommandFeatures2["onFail"] = "onFail";
|
|
422
|
-
A_CommandFeatures2["onError"] = "onError";
|
|
423
|
-
return A_CommandFeatures2;
|
|
424
|
-
})(A_CommandFeatures || {});
|
|
425
|
-
var A_CommandError = class extends A_Error {
|
|
426
|
-
};
|
|
427
|
-
A_CommandError.CommandScopeBindingError = "A-Command Scope Binding Error";
|
|
428
|
-
A_CommandError.ExecutionError = "A-Command Execution Error";
|
|
429
|
-
A_CommandError.ResultProcessingError = "A-Command Result Processing Error";
|
|
430
|
-
/**
|
|
431
|
-
* Error indicating that the command was interrupted during execution
|
|
432
|
-
*/
|
|
433
|
-
A_CommandError.CommandInterruptedError = "A-Command Interrupted Error";
|
|
434
|
-
var A_StateMachineError = class extends A_Error {
|
|
435
|
-
};
|
|
436
|
-
A_StateMachineError.InitializationError = "A-StateMachine Initialization Error";
|
|
437
|
-
A_StateMachineError.TransitionError = "A-StateMachine Transition Error";
|
|
438
|
-
|
|
439
|
-
// src/lib/A-StateMachine/A-StateMachineTransition.context.ts
|
|
440
|
-
var A_StateMachineTransition = class extends A_OperationContext {
|
|
441
|
-
constructor(params) {
|
|
442
|
-
super(
|
|
443
|
-
"a-state-machine-transition",
|
|
444
|
-
params
|
|
445
|
-
);
|
|
446
|
-
this._meta.set("from", params.from);
|
|
447
|
-
this._meta.set("to", params.to);
|
|
448
|
-
}
|
|
449
|
-
get from() {
|
|
450
|
-
return this._meta.get("from");
|
|
451
|
-
}
|
|
452
|
-
get to() {
|
|
453
|
-
return this._meta.get("to");
|
|
454
|
-
}
|
|
455
|
-
};
|
|
456
|
-
|
|
457
|
-
// src/lib/A-StateMachine/A-StateMachine.component.ts
|
|
458
|
-
var _a, _b, _c, _d;
|
|
459
|
-
var A_StateMachine = class extends A_Component {
|
|
460
|
-
/**
|
|
461
|
-
* Gets a promise that resolves when the state machine is fully initialized and ready for transitions.
|
|
462
|
-
* This ensures that all initialization hooks have been executed before allowing state transitions.
|
|
463
|
-
*
|
|
464
|
-
* @returns Promise<void> that resolves when initialization is complete
|
|
465
|
-
*
|
|
466
|
-
* @example
|
|
467
|
-
* ```typescript
|
|
468
|
-
* const stateMachine = new MyStateMachine();
|
|
469
|
-
* await stateMachine.ready; // Wait for initialization
|
|
470
|
-
* await stateMachine.transition('idle', 'running');
|
|
471
|
-
* ```
|
|
472
|
-
*/
|
|
473
|
-
get ready() {
|
|
474
|
-
if (!this._initialized) {
|
|
475
|
-
this._initialized = this.call("onInitialize" /* onInitialize */);
|
|
476
|
-
}
|
|
477
|
-
return this._initialized;
|
|
478
|
-
}
|
|
479
|
-
async [_d = "onInitialize" /* onInitialize */](...args) {
|
|
480
|
-
}
|
|
481
|
-
async [_c = "onBeforeTransition" /* onBeforeTransition */](...args) {
|
|
482
|
-
}
|
|
483
|
-
async [_b = "onAfterTransition" /* onAfterTransition */](...args) {
|
|
484
|
-
}
|
|
485
|
-
async [_a = "onError" /* onError */](...args) {
|
|
486
|
-
}
|
|
487
|
-
/**
|
|
488
|
-
* Executes a state transition from one state to another.
|
|
489
|
-
* This is the core method of the state machine that handles the complete transition lifecycle.
|
|
490
|
-
*
|
|
491
|
-
* @param from - The state to transition from (must be a key of T)
|
|
492
|
-
* @param to - The state to transition to (must be a key of T)
|
|
493
|
-
* @param props - Optional properties to pass to the transition context (should match T[keyof T])
|
|
494
|
-
* @returns Promise<void> that resolves when the transition is complete
|
|
495
|
-
*
|
|
496
|
-
* @throws {A_StateMachineError} When the transition fails for any reason
|
|
497
|
-
*
|
|
498
|
-
* @example
|
|
499
|
-
* ```typescript
|
|
500
|
-
* interface OrderStates {
|
|
501
|
-
* pending: { orderId: string };
|
|
502
|
-
* processing: { orderId: string; processedBy: string };
|
|
503
|
-
* }
|
|
504
|
-
*
|
|
505
|
-
* const orderMachine = new A_StateMachine<OrderStates>();
|
|
506
|
-
*
|
|
507
|
-
* // Transition with props
|
|
508
|
-
* await orderMachine.transition('pending', 'processing', {
|
|
509
|
-
* orderId: '12345',
|
|
510
|
-
* processedBy: 'user-456'
|
|
511
|
-
* });
|
|
512
|
-
* ```
|
|
513
|
-
*
|
|
514
|
-
* The transition process follows this lifecycle:
|
|
515
|
-
* 1. Wait for state machine initialization (ready)
|
|
516
|
-
* 2. Create transition name in camelCase format (e.g., "pending_processing")
|
|
517
|
-
* 3. Create operation context with transition data
|
|
518
|
-
* 4. Create isolated scope for the transition
|
|
519
|
-
* 5. Call onBeforeTransition hook
|
|
520
|
-
* 6. Execute the specific transition method (if defined)
|
|
521
|
-
* 7. Call onAfterTransition hook
|
|
522
|
-
* 8. Clean up scope and return result
|
|
523
|
-
*
|
|
524
|
-
* If any step fails, the onError hook is called and a wrapped error is thrown.
|
|
525
|
-
*/
|
|
526
|
-
async transition(from, to, props) {
|
|
527
|
-
await this.ready;
|
|
528
|
-
const transitionName = `${A_FormatterHelper.toCamelCase(String(from))}_${A_FormatterHelper.toCamelCase(String(to))}`;
|
|
529
|
-
const transition = new A_StateMachineTransition({
|
|
530
|
-
from: String(from),
|
|
531
|
-
to: String(to),
|
|
532
|
-
props
|
|
533
|
-
});
|
|
534
|
-
const scope = new A_Scope({
|
|
535
|
-
name: `A-StateMachine-Transition-Scope-${transitionName}`,
|
|
536
|
-
fragments: [transition]
|
|
537
|
-
});
|
|
538
|
-
try {
|
|
539
|
-
await this.call("onBeforeTransition" /* onBeforeTransition */, scope);
|
|
540
|
-
await this.call(transitionName, scope);
|
|
541
|
-
await this.call("onAfterTransition" /* onAfterTransition */, scope);
|
|
542
|
-
scope.destroy();
|
|
543
|
-
return transition.result;
|
|
544
|
-
} catch (error) {
|
|
545
|
-
const wrappedError = new A_StateMachineError({
|
|
546
|
-
title: A_StateMachineError.TransitionError,
|
|
547
|
-
description: `An error occurred while transitioning to "${transitionName}"`,
|
|
548
|
-
originalError: error
|
|
549
|
-
});
|
|
550
|
-
scope.register(wrappedError);
|
|
551
|
-
await this.call("onError" /* onError */, scope);
|
|
552
|
-
scope.destroy();
|
|
553
|
-
throw wrappedError;
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
};
|
|
557
|
-
__decorateClass([
|
|
558
|
-
A_Feature.Extend()
|
|
559
|
-
], A_StateMachine.prototype, _d, 1);
|
|
560
|
-
__decorateClass([
|
|
561
|
-
A_Feature.Extend()
|
|
562
|
-
], A_StateMachine.prototype, _c, 1);
|
|
563
|
-
__decorateClass([
|
|
564
|
-
A_Feature.Extend()
|
|
565
|
-
], A_StateMachine.prototype, _b, 1);
|
|
566
|
-
__decorateClass([
|
|
567
|
-
A_Feature.Extend()
|
|
568
|
-
], A_StateMachine.prototype, _a, 1);
|
|
569
|
-
|
|
570
|
-
// src/lib/A-Config/A-Config.constants.ts
|
|
571
|
-
var A_CONSTANTS__CONFIG_ENV_VARIABLES = {};
|
|
572
|
-
var A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY = [];
|
|
573
|
-
|
|
574
|
-
// src/lib/A-Config/A-Config.context.ts
|
|
575
|
-
var A_Config = class extends A_Fragment {
|
|
576
|
-
constructor(config) {
|
|
577
|
-
super({
|
|
578
|
-
name: "A_Config"
|
|
579
|
-
});
|
|
580
|
-
this.VARIABLES = /* @__PURE__ */ new Map();
|
|
581
|
-
this.DEFAULT_ALLOWED_TO_READ_PROPERTIES = [
|
|
582
|
-
...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,
|
|
583
|
-
...A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY
|
|
584
|
-
];
|
|
585
|
-
this.config = A_CommonHelper.deepCloneAndMerge(config, {
|
|
586
|
-
strict: false,
|
|
587
|
-
defaults: {},
|
|
588
|
-
variables: A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY
|
|
589
|
-
});
|
|
590
|
-
this.CONFIG_PROPERTIES = this.config.variables ? this.config.variables : [];
|
|
591
|
-
this.config.variables.forEach((variable) => {
|
|
592
|
-
this.VARIABLES.set(
|
|
593
|
-
A_FormatterHelper.toUpperSnakeCase(variable),
|
|
594
|
-
this.config.defaults[variable]
|
|
595
|
-
);
|
|
596
|
-
});
|
|
597
|
-
}
|
|
598
|
-
/**
|
|
599
|
-
* This method is used to get the configuration property by name
|
|
600
|
-
*
|
|
601
|
-
* @param property
|
|
602
|
-
* @returns
|
|
603
|
-
*/
|
|
604
|
-
get(property) {
|
|
605
|
-
if (this.CONFIG_PROPERTIES.includes(property) || this.DEFAULT_ALLOWED_TO_READ_PROPERTIES.includes(property) || !this.config.strict)
|
|
606
|
-
return this.VARIABLES.get(A_FormatterHelper.toUpperSnakeCase(property));
|
|
607
|
-
throw new Error("Property not exists or not allowed to read");
|
|
608
|
-
}
|
|
609
|
-
set(property, value) {
|
|
610
|
-
const array = Array.isArray(property) ? property : typeof property === "string" ? [{ property, value }] : Object.keys(property).map((key) => ({
|
|
611
|
-
property: key,
|
|
612
|
-
value: property[key]
|
|
613
|
-
}));
|
|
614
|
-
for (const { property: property2, value: value2 } of array) {
|
|
615
|
-
let targetValue = value2 ? value2 : this.config?.defaults ? this.config.defaults[property2] : void 0;
|
|
616
|
-
this.VARIABLES.set(A_FormatterHelper.toUpperSnakeCase(property2), targetValue);
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
};
|
|
620
|
-
|
|
621
|
-
// src/lib/A-Logger/A-Logger.constants.ts
|
|
622
|
-
var A_LOGGER_DEFAULT_SCOPE_LENGTH = 20;
|
|
623
|
-
var A_LOGGER_COLORS = {
|
|
624
|
-
// System colors (reserved for specific purposes)
|
|
625
|
-
red: "31",
|
|
626
|
-
// Errors, critical issues
|
|
627
|
-
yellow: "33",
|
|
628
|
-
// Warnings, caution messages
|
|
629
|
-
green: "32",
|
|
630
|
-
// Success, completion messages
|
|
631
|
-
// Safe palette for random selection (grey-blue-violet theme)
|
|
632
|
-
blue: "34",
|
|
633
|
-
// Info, general messages
|
|
634
|
-
cyan: "36",
|
|
635
|
-
// Headers, titles
|
|
636
|
-
magenta: "35",
|
|
637
|
-
// Special highlighting
|
|
638
|
-
gray: "90",
|
|
639
|
-
// Debug, less important info
|
|
640
|
-
brightBlue: "94",
|
|
641
|
-
// Bright blue variant
|
|
642
|
-
brightCyan: "96",
|
|
643
|
-
// Bright cyan variant
|
|
644
|
-
brightMagenta: "95",
|
|
645
|
-
// Bright magenta variant
|
|
646
|
-
darkGray: "30",
|
|
647
|
-
// Dark gray
|
|
648
|
-
lightGray: "37",
|
|
649
|
-
// Light gray (white)
|
|
650
|
-
// Extended blue-violet palette
|
|
651
|
-
indigo: "38;5;54",
|
|
652
|
-
// Deep indigo
|
|
653
|
-
violet: "38;5;93",
|
|
654
|
-
// Violet
|
|
655
|
-
purple: "38;5;129",
|
|
656
|
-
// Purple
|
|
657
|
-
lavender: "38;5;183",
|
|
658
|
-
// Lavender
|
|
659
|
-
skyBlue: "38;5;117",
|
|
660
|
-
// Sky blue
|
|
661
|
-
steelBlue: "38;5;67",
|
|
662
|
-
// Steel blue
|
|
663
|
-
slateBlue: "38;5;62",
|
|
664
|
-
// Slate blue
|
|
665
|
-
deepBlue: "38;5;18",
|
|
666
|
-
// Deep blue
|
|
667
|
-
lightBlue: "38;5;153",
|
|
668
|
-
// Light blue
|
|
669
|
-
periwinkle: "38;5;111",
|
|
670
|
-
// Periwinkle
|
|
671
|
-
cornflower: "38;5;69",
|
|
672
|
-
// Cornflower blue
|
|
673
|
-
powder: "38;5;152",
|
|
674
|
-
// Powder blue
|
|
675
|
-
// Additional grays for variety
|
|
676
|
-
charcoal: "38;5;236",
|
|
677
|
-
// Charcoal
|
|
678
|
-
silver: "38;5;250",
|
|
679
|
-
// Silver
|
|
680
|
-
smoke: "38;5;244",
|
|
681
|
-
// Smoke gray
|
|
682
|
-
slate: "38;5;240"
|
|
683
|
-
// Slate gray
|
|
684
|
-
};
|
|
685
|
-
var A_LOGGER_SAFE_RANDOM_COLORS = [
|
|
686
|
-
"blue",
|
|
687
|
-
"cyan",
|
|
688
|
-
"magenta",
|
|
689
|
-
"gray",
|
|
690
|
-
"brightBlue",
|
|
691
|
-
"brightCyan",
|
|
692
|
-
"brightMagenta",
|
|
693
|
-
"darkGray",
|
|
694
|
-
"lightGray",
|
|
695
|
-
"indigo",
|
|
696
|
-
"violet",
|
|
697
|
-
"purple",
|
|
698
|
-
"lavender",
|
|
699
|
-
"skyBlue",
|
|
700
|
-
"steelBlue",
|
|
701
|
-
"slateBlue",
|
|
702
|
-
"deepBlue",
|
|
703
|
-
"lightBlue",
|
|
704
|
-
"periwinkle",
|
|
705
|
-
"cornflower",
|
|
706
|
-
"powder",
|
|
707
|
-
"charcoal",
|
|
708
|
-
"silver",
|
|
709
|
-
"smoke",
|
|
710
|
-
"slate"
|
|
711
|
-
];
|
|
712
|
-
var A_LOGGER_ANSI = {
|
|
713
|
-
RESET: "\x1B[0m",
|
|
714
|
-
PREFIX: "\x1B[",
|
|
715
|
-
SUFFIX: "m"
|
|
716
|
-
};
|
|
717
|
-
var A_LOGGER_TIME_FORMAT = {
|
|
718
|
-
MINUTES_PAD: 2,
|
|
719
|
-
SECONDS_PAD: 2,
|
|
720
|
-
MILLISECONDS_PAD: 3,
|
|
721
|
-
SEPARATOR: ":"
|
|
722
|
-
};
|
|
723
|
-
var A_LOGGER_FORMAT = {
|
|
724
|
-
SCOPE_OPEN: "[",
|
|
725
|
-
SCOPE_CLOSE: "]",
|
|
726
|
-
TIME_OPEN: "|",
|
|
727
|
-
TIME_CLOSE: "|",
|
|
728
|
-
SEPARATOR: "-------------------------------",
|
|
729
|
-
PIPE: "| "
|
|
730
|
-
};
|
|
731
|
-
var A_LOGGER_ENV_KEYS = {
|
|
732
|
-
LOG_LEVEL: "A_LOGGER_LEVEL",
|
|
733
|
-
DEFAULT_SCOPE_LENGTH: "A_LOGGER_DEFAULT_SCOPE_LENGTH",
|
|
734
|
-
DEFAULT_SCOPE_COLOR: "A_LOGGER_DEFAULT_SCOPE_COLOR",
|
|
735
|
-
DEFAULT_LOG_COLOR: "A_LOGGER_DEFAULT_LOG_COLOR"
|
|
736
|
-
};
|
|
737
|
-
|
|
738
|
-
// src/lib/A-Logger/A-Logger.component.ts
|
|
739
|
-
var A_Logger = class extends A_Component {
|
|
740
|
-
// =============================================
|
|
741
|
-
// Constructor and Initialization
|
|
742
|
-
// =============================================
|
|
743
|
-
/**
|
|
744
|
-
* Initialize A_Logger with dependency injection
|
|
745
|
-
* Colors are configured through A_Config or generated randomly if not provided
|
|
746
|
-
*
|
|
747
|
-
* @param scope - The current scope context for message prefixing
|
|
748
|
-
* @param config - Optional configuration for log level filtering and color settings
|
|
749
|
-
*/
|
|
750
|
-
constructor(scope, config) {
|
|
751
|
-
super();
|
|
752
|
-
this.scope = scope;
|
|
753
|
-
this.config = config;
|
|
754
|
-
this.COLORS = A_LOGGER_COLORS;
|
|
755
|
-
this.STANDARD_SCOPE_LENGTH = config?.get(A_LOGGER_ENV_KEYS.DEFAULT_SCOPE_LENGTH) || A_LOGGER_DEFAULT_SCOPE_LENGTH;
|
|
756
|
-
const configScopeColor = config?.get(A_LOGGER_ENV_KEYS.DEFAULT_SCOPE_COLOR);
|
|
757
|
-
const configLogColor = config?.get(A_LOGGER_ENV_KEYS.DEFAULT_LOG_COLOR);
|
|
758
|
-
if (configScopeColor || configLogColor) {
|
|
759
|
-
this.DEFAULT_SCOPE_COLOR = configScopeColor || this.generateColorFromScopeName(this.scope.name);
|
|
760
|
-
this.DEFAULT_LOG_COLOR = configLogColor || this.generateColorFromScopeName(this.scope.name);
|
|
761
|
-
} else {
|
|
762
|
-
const complementaryColors = this.generateComplementaryColorsFromScope(this.scope.name);
|
|
763
|
-
this.DEFAULT_SCOPE_COLOR = complementaryColors.scopeColor;
|
|
764
|
-
this.DEFAULT_LOG_COLOR = complementaryColors.logColor;
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
// =============================================
|
|
768
|
-
// Color Generation Utilities
|
|
769
|
-
// =============================================
|
|
770
|
-
/**
|
|
771
|
-
* Generate a simple hash from a string
|
|
772
|
-
* Used to create deterministic color selection based on scope name
|
|
773
|
-
*
|
|
774
|
-
* @param str - The string to hash
|
|
775
|
-
* @returns A numeric hash value
|
|
776
|
-
*/
|
|
777
|
-
simpleHash(str) {
|
|
778
|
-
let hash = 0;
|
|
779
|
-
for (let i = 0; i < str.length; i++) {
|
|
780
|
-
const char = str.charCodeAt(i);
|
|
781
|
-
hash = (hash << 5) - hash + char;
|
|
782
|
-
hash = hash & hash;
|
|
783
|
-
}
|
|
784
|
-
return Math.abs(hash);
|
|
785
|
-
}
|
|
786
|
-
/**
|
|
787
|
-
* Generate a deterministic color based on scope name
|
|
788
|
-
* Same scope names will always get the same color, but uses safe color palette
|
|
789
|
-
*
|
|
790
|
-
* @param scopeName - The scope name to generate color for
|
|
791
|
-
* @returns A color key from the safe colors palette
|
|
792
|
-
*/
|
|
793
|
-
generateColorFromScopeName(scopeName) {
|
|
794
|
-
const safeColors = A_LOGGER_SAFE_RANDOM_COLORS;
|
|
795
|
-
const hash = this.simpleHash(scopeName);
|
|
796
|
-
const colorIndex = hash % safeColors.length;
|
|
797
|
-
return safeColors[colorIndex];
|
|
798
|
-
}
|
|
799
|
-
/**
|
|
800
|
-
* Generate a pair of complementary colors based on scope name
|
|
801
|
-
* Ensures visual harmony between scope and message colors while being deterministic
|
|
802
|
-
*
|
|
803
|
-
* @param scopeName - The scope name to base colors on
|
|
804
|
-
* @returns Object with scopeColor and logColor that work well together
|
|
805
|
-
*/
|
|
806
|
-
generateComplementaryColorsFromScope(scopeName) {
|
|
807
|
-
const colorPairs = [
|
|
808
|
-
{ scopeColor: "indigo", logColor: "lightBlue" },
|
|
809
|
-
{ scopeColor: "deepBlue", logColor: "cyan" },
|
|
810
|
-
{ scopeColor: "purple", logColor: "lavender" },
|
|
811
|
-
{ scopeColor: "steelBlue", logColor: "skyBlue" },
|
|
812
|
-
{ scopeColor: "slateBlue", logColor: "periwinkle" },
|
|
813
|
-
{ scopeColor: "charcoal", logColor: "silver" },
|
|
814
|
-
{ scopeColor: "violet", logColor: "brightMagenta" },
|
|
815
|
-
{ scopeColor: "darkGray", logColor: "lightGray" },
|
|
816
|
-
{ scopeColor: "cornflower", logColor: "powder" },
|
|
817
|
-
{ scopeColor: "slate", logColor: "smoke" }
|
|
818
|
-
];
|
|
819
|
-
const hash = this.simpleHash(scopeName);
|
|
820
|
-
const pairIndex = hash % colorPairs.length;
|
|
821
|
-
return colorPairs[pairIndex];
|
|
822
|
-
}
|
|
823
|
-
// =============================================
|
|
824
|
-
// Factory Methods
|
|
825
|
-
// =============================================
|
|
826
|
-
// =============================================
|
|
827
|
-
// Scope and Formatting Utilities
|
|
828
|
-
// =============================================
|
|
829
|
-
/**
|
|
830
|
-
* Get the formatted scope length for consistent message alignment
|
|
831
|
-
* Uses a standard length to ensure all messages align properly regardless of scope name
|
|
832
|
-
*
|
|
833
|
-
* @returns The scope length to use for padding calculations
|
|
834
|
-
*/
|
|
835
|
-
get scopeLength() {
|
|
836
|
-
return Math.max(this.scope.name.length, this.STANDARD_SCOPE_LENGTH);
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* Get the formatted scope name with proper padding, centered within the container
|
|
840
|
-
* Ensures consistent width for all scope names in log output with centered alignment
|
|
841
|
-
*
|
|
842
|
-
* @returns Centered and padded scope name for consistent formatting
|
|
843
|
-
*/
|
|
844
|
-
get formattedScope() {
|
|
845
|
-
const scopeName = this.scope.name;
|
|
846
|
-
const totalLength = this.STANDARD_SCOPE_LENGTH;
|
|
847
|
-
if (scopeName.length >= totalLength) {
|
|
848
|
-
return scopeName.substring(0, totalLength);
|
|
849
|
-
}
|
|
850
|
-
const totalPadding = totalLength - scopeName.length;
|
|
851
|
-
const leftPadding = Math.floor(totalPadding / 2);
|
|
852
|
-
const rightPadding = totalPadding - leftPadding;
|
|
853
|
-
return " ".repeat(leftPadding) + scopeName + " ".repeat(rightPadding);
|
|
854
|
-
}
|
|
855
|
-
// =============================================
|
|
856
|
-
// Message Compilation and Formatting
|
|
857
|
-
// =============================================
|
|
858
|
-
/**
|
|
859
|
-
* Compile log arguments into formatted console output with colors and proper alignment
|
|
860
|
-
*
|
|
861
|
-
* This method handles the core formatting logic for all log messages:
|
|
862
|
-
* - Applies separate colors for scope and message content
|
|
863
|
-
* - Formats scope names with consistent padding
|
|
864
|
-
* - Handles different data types appropriately
|
|
865
|
-
* - Maintains proper indentation for multi-line content
|
|
866
|
-
*
|
|
867
|
-
* @param messageColor - The color key to apply to the message content
|
|
868
|
-
* @param args - Variable arguments to format and display
|
|
869
|
-
* @returns Array of formatted strings ready for console output
|
|
870
|
-
*/
|
|
871
|
-
compile(messageColor, ...args) {
|
|
872
|
-
const timeString = this.getTime();
|
|
873
|
-
const scopePadding = " ".repeat(this.scopeLength + 3);
|
|
874
|
-
const isMultiArg = args.length > 1;
|
|
875
|
-
return [
|
|
876
|
-
// Header with separate colors for scope and message content
|
|
877
|
-
`${A_LOGGER_ANSI.PREFIX}${this.COLORS[this.DEFAULT_SCOPE_COLOR]}${A_LOGGER_ANSI.SUFFIX}${A_LOGGER_FORMAT.SCOPE_OPEN}${this.formattedScope}${A_LOGGER_FORMAT.SCOPE_CLOSE}${A_LOGGER_ANSI.RESET} ${A_LOGGER_ANSI.PREFIX}${this.COLORS[messageColor]}${A_LOGGER_ANSI.SUFFIX}${A_LOGGER_FORMAT.TIME_OPEN}${timeString}${A_LOGGER_FORMAT.TIME_CLOSE}`,
|
|
878
|
-
// Top separator for multi-argument messages
|
|
879
|
-
isMultiArg ? `
|
|
880
|
-
${scopePadding}${A_LOGGER_FORMAT.TIME_OPEN}${A_LOGGER_FORMAT.SEPARATOR}` : "",
|
|
881
|
-
// Process each argument with appropriate formatting
|
|
882
|
-
...args.map((arg, i) => {
|
|
883
|
-
const shouldAddNewline = i > 0 || isMultiArg;
|
|
884
|
-
switch (true) {
|
|
885
|
-
case arg instanceof A_Error:
|
|
886
|
-
return this.compile_A_Error(arg);
|
|
887
|
-
case arg instanceof Error:
|
|
888
|
-
return this.compile_Error(arg);
|
|
889
|
-
case (typeof arg === "object" && arg !== null):
|
|
890
|
-
return this.formatObject(arg, shouldAddNewline, scopePadding);
|
|
891
|
-
default:
|
|
892
|
-
return this.formatString(String(arg), shouldAddNewline, scopePadding);
|
|
893
|
-
}
|
|
894
|
-
}),
|
|
895
|
-
// Bottom separator and color reset
|
|
896
|
-
isMultiArg ? `
|
|
897
|
-
${scopePadding}${A_LOGGER_FORMAT.TIME_OPEN}${A_LOGGER_FORMAT.SEPARATOR}${A_LOGGER_ANSI.RESET}` : A_LOGGER_ANSI.RESET
|
|
898
|
-
];
|
|
899
|
-
}
|
|
900
|
-
/**
|
|
901
|
-
* Format an object for display with proper JSON indentation
|
|
902
|
-
*
|
|
903
|
-
* @param obj - The object to format
|
|
904
|
-
* @param shouldAddNewline - Whether to add a newline prefix
|
|
905
|
-
* @param scopePadding - The padding string for consistent alignment
|
|
906
|
-
* @returns Formatted object string
|
|
907
|
-
*/
|
|
908
|
-
formatObject(obj, shouldAddNewline, scopePadding) {
|
|
909
|
-
let jsonString;
|
|
910
|
-
try {
|
|
911
|
-
jsonString = JSON.stringify(obj, null, 2);
|
|
912
|
-
} catch (error) {
|
|
913
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
914
|
-
jsonString = JSON.stringify(obj, (key, value) => {
|
|
915
|
-
if (typeof value === "object" && value !== null) {
|
|
916
|
-
if (seen.has(value)) {
|
|
917
|
-
return "[Circular Reference]";
|
|
918
|
-
}
|
|
919
|
-
seen.add(value);
|
|
920
|
-
}
|
|
921
|
-
return value;
|
|
922
|
-
}, 2);
|
|
923
|
-
}
|
|
924
|
-
const formatted = jsonString.replace(/\n/g, `
|
|
925
|
-
${scopePadding}${A_LOGGER_FORMAT.PIPE}`);
|
|
926
|
-
return shouldAddNewline ? `
|
|
927
|
-
${scopePadding}${A_LOGGER_FORMAT.PIPE}` + formatted : formatted;
|
|
928
|
-
}
|
|
929
|
-
/**
|
|
930
|
-
* Format a string for display with proper indentation
|
|
931
|
-
*
|
|
932
|
-
* @param str - The string to format
|
|
933
|
-
* @param shouldAddNewline - Whether to add a newline prefix
|
|
934
|
-
* @param scopePadding - The padding string for consistent alignment
|
|
935
|
-
* @returns Formatted string
|
|
936
|
-
*/
|
|
937
|
-
formatString(str, shouldAddNewline, scopePadding) {
|
|
938
|
-
const prefix = shouldAddNewline ? "\n" : "";
|
|
939
|
-
return (prefix + str).replace(/\n/g, `
|
|
940
|
-
${scopePadding}${A_LOGGER_FORMAT.PIPE}`);
|
|
941
|
-
}
|
|
942
|
-
// =============================================
|
|
943
|
-
// Log Level Management
|
|
944
|
-
// =============================================
|
|
945
|
-
/**
|
|
946
|
-
* Determine if a log message should be output based on configured log level
|
|
947
|
-
*
|
|
948
|
-
* Log level hierarchy:
|
|
949
|
-
* - debug: Shows all messages (debug, info, warning, error)
|
|
950
|
-
* - info: Shows info, warning, and error messages
|
|
951
|
-
* - warn: Shows warning and error messages only
|
|
952
|
-
* - error: Shows error messages only
|
|
953
|
-
* - all: Shows all messages (alias for debug)
|
|
954
|
-
*
|
|
955
|
-
* @param logMethod - The type of log method being called
|
|
956
|
-
* @returns True if the message should be logged, false otherwise
|
|
957
|
-
*/
|
|
958
|
-
shouldLog(logMethod) {
|
|
959
|
-
const shouldLog = this.config?.get(A_LOGGER_ENV_KEYS.LOG_LEVEL) || "info";
|
|
960
|
-
switch (shouldLog) {
|
|
961
|
-
case "debug":
|
|
962
|
-
return true;
|
|
963
|
-
case "info":
|
|
964
|
-
return logMethod === "info" || logMethod === "warning" || logMethod === "error";
|
|
965
|
-
case "warn":
|
|
966
|
-
return logMethod === "warning" || logMethod === "error";
|
|
967
|
-
case "error":
|
|
968
|
-
return logMethod === "error";
|
|
969
|
-
case "all":
|
|
970
|
-
return true;
|
|
971
|
-
default:
|
|
972
|
-
return false;
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
debug(param1, ...args) {
|
|
976
|
-
if (!this.shouldLog("debug")) return;
|
|
977
|
-
if (typeof param1 === "string" && this.COLORS[param1]) {
|
|
978
|
-
console.log(...this.compile(param1, ...args));
|
|
979
|
-
} else {
|
|
980
|
-
console.log(...this.compile(this.DEFAULT_LOG_COLOR, param1, ...args));
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
info(param1, ...args) {
|
|
984
|
-
if (!this.shouldLog("info")) return;
|
|
985
|
-
if (typeof param1 === "string" && this.COLORS[param1]) {
|
|
986
|
-
console.log(...this.compile(param1, ...args));
|
|
987
|
-
} else {
|
|
988
|
-
console.log(...this.compile(this.DEFAULT_LOG_COLOR, param1, ...args));
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
log(param1, ...args) {
|
|
992
|
-
this.info(param1, ...args);
|
|
993
|
-
}
|
|
994
|
-
/**
|
|
995
|
-
* Log warning messages with yellow color coding
|
|
996
|
-
*
|
|
997
|
-
* Use for non-critical issues that should be brought to attention
|
|
998
|
-
* but don't prevent normal operation
|
|
999
|
-
*
|
|
1000
|
-
* @param args - Arguments to log as warnings
|
|
1001
|
-
*
|
|
1002
|
-
* @example
|
|
1003
|
-
* ```typescript
|
|
1004
|
-
* logger.warning('Deprecated method used');
|
|
1005
|
-
* logger.warning('Rate limit approaching:', { current: 95, limit: 100 });
|
|
1006
|
-
* ```
|
|
1007
|
-
*/
|
|
1008
|
-
warning(...args) {
|
|
1009
|
-
if (!this.shouldLog("warning")) return;
|
|
1010
|
-
console.log(...this.compile("yellow", ...args));
|
|
1011
|
-
}
|
|
1012
|
-
/**
|
|
1013
|
-
* Log error messages with red color coding
|
|
1014
|
-
*
|
|
1015
|
-
* Use for critical issues, exceptions, and failures that need immediate attention
|
|
1016
|
-
*
|
|
1017
|
-
* @param args - Arguments to log as errors
|
|
1018
|
-
* @returns void (for compatibility with console.log)
|
|
1019
|
-
*
|
|
1020
|
-
* @example
|
|
1021
|
-
* ```typescript
|
|
1022
|
-
* logger.error('Database connection failed');
|
|
1023
|
-
* logger.error(new Error('Validation failed'));
|
|
1024
|
-
* logger.error('Critical error:', error, { context: 'user-registration' });
|
|
1025
|
-
* ```
|
|
1026
|
-
*/
|
|
1027
|
-
error(...args) {
|
|
1028
|
-
if (!this.shouldLog("error")) return;
|
|
1029
|
-
console.log(...this.compile("red", ...args));
|
|
1030
|
-
}
|
|
1031
|
-
// =============================================
|
|
1032
|
-
// Specialized Error Formatting
|
|
1033
|
-
// =============================================
|
|
1034
|
-
/**
|
|
1035
|
-
* Legacy method for A_Error logging (kept for backward compatibility)
|
|
1036
|
-
*
|
|
1037
|
-
* @deprecated Use error() method instead which handles A_Error automatically
|
|
1038
|
-
* @param error - The A_Error instance to log
|
|
1039
|
-
*/
|
|
1040
|
-
log_A_Error(error) {
|
|
1041
|
-
const time = this.getTime();
|
|
1042
|
-
const scopePadding = " ".repeat(this.scopeLength + 3);
|
|
1043
|
-
console.log(`\x1B[31m[${this.formattedScope}] |${time}| ERROR ${error.code}
|
|
1044
|
-
${scopePadding}| ${error.message}
|
|
1045
|
-
${scopePadding}| ${error.description}
|
|
1046
|
-
${scopePadding}|-------------------------------
|
|
1047
|
-
${scopePadding}| ${error.stack?.split("\n").map((line, index) => index === 0 ? line : `${scopePadding}| ${line}`).join("\n") || "No stack trace"}
|
|
1048
|
-
${scopePadding}|-------------------------------
|
|
1049
|
-
\x1B[0m` + (error.originalError ? `\x1B[31m${scopePadding}| Wrapped From ${error.originalError.message}
|
|
1050
|
-
${scopePadding}|-------------------------------
|
|
1051
|
-
${scopePadding}| ${error.originalError.stack?.split("\n").map((line, index) => index === 0 ? line : `${scopePadding}| ${line}`).join("\n") || "No stack trace"}
|
|
1052
|
-
${scopePadding}|-------------------------------
|
|
1053
|
-
\x1B[0m` : "") + (error.link ? `\x1B[31m${scopePadding}| Read in docs: ${error.link}
|
|
1054
|
-
${scopePadding}|-------------------------------
|
|
1055
|
-
\x1B[0m` : ""));
|
|
1056
|
-
}
|
|
1057
|
-
/**
|
|
1058
|
-
* Format A_Error instances for inline display within compiled messages
|
|
1059
|
-
*
|
|
1060
|
-
* Provides detailed formatting for A_Error objects including:
|
|
1061
|
-
* - Error code and message
|
|
1062
|
-
* - Description and stack trace
|
|
1063
|
-
* - Original error information (if wrapped)
|
|
1064
|
-
* - Documentation links (if available)
|
|
1065
|
-
*
|
|
1066
|
-
* @param error - The A_Error instance to format
|
|
1067
|
-
* @returns Formatted string ready for display
|
|
1068
|
-
*/
|
|
1069
|
-
compile_A_Error(error) {
|
|
1070
|
-
const scopePadding = " ".repeat(this.scopeLength + 3);
|
|
1071
|
-
return `
|
|
1072
|
-
${scopePadding}|-------------------------------
|
|
1073
|
-
${scopePadding}| Error: | ${error.code}
|
|
1074
|
-
${scopePadding}|-------------------------------
|
|
1075
|
-
${scopePadding}|${" ".repeat(10)}| ${error.message}
|
|
1076
|
-
${scopePadding}|${" ".repeat(10)}| ${error.description}
|
|
1077
|
-
${scopePadding}|-------------------------------
|
|
1078
|
-
${scopePadding}| ${error.stack?.split("\n").map((line, index) => index === 0 ? line : `${scopePadding}| ${line}`).join("\n") || "No stack trace"}
|
|
1079
|
-
${scopePadding}|-------------------------------` + (error.originalError ? `${scopePadding}| Wrapped From ${error.originalError.message}
|
|
1080
|
-
${scopePadding}|-------------------------------
|
|
1081
|
-
${scopePadding}| ${error.originalError.stack?.split("\n").map((line, index) => index === 0 ? line : `${scopePadding}| ${line}`).join("\n") || "No stack trace"}
|
|
1082
|
-
${scopePadding}|-------------------------------` : "") + (error.link ? `${scopePadding}| Read in docs: ${error.link}
|
|
1083
|
-
${scopePadding}|-------------------------------` : "");
|
|
1084
|
-
}
|
|
1085
|
-
/**
|
|
1086
|
-
* Format standard Error instances for inline display within compiled messages
|
|
1087
|
-
*
|
|
1088
|
-
* Converts standard JavaScript Error objects into a readable JSON format
|
|
1089
|
-
* with proper indentation and stack trace formatting
|
|
1090
|
-
*
|
|
1091
|
-
* @param error - The Error instance to format
|
|
1092
|
-
* @returns Formatted string ready for display
|
|
1093
|
-
*/
|
|
1094
|
-
compile_Error(error) {
|
|
1095
|
-
const scopePadding = " ".repeat(this.scopeLength + 3);
|
|
1096
|
-
return JSON.stringify({
|
|
1097
|
-
name: error.name,
|
|
1098
|
-
message: error.message,
|
|
1099
|
-
stack: error.stack?.split("\n").map((line, index) => index === 0 ? line : `${scopePadding}| ${line}`).join("\n")
|
|
1100
|
-
}, null, 2).replace(/\n/g, `
|
|
1101
|
-
${scopePadding}| `).replace(/\\n/g, "\n");
|
|
1102
|
-
}
|
|
1103
|
-
// =============================================
|
|
1104
|
-
// Utility Methods
|
|
1105
|
-
// =============================================
|
|
1106
|
-
/**
|
|
1107
|
-
* Generate timestamp string for log messages
|
|
1108
|
-
*
|
|
1109
|
-
* Format: MM:SS:mmm (minutes:seconds:milliseconds)
|
|
1110
|
-
* This provides sufficient precision for debugging while remaining readable
|
|
1111
|
-
*
|
|
1112
|
-
* @returns Formatted timestamp string
|
|
1113
|
-
*
|
|
1114
|
-
* @example
|
|
1115
|
-
* Returns: "15:42:137" for 3:42:15 PM and 137 milliseconds
|
|
1116
|
-
*/
|
|
1117
|
-
getTime() {
|
|
1118
|
-
const now = /* @__PURE__ */ new Date();
|
|
1119
|
-
const minutes = String(now.getMinutes()).padStart(A_LOGGER_TIME_FORMAT.MINUTES_PAD, "0");
|
|
1120
|
-
const seconds = String(now.getSeconds()).padStart(A_LOGGER_TIME_FORMAT.SECONDS_PAD, "0");
|
|
1121
|
-
const milliseconds = String(now.getMilliseconds()).padStart(A_LOGGER_TIME_FORMAT.MILLISECONDS_PAD, "0");
|
|
1122
|
-
return `${minutes}${A_LOGGER_TIME_FORMAT.SEPARATOR}${seconds}${A_LOGGER_TIME_FORMAT.SEPARATOR}${milliseconds}`;
|
|
1123
|
-
}
|
|
1124
|
-
};
|
|
1125
|
-
A_Logger = __decorateClass([
|
|
1126
|
-
__decorateParam(0, A_Inject(A_Scope)),
|
|
1127
|
-
__decorateParam(1, A_Inject(A_Config))
|
|
1128
|
-
], A_Logger);
|
|
1129
|
-
|
|
1130
|
-
// src/lib/A-Command/A-Command.entity.ts
|
|
1131
|
-
var _a2, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k;
|
|
1132
|
-
var A_Command = class extends A_Entity {
|
|
1133
|
-
/**
|
|
1134
|
-
*
|
|
1135
|
-
* A-Command represents an executable command with a specific code and parameters.
|
|
1136
|
-
* It can be executed within a given scope and stores execution results and errors.
|
|
1137
|
-
*
|
|
1138
|
-
*
|
|
1139
|
-
* A-Command should be context independent and execution logic should be based on attached components
|
|
1140
|
-
*
|
|
1141
|
-
* @param code
|
|
1142
|
-
* @param params
|
|
1143
|
-
*/
|
|
1144
|
-
constructor(params) {
|
|
1145
|
-
super(params);
|
|
1146
|
-
/** Map of event listeners organized by event name */
|
|
1147
|
-
this._listeners = /* @__PURE__ */ new Map();
|
|
1148
|
-
}
|
|
1149
|
-
// ====================================================================
|
|
1150
|
-
// ================== Static Command Information ======================
|
|
1151
|
-
// ====================================================================
|
|
1152
|
-
/**
|
|
1153
|
-
* Static command identifier derived from the class name
|
|
1154
|
-
* Used for command registration and serialization
|
|
1155
|
-
*/
|
|
1156
|
-
static get code() {
|
|
1157
|
-
return super.entity;
|
|
1158
|
-
}
|
|
1159
|
-
// ====================================================================
|
|
1160
|
-
// ================== Public Getter Properties =======================
|
|
1161
|
-
// ====================================================================
|
|
1162
|
-
/**
|
|
1163
|
-
* Total execution duration in milliseconds
|
|
1164
|
-
*
|
|
1165
|
-
* - If completed/failed: Returns total time from start to end
|
|
1166
|
-
* - If currently executing: Returns elapsed time since start
|
|
1167
|
-
* - If not started: Returns undefined
|
|
1168
|
-
*/
|
|
1169
|
-
get duration() {
|
|
1170
|
-
return this._endTime && this._startTime ? this._endTime.getTime() - this._startTime.getTime() : this._startTime ? (/* @__PURE__ */ new Date()).getTime() - this._startTime.getTime() : void 0;
|
|
1171
|
-
}
|
|
1172
|
-
/**
|
|
1173
|
-
* Idle time before execution started in milliseconds
|
|
1174
|
-
*
|
|
1175
|
-
* Time between command creation and execution start.
|
|
1176
|
-
* Useful for monitoring command queue performance.
|
|
1177
|
-
*/
|
|
1178
|
-
get idleTime() {
|
|
1179
|
-
return this._startTime && this._createdAt ? this._startTime.getTime() - this._createdAt.getTime() : void 0;
|
|
1180
|
-
}
|
|
1181
|
-
/**
|
|
1182
|
-
* Command execution scope for dependency injection
|
|
1183
|
-
*
|
|
1184
|
-
* Provides access to components, services, and shared resources
|
|
1185
|
-
* during command execution. Inherits from the scope where the
|
|
1186
|
-
* command was registered.
|
|
1187
|
-
*/
|
|
1188
|
-
get scope() {
|
|
1189
|
-
return this._executionScope;
|
|
1190
|
-
}
|
|
1191
|
-
/**
|
|
1192
|
-
* Unique command type identifier
|
|
1193
|
-
*
|
|
1194
|
-
* Derived from the class name and used for:
|
|
1195
|
-
* - Command registration and resolution
|
|
1196
|
-
* - Serialization and deserialization
|
|
1197
|
-
* - Logging and debugging
|
|
1198
|
-
*
|
|
1199
|
-
* @example 'create-user-command', 'process-order-command'
|
|
1200
|
-
*/
|
|
1201
|
-
get code() {
|
|
1202
|
-
return this.constructor.code;
|
|
1203
|
-
}
|
|
1204
|
-
/**
|
|
1205
|
-
* Current lifecycle status of the command
|
|
1206
|
-
*
|
|
1207
|
-
* Indicates the current phase in the command execution lifecycle.
|
|
1208
|
-
* Used to track progress and determine available operations.
|
|
1209
|
-
*/
|
|
1210
|
-
get status() {
|
|
1211
|
-
return this._status;
|
|
1212
|
-
}
|
|
1213
|
-
/**
|
|
1214
|
-
* Timestamp when the command was created
|
|
1215
|
-
*
|
|
1216
|
-
* Marks the initial instantiation time, useful for tracking
|
|
1217
|
-
* command age and queue performance metrics.
|
|
1218
|
-
*/
|
|
1219
|
-
get createdAt() {
|
|
1220
|
-
return this._createdAt;
|
|
1221
|
-
}
|
|
1222
|
-
/**
|
|
1223
|
-
* Timestamp when command execution started
|
|
1224
|
-
*
|
|
1225
|
-
* Undefined until execution begins. Used for calculating
|
|
1226
|
-
* execution duration and idle time.
|
|
1227
|
-
*/
|
|
1228
|
-
get startedAt() {
|
|
1229
|
-
return this._startTime;
|
|
1230
|
-
}
|
|
1231
|
-
/**
|
|
1232
|
-
* Timestamp when command execution ended
|
|
1233
|
-
*
|
|
1234
|
-
* Set when command reaches COMPLETED or FAILED status.
|
|
1235
|
-
* Used for calculating total execution duration.
|
|
1236
|
-
*/
|
|
1237
|
-
get endedAt() {
|
|
1238
|
-
return this._endTime;
|
|
1239
|
-
}
|
|
1240
|
-
/**
|
|
1241
|
-
* Result data produced by command execution
|
|
1242
|
-
*
|
|
1243
|
-
* Contains the output data from successful command execution.
|
|
1244
|
-
* Undefined until command completes successfully.
|
|
1245
|
-
*/
|
|
1246
|
-
get result() {
|
|
1247
|
-
return this._result;
|
|
1248
|
-
}
|
|
1249
|
-
/**
|
|
1250
|
-
* Array of errors that occurred during execution
|
|
1251
|
-
*
|
|
1252
|
-
* Automatically wraps native errors in A_Error instances
|
|
1253
|
-
* for consistent error handling. Empty array if no errors occurred.
|
|
1254
|
-
*/
|
|
1255
|
-
get error() {
|
|
1256
|
-
return this._error;
|
|
1257
|
-
}
|
|
1258
|
-
/**
|
|
1259
|
-
* Command initialization parameters
|
|
1260
|
-
*
|
|
1261
|
-
* Contains the input data used to create and configure the command.
|
|
1262
|
-
* These parameters are immutable during command execution.
|
|
1263
|
-
return new A_Error(err);
|
|
1264
|
-
}
|
|
1265
|
-
});
|
|
1266
|
-
}
|
|
1267
|
-
|
|
1268
|
-
/**
|
|
1269
|
-
* Command initialization parameters
|
|
1270
|
-
*
|
|
1271
|
-
* Contains the input data used to create and configure the command.
|
|
1272
|
-
* These parameters are immutable during command execution.
|
|
1273
|
-
*/
|
|
1274
|
-
get params() {
|
|
1275
|
-
return this._params;
|
|
1276
|
-
}
|
|
1277
|
-
/**
|
|
1278
|
-
* Indicates if the command has been processed (completed or failed)
|
|
1279
|
-
*
|
|
1280
|
-
* Returns true if the command has completed or failed, false otherwise.
|
|
1281
|
-
*/
|
|
1282
|
-
get isProcessed() {
|
|
1283
|
-
return this._status === "COMPLETED" /* COMPLETED */ || this._status === "FAILED" /* FAILED */;
|
|
1284
|
-
}
|
|
1285
|
-
async [_k = "onBeforeTransition" /* onBeforeTransition */](transition, logger, ...args) {
|
|
1286
|
-
this.checkScopeInheritance();
|
|
1287
|
-
logger?.debug("yellow", `Command ${this.aseid.toString()} transitioning from ${transition.from} to ${transition.to}`);
|
|
1288
|
-
}
|
|
1289
|
-
async [_j = "created_initialized" /* CREATED_TO_INITIALIZED */](transition, ...args) {
|
|
1290
|
-
if (this._status !== "CREATED" /* CREATED */) {
|
|
1291
|
-
return;
|
|
1292
|
-
}
|
|
1293
|
-
this._createdAt = /* @__PURE__ */ new Date();
|
|
1294
|
-
this._status = "INITIALIZED" /* INITIALIZED */;
|
|
1295
|
-
this.emit("onInit" /* onInit */);
|
|
1296
|
-
}
|
|
1297
|
-
async [_i = "initialized_executing" /* INITIALIZED_TO_EXECUTING */](transition, ...args) {
|
|
1298
|
-
if (this._status !== "INITIALIZED" /* INITIALIZED */ && this._status !== "CREATED" /* CREATED */) {
|
|
1299
|
-
return;
|
|
1300
|
-
}
|
|
1301
|
-
this._startTime = /* @__PURE__ */ new Date();
|
|
1302
|
-
this._status = "EXECUTING" /* EXECUTING */;
|
|
1303
|
-
this.emit("onExecute" /* onExecute */);
|
|
1304
|
-
}
|
|
1305
|
-
/**
|
|
1306
|
-
* Handles command completion after successful execution
|
|
1307
|
-
*
|
|
1308
|
-
* EXECUTION -> COMPLETED transition
|
|
1309
|
-
*/
|
|
1310
|
-
async [_h = "executing_completed" /* EXECUTING_TO_COMPLETED */](transition, ...args) {
|
|
1311
|
-
this._endTime = /* @__PURE__ */ new Date();
|
|
1312
|
-
this._status = "COMPLETED" /* COMPLETED */;
|
|
1313
|
-
this.emit("onComplete" /* onComplete */);
|
|
1314
|
-
}
|
|
1315
|
-
/**
|
|
1316
|
-
* Handles command failure during execution
|
|
1317
|
-
*
|
|
1318
|
-
* EXECUTION -> FAILED transition
|
|
1319
|
-
*/
|
|
1320
|
-
async [_g = "executing_failed" /* EXECUTING_TO_FAILED */](transition, error, ...args) {
|
|
1321
|
-
this._endTime = /* @__PURE__ */ new Date();
|
|
1322
|
-
this._status = "FAILED" /* FAILED */;
|
|
1323
|
-
this.emit("onFail" /* onFail */);
|
|
1324
|
-
}
|
|
1325
|
-
/**
|
|
1326
|
-
* Default behavior for Command Initialization uses StateMachine to transition states
|
|
1327
|
-
*/
|
|
1328
|
-
async [_f = "onInit" /* onInit */](stateMachine, ...args) {
|
|
1329
|
-
await stateMachine.transition("CREATED" /* CREATED */, "INITIALIZED" /* INITIALIZED */);
|
|
1330
|
-
}
|
|
1331
|
-
async [_e = "onBeforeExecute" /* onBeforeExecute */](stateMachine, ...args) {
|
|
1332
|
-
await stateMachine.transition("INITIALIZED" /* INITIALIZED */, "EXECUTING" /* EXECUTING */);
|
|
1333
|
-
}
|
|
1334
|
-
async [_d2 = "onExecute" /* onExecute */](...args) {
|
|
1335
|
-
}
|
|
1336
|
-
/**
|
|
1337
|
-
* By Default on AfterExecute calls the Completion method to mark the command as completed
|
|
1338
|
-
*
|
|
1339
|
-
* [!] This can be overridden to implement custom behavior using A_Feature overrides
|
|
1340
|
-
*/
|
|
1341
|
-
async [_c2 = "onAfterExecute" /* onAfterExecute */](...args) {
|
|
1342
|
-
}
|
|
1343
|
-
async [_b2 = "onComplete" /* onComplete */](stateMachine, ...args) {
|
|
1344
|
-
await stateMachine.transition("EXECUTING" /* EXECUTING */, "COMPLETED" /* COMPLETED */);
|
|
1345
|
-
}
|
|
1346
|
-
async [_a2 = "onFail" /* onFail */](stateMachine, operation, ...args) {
|
|
1347
|
-
await stateMachine.transition("EXECUTING" /* EXECUTING */, "FAILED" /* FAILED */);
|
|
1348
|
-
}
|
|
1349
|
-
// --------------------------------------------------------------------------
|
|
1350
|
-
// A-Command Lifecycle Methods
|
|
1351
|
-
// --------------------------------------------------------------------------
|
|
1352
|
-
/**
|
|
1353
|
-
* Initializes the command before execution.
|
|
1354
|
-
*/
|
|
1355
|
-
async init() {
|
|
1356
|
-
await this.call("onInit" /* onInit */, this.scope);
|
|
1357
|
-
}
|
|
1358
|
-
/**
|
|
1359
|
-
* Executes the command logic.
|
|
1360
|
-
*/
|
|
1361
|
-
async execute() {
|
|
1362
|
-
if (this.isProcessed) return;
|
|
1363
|
-
try {
|
|
1364
|
-
this.checkScopeInheritance();
|
|
1365
|
-
const context = new A_OperationContext("execute-command");
|
|
1366
|
-
this.scope.register(context);
|
|
1367
|
-
await new Promise(async (resolve, reject) => {
|
|
1368
|
-
try {
|
|
1369
|
-
const onBeforeExecuteFeature = new A_Feature({
|
|
1370
|
-
name: "onBeforeExecute" /* onBeforeExecute */,
|
|
1371
|
-
component: this,
|
|
1372
|
-
scope: this.scope
|
|
1373
|
-
});
|
|
1374
|
-
const onExecuteFeature = new A_Feature({
|
|
1375
|
-
name: "onExecute" /* onExecute */,
|
|
1376
|
-
component: this,
|
|
1377
|
-
scope: this.scope
|
|
1378
|
-
});
|
|
1379
|
-
const onAfterExecuteFeature = new A_Feature({
|
|
1380
|
-
name: "onAfterExecute" /* onAfterExecute */,
|
|
1381
|
-
component: this,
|
|
1382
|
-
scope: this.scope
|
|
1383
|
-
});
|
|
1384
|
-
this.on("onComplete" /* onComplete */, () => {
|
|
1385
|
-
onBeforeExecuteFeature.interrupt();
|
|
1386
|
-
onExecuteFeature.interrupt();
|
|
1387
|
-
onAfterExecuteFeature.interrupt();
|
|
1388
|
-
resolve();
|
|
1389
|
-
});
|
|
1390
|
-
await onBeforeExecuteFeature.process(this.scope);
|
|
1391
|
-
await onExecuteFeature.process(this.scope);
|
|
1392
|
-
await onAfterExecuteFeature.process(this.scope);
|
|
1393
|
-
if (this._origin === "invoked") {
|
|
1394
|
-
await this.complete();
|
|
1395
|
-
}
|
|
1396
|
-
resolve();
|
|
1397
|
-
} catch (error) {
|
|
1398
|
-
reject(error);
|
|
1399
|
-
}
|
|
1400
|
-
});
|
|
1401
|
-
} catch (error) {
|
|
1402
|
-
let targetError = error instanceof A_Error ? error : new A_CommandError({
|
|
1403
|
-
title: A_CommandError.ExecutionError,
|
|
1404
|
-
description: `An error occurred while executing command "${this.aseid.toString()}".`,
|
|
1405
|
-
originalError: error
|
|
1406
|
-
});
|
|
1407
|
-
await this.fail(targetError);
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
/**
|
|
1411
|
-
* Marks the command as completed
|
|
1412
|
-
*/
|
|
1413
|
-
async complete(result) {
|
|
1414
|
-
if (this.isProcessed) return;
|
|
1415
|
-
this._status = "COMPLETED" /* COMPLETED */;
|
|
1416
|
-
this._result = result;
|
|
1417
|
-
await this.call("onComplete" /* onComplete */, this.scope);
|
|
1418
|
-
this.scope.destroy();
|
|
1419
|
-
}
|
|
1420
|
-
/**
|
|
1421
|
-
* Marks the command as failed
|
|
1422
|
-
*/
|
|
1423
|
-
async fail(error) {
|
|
1424
|
-
if (this.isProcessed) return;
|
|
1425
|
-
this._status = "FAILED" /* FAILED */;
|
|
1426
|
-
if (error) {
|
|
1427
|
-
this._error = error;
|
|
1428
|
-
this.scope.register(error);
|
|
1429
|
-
}
|
|
1430
|
-
await this.call("onFail" /* onFail */, this.scope);
|
|
1431
|
-
this.scope.destroy();
|
|
1432
|
-
}
|
|
1433
|
-
// --------------------------------------------------------------------------
|
|
1434
|
-
// A-Command Event-Emitter methods
|
|
1435
|
-
// --------------------------------------------------------------------------
|
|
1436
|
-
/**
|
|
1437
|
-
* Registers an event listener for a specific event
|
|
1438
|
-
*
|
|
1439
|
-
* @param event
|
|
1440
|
-
* @param listener
|
|
1441
|
-
*/
|
|
1442
|
-
on(event, listener) {
|
|
1443
|
-
if (!this._listeners.has(event)) {
|
|
1444
|
-
this._listeners.set(event, /* @__PURE__ */ new Set());
|
|
1445
|
-
}
|
|
1446
|
-
this._listeners.get(event).add(listener);
|
|
1447
|
-
}
|
|
1448
|
-
/**
|
|
1449
|
-
* Removes an event listener for a specific event
|
|
1450
|
-
*
|
|
1451
|
-
* @param event
|
|
1452
|
-
* @param listener
|
|
1453
|
-
*/
|
|
1454
|
-
off(event, listener) {
|
|
1455
|
-
this._listeners.get(event)?.delete(listener);
|
|
1456
|
-
}
|
|
1457
|
-
/**
|
|
1458
|
-
* Emits an event to all registered listeners
|
|
1459
|
-
*
|
|
1460
|
-
* @param event
|
|
1461
|
-
*/
|
|
1462
|
-
emit(event) {
|
|
1463
|
-
this._listeners.get(event)?.forEach(async (listener) => {
|
|
1464
|
-
listener(this);
|
|
1465
|
-
});
|
|
1466
|
-
}
|
|
1467
|
-
// --------------------------------------------------------------------------
|
|
1468
|
-
// A-Entity Base Class Overrides
|
|
1469
|
-
// --------------------------------------------------------------------------
|
|
1470
|
-
// Serialization / Deserialization
|
|
1471
|
-
// -------------------------------------------------------------------------
|
|
1472
|
-
/**
|
|
1473
|
-
* Allows to create a Command instance from new data
|
|
1474
|
-
*
|
|
1475
|
-
* @param newEntity
|
|
1476
|
-
*/
|
|
1477
|
-
fromNew(newEntity) {
|
|
1478
|
-
super.fromNew(newEntity);
|
|
1479
|
-
this._origin = "invoked";
|
|
1480
|
-
this._executionScope = new A_Scope({
|
|
1481
|
-
name: `A-Command-Execution-Scope-${this.aseid.toString()}`,
|
|
1482
|
-
components: [A_StateMachine]
|
|
1483
|
-
});
|
|
1484
|
-
this._createdAt = /* @__PURE__ */ new Date();
|
|
1485
|
-
this._params = newEntity;
|
|
1486
|
-
this._status = "CREATED" /* CREATED */;
|
|
1487
|
-
}
|
|
1488
|
-
/**
|
|
1489
|
-
* Allows to convert serialized data to Command instance
|
|
1490
|
-
*
|
|
1491
|
-
* [!] By default it omits params as they are not stored in the serialized data
|
|
1492
|
-
*
|
|
1493
|
-
* @param serialized
|
|
1494
|
-
*/
|
|
1495
|
-
fromJSON(serialized) {
|
|
1496
|
-
super.fromJSON(serialized);
|
|
1497
|
-
this._origin = "serialized";
|
|
1498
|
-
this._executionScope = new A_Scope({
|
|
1499
|
-
name: `A-Command-Execution-Scope-${this.aseid.toString()}`,
|
|
1500
|
-
components: [A_StateMachine]
|
|
1501
|
-
});
|
|
1502
|
-
if (serialized.createdAt) this._createdAt = new Date(serialized.createdAt);
|
|
1503
|
-
if (serialized.startedAt) this._startTime = new Date(serialized.startedAt);
|
|
1504
|
-
if (serialized.endedAt) this._endTime = new Date(serialized.endedAt);
|
|
1505
|
-
this._params = serialized.params;
|
|
1506
|
-
this._status = serialized.status;
|
|
1507
|
-
if (serialized.error)
|
|
1508
|
-
this._error = new A_CommandError(serialized.error);
|
|
1509
|
-
if (serialized.result)
|
|
1510
|
-
this._result = serialized.result;
|
|
1511
|
-
}
|
|
1512
|
-
/**
|
|
1513
|
-
* Converts the Command instance to a plain object
|
|
1514
|
-
*
|
|
1515
|
-
* @returns
|
|
1516
|
-
*/
|
|
1517
|
-
toJSON() {
|
|
1518
|
-
return {
|
|
1519
|
-
...super.toJSON(),
|
|
1520
|
-
code: this.code,
|
|
1521
|
-
status: this._status,
|
|
1522
|
-
params: this._params,
|
|
1523
|
-
createdAt: this._createdAt.toISOString(),
|
|
1524
|
-
startedAt: this._startTime ? this._startTime.toISOString() : void 0,
|
|
1525
|
-
endedAt: this._endTime ? this._endTime.toISOString() : void 0,
|
|
1526
|
-
duration: this.duration,
|
|
1527
|
-
idleTime: this.idleTime,
|
|
1528
|
-
result: this.result,
|
|
1529
|
-
error: this.error ? this.error.toJSON() : void 0
|
|
1530
|
-
};
|
|
1531
|
-
}
|
|
1532
|
-
//============================================================================================
|
|
1533
|
-
// Helpers Methods
|
|
1534
|
-
//============================================================================================
|
|
1535
|
-
/**
|
|
1536
|
-
* Ensures that the command's execution scope inherits from the context scope
|
|
1537
|
-
*
|
|
1538
|
-
* Throws an error if the command is not bound to any context scope
|
|
1539
|
-
*/
|
|
1540
|
-
checkScopeInheritance() {
|
|
1541
|
-
let attachedScope;
|
|
1542
|
-
try {
|
|
1543
|
-
attachedScope = A_Context.scope(this);
|
|
1544
|
-
} catch (error) {
|
|
1545
|
-
throw new A_CommandError({
|
|
1546
|
-
title: A_CommandError.CommandScopeBindingError,
|
|
1547
|
-
description: `Command ${this.aseid.toString()} is not bound to any context scope. Ensure the command is properly registered within a context before execution.`,
|
|
1548
|
-
originalError: error
|
|
1549
|
-
});
|
|
1550
|
-
}
|
|
1551
|
-
if (!this.scope.isInheritedFrom(A_Context.scope(this))) {
|
|
1552
|
-
this.scope.inherit(A_Context.scope(this));
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
};
|
|
1556
|
-
__decorateClass([
|
|
1557
|
-
A_Feature.Extend(),
|
|
1558
|
-
__decorateParam(0, A_Inject(A_StateMachineTransition)),
|
|
1559
|
-
__decorateParam(1, A_Inject(A_Logger))
|
|
1560
|
-
], A_Command.prototype, _k, 1);
|
|
1561
|
-
__decorateClass([
|
|
1562
|
-
A_Feature.Extend(),
|
|
1563
|
-
__decorateParam(0, A_Inject(A_StateMachineTransition))
|
|
1564
|
-
], A_Command.prototype, _j, 1);
|
|
1565
|
-
__decorateClass([
|
|
1566
|
-
A_Feature.Extend(),
|
|
1567
|
-
__decorateParam(0, A_Inject(A_StateMachineTransition))
|
|
1568
|
-
], A_Command.prototype, _i, 1);
|
|
1569
|
-
__decorateClass([
|
|
1570
|
-
A_Feature.Extend(),
|
|
1571
|
-
__decorateParam(0, A_Inject(A_StateMachineTransition))
|
|
1572
|
-
], A_Command.prototype, _h, 1);
|
|
1573
|
-
__decorateClass([
|
|
1574
|
-
A_Feature.Extend(),
|
|
1575
|
-
__decorateParam(0, A_Inject(A_StateMachineTransition)),
|
|
1576
|
-
__decorateParam(1, A_Inject(A_Error))
|
|
1577
|
-
], A_Command.prototype, _g, 1);
|
|
1578
|
-
__decorateClass([
|
|
1579
|
-
A_Feature.Extend(),
|
|
1580
|
-
__decorateParam(0, A_Inject(A_StateMachine))
|
|
1581
|
-
], A_Command.prototype, _f, 1);
|
|
1582
|
-
__decorateClass([
|
|
1583
|
-
A_Feature.Extend({
|
|
1584
|
-
after: /.*/
|
|
1585
|
-
}),
|
|
1586
|
-
__decorateParam(0, A_Dependency.Required()),
|
|
1587
|
-
__decorateParam(0, A_Inject(A_StateMachine))
|
|
1588
|
-
], A_Command.prototype, _e, 1);
|
|
1589
|
-
__decorateClass([
|
|
1590
|
-
A_Feature.Extend()
|
|
1591
|
-
], A_Command.prototype, _d2, 1);
|
|
1592
|
-
__decorateClass([
|
|
1593
|
-
A_Feature.Extend()
|
|
1594
|
-
], A_Command.prototype, _c2, 1);
|
|
1595
|
-
__decorateClass([
|
|
1596
|
-
A_Feature.Extend({
|
|
1597
|
-
after: /.*/
|
|
1598
|
-
}),
|
|
1599
|
-
__decorateParam(0, A_Inject(A_StateMachine))
|
|
1600
|
-
], A_Command.prototype, _b2, 1);
|
|
1601
|
-
__decorateClass([
|
|
1602
|
-
A_Feature.Extend({
|
|
1603
|
-
after: /.*/
|
|
1604
|
-
}),
|
|
1605
|
-
__decorateParam(0, A_Dependency.Required()),
|
|
1606
|
-
__decorateParam(0, A_Inject(A_StateMachine)),
|
|
1607
|
-
__decorateParam(1, A_Inject(A_OperationContext))
|
|
1608
|
-
], A_Command.prototype, _a2, 1);
|
|
1609
|
-
var A_FSPolyfillClass = class {
|
|
1610
|
-
constructor(logger) {
|
|
1611
|
-
this.logger = logger;
|
|
1612
|
-
this._initialized = false;
|
|
1613
|
-
}
|
|
1614
|
-
get isInitialized() {
|
|
1615
|
-
return this._initialized;
|
|
1616
|
-
}
|
|
1617
|
-
async get() {
|
|
1618
|
-
if (!this._initialized) {
|
|
1619
|
-
await this.init();
|
|
1620
|
-
}
|
|
1621
|
-
return this._fs;
|
|
1622
|
-
}
|
|
1623
|
-
async init() {
|
|
1624
|
-
try {
|
|
1625
|
-
if (A_Context.environment === "server") {
|
|
1626
|
-
await this.initServer();
|
|
1627
|
-
} else {
|
|
1628
|
-
this.initBrowser();
|
|
1629
|
-
}
|
|
1630
|
-
this._initialized = true;
|
|
1631
|
-
} catch (error) {
|
|
1632
|
-
this.initBrowser();
|
|
1633
|
-
this._initialized = true;
|
|
1634
|
-
}
|
|
1635
|
-
}
|
|
1636
|
-
async initServer() {
|
|
1637
|
-
this._fs = await import('fs');
|
|
1638
|
-
}
|
|
1639
|
-
initBrowser() {
|
|
1640
|
-
this._fs = {
|
|
1641
|
-
readFileSync: (path, encoding) => {
|
|
1642
|
-
this.logger.warning("fs.readFileSync not available in browser environment");
|
|
1643
|
-
return "";
|
|
1644
|
-
},
|
|
1645
|
-
existsSync: (path) => {
|
|
1646
|
-
this.logger.warning("fs.existsSync not available in browser environment");
|
|
1647
|
-
return false;
|
|
1648
|
-
},
|
|
1649
|
-
createReadStream: (path) => {
|
|
1650
|
-
this.logger.warning("fs.createReadStream not available in browser environment");
|
|
1651
|
-
return null;
|
|
1652
|
-
}
|
|
1653
|
-
};
|
|
1654
|
-
}
|
|
1655
|
-
};
|
|
1656
|
-
var A_CryptoPolyfillClass = class {
|
|
1657
|
-
constructor(logger) {
|
|
1658
|
-
this.logger = logger;
|
|
1659
|
-
this._initialized = false;
|
|
1660
|
-
}
|
|
1661
|
-
get isInitialized() {
|
|
1662
|
-
return this._initialized;
|
|
1663
|
-
}
|
|
1664
|
-
async get(fsPolyfill) {
|
|
1665
|
-
if (!this._initialized) {
|
|
1666
|
-
this._fsPolyfill = fsPolyfill;
|
|
1667
|
-
await this.init();
|
|
1668
|
-
}
|
|
1669
|
-
return this._crypto;
|
|
1670
|
-
}
|
|
1671
|
-
async init() {
|
|
1672
|
-
try {
|
|
1673
|
-
if (A_Context.environment === "server") {
|
|
1674
|
-
await this.initServer();
|
|
1675
|
-
} else {
|
|
1676
|
-
this.initBrowser();
|
|
1677
|
-
}
|
|
1678
|
-
this._initialized = true;
|
|
1679
|
-
} catch (error) {
|
|
1680
|
-
this.initBrowser();
|
|
1681
|
-
this._initialized = true;
|
|
1682
|
-
}
|
|
1683
|
-
}
|
|
1684
|
-
async initServer() {
|
|
1685
|
-
const crypto2 = await import('crypto');
|
|
1686
|
-
this._crypto = {
|
|
1687
|
-
createTextHash: (text, algorithm = "sha384") => Promise.resolve(
|
|
1688
|
-
`${algorithm}-${crypto2.createHash(algorithm).update(text).digest("base64")}`
|
|
1689
|
-
),
|
|
1690
|
-
createFileHash: (filePath, algorithm = "sha384") => new Promise(async (resolve, reject) => {
|
|
1691
|
-
try {
|
|
1692
|
-
if (!this._fsPolyfill) {
|
|
1693
|
-
throw new Error("FS polyfill is required for file hashing");
|
|
1694
|
-
}
|
|
1695
|
-
const hash = crypto2.createHash(algorithm);
|
|
1696
|
-
const fileStream = this._fsPolyfill.createReadStream(filePath);
|
|
1697
|
-
fileStream.on("data", (data) => hash.update(data));
|
|
1698
|
-
fileStream.on("end", () => resolve(`${algorithm}-${hash.digest("base64")}`));
|
|
1699
|
-
fileStream.on("error", (err) => reject(err));
|
|
1700
|
-
} catch (error) {
|
|
1701
|
-
reject(error);
|
|
1702
|
-
}
|
|
1703
|
-
})
|
|
1704
|
-
};
|
|
1705
|
-
}
|
|
1706
|
-
initBrowser() {
|
|
1707
|
-
this._crypto = {
|
|
1708
|
-
createFileHash: () => {
|
|
1709
|
-
this.logger.warning("File hash not available in browser environment");
|
|
1710
|
-
return Promise.resolve("");
|
|
1711
|
-
},
|
|
1712
|
-
createTextHash: (text, algorithm = "SHA-384") => new Promise(async (resolve, reject) => {
|
|
1713
|
-
try {
|
|
1714
|
-
if (!crypto.subtle) {
|
|
1715
|
-
throw new Error("SubtleCrypto not available");
|
|
1716
|
-
}
|
|
1717
|
-
const encoder = new TextEncoder();
|
|
1718
|
-
const data = encoder.encode(text);
|
|
1719
|
-
const hashBuffer = await crypto.subtle.digest(algorithm, data);
|
|
1720
|
-
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
1721
|
-
const hashBase64 = btoa(String.fromCharCode(...hashArray));
|
|
1722
|
-
resolve(`${algorithm}-${hashBase64}`);
|
|
1723
|
-
} catch (error) {
|
|
1724
|
-
reject(error);
|
|
1725
|
-
}
|
|
1726
|
-
})
|
|
1727
|
-
};
|
|
1728
|
-
}
|
|
1729
|
-
};
|
|
1730
|
-
var A_HttpPolyfillClass = class {
|
|
1731
|
-
constructor(logger) {
|
|
1732
|
-
this.logger = logger;
|
|
1733
|
-
this._initialized = false;
|
|
1734
|
-
}
|
|
1735
|
-
get isInitialized() {
|
|
1736
|
-
return this._initialized;
|
|
1737
|
-
}
|
|
1738
|
-
async get() {
|
|
1739
|
-
if (!this._initialized) {
|
|
1740
|
-
await this.init();
|
|
1741
|
-
}
|
|
1742
|
-
return this._http;
|
|
1743
|
-
}
|
|
1744
|
-
async init() {
|
|
1745
|
-
try {
|
|
1746
|
-
if (A_Context.environment === "server") {
|
|
1747
|
-
await this.initServer();
|
|
1748
|
-
} else {
|
|
1749
|
-
this.initBrowser();
|
|
1750
|
-
}
|
|
1751
|
-
this._initialized = true;
|
|
1752
|
-
} catch (error) {
|
|
1753
|
-
this.initBrowser();
|
|
1754
|
-
this._initialized = true;
|
|
1755
|
-
}
|
|
1756
|
-
}
|
|
1757
|
-
async initServer() {
|
|
1758
|
-
const httpModule = await import('http');
|
|
1759
|
-
this._http = {
|
|
1760
|
-
request: httpModule.request,
|
|
1761
|
-
get: httpModule.get,
|
|
1762
|
-
createServer: httpModule.createServer
|
|
1763
|
-
};
|
|
1764
|
-
}
|
|
1765
|
-
initBrowser() {
|
|
1766
|
-
this._http = {
|
|
1767
|
-
request: (options, callback) => {
|
|
1768
|
-
this.logger.warning("http.request not available in browser/test environment, use fetch instead");
|
|
1769
|
-
return this.createMockRequest(options, callback, false);
|
|
1770
|
-
},
|
|
1771
|
-
get: (url, callback) => {
|
|
1772
|
-
this.logger.warning("http.get not available in browser/test environment, use fetch instead");
|
|
1773
|
-
return this.createMockRequest(typeof url === "string" ? { hostname: url } : url, callback, false);
|
|
1774
|
-
},
|
|
1775
|
-
createServer: () => {
|
|
1776
|
-
this.logger.error("http.createServer not available in browser/test environment");
|
|
1777
|
-
return null;
|
|
1778
|
-
}
|
|
1779
|
-
};
|
|
1780
|
-
}
|
|
1781
|
-
createMockRequest(options, callback, isHttps = false) {
|
|
1782
|
-
const request = {
|
|
1783
|
-
end: () => {
|
|
1784
|
-
if (callback) {
|
|
1785
|
-
const mockResponse = {
|
|
1786
|
-
statusCode: 200,
|
|
1787
|
-
headers: {},
|
|
1788
|
-
on: (event, handler) => {
|
|
1789
|
-
if (event === "data") {
|
|
1790
|
-
setTimeout(() => handler("mock data"), 0);
|
|
1791
|
-
} else if (event === "end") {
|
|
1792
|
-
setTimeout(() => handler(), 0);
|
|
1793
|
-
}
|
|
1794
|
-
},
|
|
1795
|
-
pipe: (dest) => {
|
|
1796
|
-
if (dest.write) dest.write("mock data");
|
|
1797
|
-
if (dest.end) dest.end();
|
|
1798
|
-
}
|
|
1799
|
-
};
|
|
1800
|
-
setTimeout(() => callback(mockResponse), 0);
|
|
1801
|
-
}
|
|
1802
|
-
},
|
|
1803
|
-
write: (data) => {
|
|
1804
|
-
},
|
|
1805
|
-
on: (event, handler) => {
|
|
1806
|
-
}
|
|
1807
|
-
};
|
|
1808
|
-
return request;
|
|
1809
|
-
}
|
|
1810
|
-
};
|
|
1811
|
-
var A_HttpsPolyfillClass = class {
|
|
1812
|
-
constructor(logger) {
|
|
1813
|
-
this.logger = logger;
|
|
1814
|
-
this._initialized = false;
|
|
1815
|
-
}
|
|
1816
|
-
get isInitialized() {
|
|
1817
|
-
return this._initialized;
|
|
1818
|
-
}
|
|
1819
|
-
async get() {
|
|
1820
|
-
if (!this._initialized) {
|
|
1821
|
-
await this.init();
|
|
1822
|
-
}
|
|
1823
|
-
return this._https;
|
|
1824
|
-
}
|
|
1825
|
-
async init() {
|
|
1826
|
-
try {
|
|
1827
|
-
if (A_Context.environment === "server") {
|
|
1828
|
-
await this.initServer();
|
|
1829
|
-
} else {
|
|
1830
|
-
this.initBrowser();
|
|
1831
|
-
}
|
|
1832
|
-
this._initialized = true;
|
|
1833
|
-
} catch (error) {
|
|
1834
|
-
this.initBrowser();
|
|
1835
|
-
this._initialized = true;
|
|
1836
|
-
}
|
|
1837
|
-
}
|
|
1838
|
-
async initServer() {
|
|
1839
|
-
const httpsModule = await import('https');
|
|
1840
|
-
this._https = {
|
|
1841
|
-
request: httpsModule.request,
|
|
1842
|
-
get: httpsModule.get,
|
|
1843
|
-
createServer: httpsModule.createServer
|
|
1844
|
-
};
|
|
1845
|
-
}
|
|
1846
|
-
initBrowser() {
|
|
1847
|
-
this._https = {
|
|
1848
|
-
request: (options, callback) => {
|
|
1849
|
-
this.logger.warning("https.request not available in browser/test environment, use fetch instead");
|
|
1850
|
-
return this.createMockRequest(options, callback, true);
|
|
1851
|
-
},
|
|
1852
|
-
get: (url, callback) => {
|
|
1853
|
-
this.logger.warning("https.get not available in browser/test environment, use fetch instead");
|
|
1854
|
-
return this.createMockRequest(typeof url === "string" ? { hostname: url } : url, callback, true);
|
|
1855
|
-
},
|
|
1856
|
-
createServer: () => {
|
|
1857
|
-
this.logger.error("https.createServer not available in browser/test environment");
|
|
1858
|
-
return null;
|
|
1859
|
-
}
|
|
1860
|
-
};
|
|
1861
|
-
}
|
|
1862
|
-
createMockRequest(options, callback, isHttps = true) {
|
|
1863
|
-
const request = {
|
|
1864
|
-
end: () => {
|
|
1865
|
-
if (callback) {
|
|
1866
|
-
const mockResponse = {
|
|
1867
|
-
statusCode: 200,
|
|
1868
|
-
headers: {},
|
|
1869
|
-
on: (event, handler) => {
|
|
1870
|
-
if (event === "data") {
|
|
1871
|
-
setTimeout(() => handler("mock data"), 0);
|
|
1872
|
-
} else if (event === "end") {
|
|
1873
|
-
setTimeout(() => handler(), 0);
|
|
1874
|
-
}
|
|
1875
|
-
},
|
|
1876
|
-
pipe: (dest) => {
|
|
1877
|
-
if (dest.write) dest.write("mock data");
|
|
1878
|
-
if (dest.end) dest.end();
|
|
1879
|
-
}
|
|
1880
|
-
};
|
|
1881
|
-
setTimeout(() => callback(mockResponse), 0);
|
|
1882
|
-
}
|
|
1883
|
-
},
|
|
1884
|
-
write: (data) => {
|
|
1885
|
-
},
|
|
1886
|
-
on: (event, handler) => {
|
|
1887
|
-
}
|
|
1888
|
-
};
|
|
1889
|
-
return request;
|
|
1890
|
-
}
|
|
1891
|
-
};
|
|
1892
|
-
var A_PathPolyfillClass = class {
|
|
1893
|
-
constructor(logger) {
|
|
1894
|
-
this.logger = logger;
|
|
1895
|
-
this._initialized = false;
|
|
1896
|
-
}
|
|
1897
|
-
get isInitialized() {
|
|
1898
|
-
return this._initialized;
|
|
1899
|
-
}
|
|
1900
|
-
async get() {
|
|
1901
|
-
if (!this._initialized) {
|
|
1902
|
-
await this.init();
|
|
1903
|
-
}
|
|
1904
|
-
return this._path;
|
|
1905
|
-
}
|
|
1906
|
-
async init() {
|
|
1907
|
-
try {
|
|
1908
|
-
if (A_Context.environment === "server") {
|
|
1909
|
-
await this.initServer();
|
|
1910
|
-
} else {
|
|
1911
|
-
this.initBrowser();
|
|
1912
|
-
}
|
|
1913
|
-
this._initialized = true;
|
|
1914
|
-
} catch (error) {
|
|
1915
|
-
this.initBrowser();
|
|
1916
|
-
this._initialized = true;
|
|
1917
|
-
}
|
|
1918
|
-
}
|
|
1919
|
-
async initServer() {
|
|
1920
|
-
this._path = await import('path');
|
|
1921
|
-
}
|
|
1922
|
-
initBrowser() {
|
|
1923
|
-
this._path = {
|
|
1924
|
-
join: (...paths) => {
|
|
1925
|
-
return paths.join("/").replace(/\/+/g, "/");
|
|
1926
|
-
},
|
|
1927
|
-
resolve: (...paths) => {
|
|
1928
|
-
let resolvedPath = "";
|
|
1929
|
-
for (const path of paths) {
|
|
1930
|
-
if (path.startsWith("/")) {
|
|
1931
|
-
resolvedPath = path;
|
|
1932
|
-
} else {
|
|
1933
|
-
resolvedPath = this._path.join(resolvedPath, path);
|
|
1934
|
-
}
|
|
1935
|
-
}
|
|
1936
|
-
return resolvedPath || "/";
|
|
1937
|
-
},
|
|
1938
|
-
dirname: (path) => {
|
|
1939
|
-
const parts = path.split("/");
|
|
1940
|
-
return parts.slice(0, -1).join("/") || "/";
|
|
1941
|
-
},
|
|
1942
|
-
basename: (path, ext) => {
|
|
1943
|
-
const base = path.split("/").pop() || "";
|
|
1944
|
-
return ext && base.endsWith(ext) ? base.slice(0, -ext.length) : base;
|
|
1945
|
-
},
|
|
1946
|
-
extname: (path) => {
|
|
1947
|
-
const parts = path.split(".");
|
|
1948
|
-
return parts.length > 1 ? "." + parts.pop() : "";
|
|
1949
|
-
},
|
|
1950
|
-
relative: (from, to) => {
|
|
1951
|
-
return to.replace(from, "").replace(/^\//, "");
|
|
1952
|
-
},
|
|
1953
|
-
normalize: (path) => {
|
|
1954
|
-
return path.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
|
|
1955
|
-
},
|
|
1956
|
-
isAbsolute: (path) => {
|
|
1957
|
-
return path.startsWith("/") || /^[a-zA-Z]:/.test(path);
|
|
1958
|
-
},
|
|
1959
|
-
parse: (path) => {
|
|
1960
|
-
const ext = this._path.extname(path);
|
|
1961
|
-
const base = this._path.basename(path);
|
|
1962
|
-
const name = this._path.basename(path, ext);
|
|
1963
|
-
const dir = this._path.dirname(path);
|
|
1964
|
-
return { root: "/", dir, base, ext, name };
|
|
1965
|
-
},
|
|
1966
|
-
format: (pathObject) => {
|
|
1967
|
-
return this._path.join(pathObject.dir || "", pathObject.base || "");
|
|
1968
|
-
},
|
|
1969
|
-
sep: "/",
|
|
1970
|
-
delimiter: ":"
|
|
1971
|
-
};
|
|
1972
|
-
}
|
|
1973
|
-
};
|
|
1974
|
-
var A_UrlPolyfillClass = class {
|
|
1975
|
-
constructor(logger) {
|
|
1976
|
-
this.logger = logger;
|
|
1977
|
-
this._initialized = false;
|
|
1978
|
-
}
|
|
1979
|
-
get isInitialized() {
|
|
1980
|
-
return this._initialized;
|
|
1981
|
-
}
|
|
1982
|
-
async get() {
|
|
1983
|
-
if (!this._initialized) {
|
|
1984
|
-
await this.init();
|
|
1985
|
-
}
|
|
1986
|
-
return this._url;
|
|
1987
|
-
}
|
|
1988
|
-
async init() {
|
|
1989
|
-
try {
|
|
1990
|
-
if (A_Context.environment === "server") {
|
|
1991
|
-
await this.initServer();
|
|
1992
|
-
} else {
|
|
1993
|
-
this.initBrowser();
|
|
1994
|
-
}
|
|
1995
|
-
this._initialized = true;
|
|
1996
|
-
} catch (error) {
|
|
1997
|
-
this.initBrowser();
|
|
1998
|
-
this._initialized = true;
|
|
1999
|
-
}
|
|
2000
|
-
}
|
|
2001
|
-
async initServer() {
|
|
2002
|
-
const urlModule = await import('url');
|
|
2003
|
-
this._url = {
|
|
2004
|
-
parse: urlModule.parse,
|
|
2005
|
-
format: urlModule.format,
|
|
2006
|
-
resolve: urlModule.resolve,
|
|
2007
|
-
URL: urlModule.URL || globalThis.URL,
|
|
2008
|
-
URLSearchParams: urlModule.URLSearchParams || globalThis.URLSearchParams
|
|
2009
|
-
};
|
|
2010
|
-
}
|
|
2011
|
-
initBrowser() {
|
|
2012
|
-
this._url = {
|
|
2013
|
-
parse: (urlString) => {
|
|
2014
|
-
try {
|
|
2015
|
-
const url = new URL(urlString);
|
|
2016
|
-
return {
|
|
2017
|
-
protocol: url.protocol,
|
|
2018
|
-
hostname: url.hostname,
|
|
2019
|
-
port: url.port,
|
|
2020
|
-
pathname: url.pathname,
|
|
2021
|
-
search: url.search,
|
|
2022
|
-
hash: url.hash,
|
|
2023
|
-
host: url.host,
|
|
2024
|
-
href: url.href
|
|
2025
|
-
};
|
|
2026
|
-
} catch {
|
|
2027
|
-
return {};
|
|
2028
|
-
}
|
|
2029
|
-
},
|
|
2030
|
-
format: (urlObject) => {
|
|
2031
|
-
try {
|
|
2032
|
-
return new URL("", urlObject.href || `${urlObject.protocol}//${urlObject.host}${urlObject.pathname}${urlObject.search}${urlObject.hash}`).href;
|
|
2033
|
-
} catch {
|
|
2034
|
-
return "";
|
|
2035
|
-
}
|
|
2036
|
-
},
|
|
2037
|
-
resolve: (from, to) => {
|
|
2038
|
-
try {
|
|
2039
|
-
return new URL(to, from).href;
|
|
2040
|
-
} catch {
|
|
2041
|
-
return to;
|
|
2042
|
-
}
|
|
2043
|
-
},
|
|
2044
|
-
URL: globalThis.URL,
|
|
2045
|
-
URLSearchParams: globalThis.URLSearchParams
|
|
2046
|
-
};
|
|
2047
|
-
}
|
|
2048
|
-
};
|
|
2049
|
-
var A_BufferPolyfillClass = class {
|
|
2050
|
-
constructor(logger) {
|
|
2051
|
-
this.logger = logger;
|
|
2052
|
-
this._initialized = false;
|
|
2053
|
-
}
|
|
2054
|
-
get isInitialized() {
|
|
2055
|
-
return this._initialized;
|
|
2056
|
-
}
|
|
2057
|
-
async get() {
|
|
2058
|
-
if (!this._initialized) {
|
|
2059
|
-
await this.init();
|
|
2060
|
-
}
|
|
2061
|
-
return this._buffer;
|
|
2062
|
-
}
|
|
2063
|
-
async init() {
|
|
2064
|
-
try {
|
|
2065
|
-
if (A_Context.environment === "server") {
|
|
2066
|
-
await this.initServer();
|
|
2067
|
-
} else {
|
|
2068
|
-
this.initBrowser();
|
|
2069
|
-
}
|
|
2070
|
-
this._initialized = true;
|
|
2071
|
-
} catch (error) {
|
|
2072
|
-
this.initBrowser();
|
|
2073
|
-
this._initialized = true;
|
|
2074
|
-
}
|
|
2075
|
-
}
|
|
2076
|
-
async initServer() {
|
|
2077
|
-
const bufferModule = await import('buffer');
|
|
2078
|
-
this._buffer = {
|
|
2079
|
-
from: bufferModule.Buffer.from,
|
|
2080
|
-
alloc: bufferModule.Buffer.alloc,
|
|
2081
|
-
allocUnsafe: bufferModule.Buffer.allocUnsafe,
|
|
2082
|
-
isBuffer: bufferModule.Buffer.isBuffer,
|
|
2083
|
-
concat: bufferModule.Buffer.concat
|
|
2084
|
-
};
|
|
2085
|
-
}
|
|
2086
|
-
initBrowser() {
|
|
2087
|
-
this._buffer = {
|
|
2088
|
-
from: (data, encoding) => {
|
|
2089
|
-
if (typeof data === "string") {
|
|
2090
|
-
return new TextEncoder().encode(data);
|
|
2091
|
-
}
|
|
2092
|
-
return new Uint8Array(data);
|
|
2093
|
-
},
|
|
2094
|
-
alloc: (size, fill) => {
|
|
2095
|
-
const buffer = new Uint8Array(size);
|
|
2096
|
-
if (fill !== void 0) {
|
|
2097
|
-
buffer.fill(fill);
|
|
2098
|
-
}
|
|
2099
|
-
return buffer;
|
|
2100
|
-
},
|
|
2101
|
-
allocUnsafe: (size) => {
|
|
2102
|
-
return new Uint8Array(size);
|
|
2103
|
-
},
|
|
2104
|
-
isBuffer: (obj) => {
|
|
2105
|
-
return obj instanceof Uint8Array || obj instanceof ArrayBuffer;
|
|
2106
|
-
},
|
|
2107
|
-
concat: (list, totalLength) => {
|
|
2108
|
-
const length = totalLength || list.reduce((sum, buf) => sum + buf.length, 0);
|
|
2109
|
-
const result = new Uint8Array(length);
|
|
2110
|
-
let offset = 0;
|
|
2111
|
-
for (const buf of list) {
|
|
2112
|
-
result.set(buf, offset);
|
|
2113
|
-
offset += buf.length;
|
|
2114
|
-
}
|
|
2115
|
-
return result;
|
|
2116
|
-
}
|
|
2117
|
-
};
|
|
2118
|
-
}
|
|
2119
|
-
};
|
|
2120
|
-
var A_ProcessPolyfillClass = class {
|
|
2121
|
-
constructor(logger) {
|
|
2122
|
-
this.logger = logger;
|
|
2123
|
-
this._initialized = false;
|
|
2124
|
-
}
|
|
2125
|
-
get isInitialized() {
|
|
2126
|
-
return this._initialized;
|
|
2127
|
-
}
|
|
2128
|
-
async get() {
|
|
2129
|
-
if (!this._initialized) {
|
|
2130
|
-
await this.init();
|
|
2131
|
-
}
|
|
2132
|
-
return this._process;
|
|
2133
|
-
}
|
|
2134
|
-
async init() {
|
|
2135
|
-
try {
|
|
2136
|
-
if (A_Context.environment === "server") {
|
|
2137
|
-
this.initServer();
|
|
2138
|
-
} else {
|
|
2139
|
-
this.initBrowser();
|
|
2140
|
-
}
|
|
2141
|
-
this._initialized = true;
|
|
2142
|
-
} catch (error) {
|
|
2143
|
-
this.initBrowser();
|
|
2144
|
-
this._initialized = true;
|
|
2145
|
-
}
|
|
2146
|
-
}
|
|
2147
|
-
initServer() {
|
|
2148
|
-
this._process = {
|
|
2149
|
-
env: process.env,
|
|
2150
|
-
argv: process.argv,
|
|
2151
|
-
platform: process.platform,
|
|
2152
|
-
version: process.version,
|
|
2153
|
-
versions: process.versions,
|
|
2154
|
-
cwd: process.cwd,
|
|
2155
|
-
exit: process.exit,
|
|
2156
|
-
nextTick: process.nextTick
|
|
2157
|
-
};
|
|
2158
|
-
}
|
|
2159
|
-
initBrowser() {
|
|
2160
|
-
this._process = {
|
|
2161
|
-
env: {
|
|
2162
|
-
NODE_ENV: "browser",
|
|
2163
|
-
...globalThis.process?.env || {}
|
|
2164
|
-
},
|
|
2165
|
-
argv: ["browser"],
|
|
2166
|
-
platform: "browser",
|
|
2167
|
-
version: "browser",
|
|
2168
|
-
versions: { node: "browser" },
|
|
2169
|
-
cwd: () => "/",
|
|
2170
|
-
exit: (code) => {
|
|
2171
|
-
this.logger.warning("process.exit not available in browser");
|
|
2172
|
-
throw new Error(`Process exit with code ${code}`);
|
|
2173
|
-
},
|
|
2174
|
-
nextTick: (callback, ...args) => {
|
|
2175
|
-
setTimeout(() => callback(...args), 0);
|
|
2176
|
-
}
|
|
2177
|
-
};
|
|
2178
|
-
}
|
|
2179
|
-
};
|
|
2180
|
-
|
|
2181
|
-
// src/lib/A-Polyfill/A-Polyfill.component.ts
|
|
2182
|
-
var A_Polyfill = class extends A_Component {
|
|
2183
|
-
constructor(logger) {
|
|
2184
|
-
super();
|
|
2185
|
-
this.logger = logger;
|
|
2186
|
-
this._initializing = null;
|
|
2187
|
-
}
|
|
2188
|
-
/**
|
|
2189
|
-
* Indicates whether the channel is connected
|
|
2190
|
-
*/
|
|
2191
|
-
get ready() {
|
|
2192
|
-
if (!this._initialized) {
|
|
2193
|
-
this._initialized = this._loadInternal();
|
|
2194
|
-
}
|
|
2195
|
-
return this._initialized;
|
|
2196
|
-
}
|
|
2197
|
-
async load() {
|
|
2198
|
-
await this.ready;
|
|
2199
|
-
}
|
|
2200
|
-
async attachToWindow() {
|
|
2201
|
-
if (A_Context.environment !== "browser") return;
|
|
2202
|
-
globalThis.A_Polyfill = this;
|
|
2203
|
-
globalThis.process = { env: { NODE_ENV: "production" }, cwd: () => "/" };
|
|
2204
|
-
globalThis.__dirname = "/";
|
|
2205
|
-
}
|
|
2206
|
-
async _loadInternal() {
|
|
2207
|
-
this._fsPolyfill = new A_FSPolyfillClass(this.logger);
|
|
2208
|
-
this._cryptoPolyfill = new A_CryptoPolyfillClass(this.logger);
|
|
2209
|
-
this._httpPolyfill = new A_HttpPolyfillClass(this.logger);
|
|
2210
|
-
this._httpsPolyfill = new A_HttpsPolyfillClass(this.logger);
|
|
2211
|
-
this._pathPolyfill = new A_PathPolyfillClass(this.logger);
|
|
2212
|
-
this._urlPolyfill = new A_UrlPolyfillClass(this.logger);
|
|
2213
|
-
this._bufferPolyfill = new A_BufferPolyfillClass(this.logger);
|
|
2214
|
-
this._processPolyfill = new A_ProcessPolyfillClass(this.logger);
|
|
2215
|
-
await this._fsPolyfill.get();
|
|
2216
|
-
await this._cryptoPolyfill.get(await this._fsPolyfill.get());
|
|
2217
|
-
await this._httpPolyfill.get();
|
|
2218
|
-
await this._httpsPolyfill.get();
|
|
2219
|
-
await this._pathPolyfill.get();
|
|
2220
|
-
await this._urlPolyfill.get();
|
|
2221
|
-
await this._bufferPolyfill.get();
|
|
2222
|
-
await this._processPolyfill.get();
|
|
2223
|
-
}
|
|
2224
|
-
/**
|
|
2225
|
-
* Allows to use the 'fs' polyfill methods regardless of the environment
|
|
2226
|
-
* This method loads the 'fs' polyfill and returns its instance
|
|
2227
|
-
*
|
|
2228
|
-
* @returns
|
|
2229
|
-
*/
|
|
2230
|
-
async fs() {
|
|
2231
|
-
await this.ready;
|
|
2232
|
-
return await this._fsPolyfill.get();
|
|
2233
|
-
}
|
|
2234
|
-
/**
|
|
2235
|
-
* Allows to use the 'crypto' polyfill methods regardless of the environment
|
|
2236
|
-
* This method loads the 'crypto' polyfill and returns its instance
|
|
2237
|
-
*
|
|
2238
|
-
* @returns
|
|
2239
|
-
*/
|
|
2240
|
-
async crypto() {
|
|
2241
|
-
await this.ready;
|
|
2242
|
-
return await this._cryptoPolyfill.get();
|
|
2243
|
-
}
|
|
2244
|
-
/**
|
|
2245
|
-
* Allows to use the 'http' polyfill methods regardless of the environment
|
|
2246
|
-
* This method loads the 'http' polyfill and returns its instance
|
|
2247
|
-
*
|
|
2248
|
-
* @returns
|
|
2249
|
-
*/
|
|
2250
|
-
async http() {
|
|
2251
|
-
await this.ready;
|
|
2252
|
-
return await this._httpPolyfill.get();
|
|
2253
|
-
}
|
|
2254
|
-
/**
|
|
2255
|
-
* Allows to use the 'https' polyfill methods regardless of the environment
|
|
2256
|
-
* This method loads the 'https' polyfill and returns its instance
|
|
2257
|
-
*
|
|
2258
|
-
* @returns
|
|
2259
|
-
*/
|
|
2260
|
-
async https() {
|
|
2261
|
-
await this.ready;
|
|
2262
|
-
return await this._httpsPolyfill.get();
|
|
2263
|
-
}
|
|
2264
|
-
/**
|
|
2265
|
-
* Allows to use the 'path' polyfill methods regardless of the environment
|
|
2266
|
-
* This method loads the 'path' polyfill and returns its instance
|
|
2267
|
-
*
|
|
2268
|
-
* @returns
|
|
2269
|
-
*/
|
|
2270
|
-
async path() {
|
|
2271
|
-
await this.ready;
|
|
2272
|
-
return await this._pathPolyfill.get();
|
|
2273
|
-
}
|
|
2274
|
-
/**
|
|
2275
|
-
* Allows to use the 'url' polyfill methods regardless of the environment
|
|
2276
|
-
* This method loads the 'url' polyfill and returns its instance
|
|
2277
|
-
*
|
|
2278
|
-
* @returns
|
|
2279
|
-
*/
|
|
2280
|
-
async url() {
|
|
2281
|
-
await this.ready;
|
|
2282
|
-
return await this._urlPolyfill.get();
|
|
2283
|
-
}
|
|
2284
|
-
/**
|
|
2285
|
-
* Allows to use the 'buffer' polyfill methods regardless of the environment
|
|
2286
|
-
* This method loads the 'buffer' polyfill and returns its instance
|
|
2287
|
-
*
|
|
2288
|
-
* @returns
|
|
2289
|
-
*/
|
|
2290
|
-
async buffer() {
|
|
2291
|
-
await this.ready;
|
|
2292
|
-
return await this._bufferPolyfill.get();
|
|
2293
|
-
}
|
|
2294
|
-
/**
|
|
2295
|
-
* Allows to use the 'process' polyfill methods regardless of the environment
|
|
2296
|
-
* This method loads the 'process' polyfill and returns its instance
|
|
2297
|
-
*
|
|
2298
|
-
* @returns
|
|
2299
|
-
*/
|
|
2300
|
-
async process() {
|
|
2301
|
-
await this.ready;
|
|
2302
|
-
return await this._processPolyfill.get();
|
|
2303
|
-
}
|
|
2304
|
-
};
|
|
2305
|
-
__decorateClass([
|
|
2306
|
-
A_Concept.Load()
|
|
2307
|
-
], A_Polyfill.prototype, "load", 1);
|
|
2308
|
-
__decorateClass([
|
|
2309
|
-
A_Concept.Load()
|
|
2310
|
-
], A_Polyfill.prototype, "attachToWindow", 1);
|
|
2311
|
-
A_Polyfill = __decorateClass([
|
|
2312
|
-
__decorateParam(0, A_Inject(A_Logger))
|
|
2313
|
-
], A_Polyfill);
|
|
2314
|
-
var A_ConfigError = class extends A_Error {
|
|
2315
|
-
};
|
|
2316
|
-
A_ConfigError.InitializationError = "A-Config Initialization Error";
|
|
2317
|
-
var ConfigReader = class extends A_Component {
|
|
2318
|
-
constructor(polyfill) {
|
|
2319
|
-
super();
|
|
2320
|
-
this.polyfill = polyfill;
|
|
2321
|
-
}
|
|
2322
|
-
async attachContext(container, feature, config) {
|
|
2323
|
-
if (!config) {
|
|
2324
|
-
config = new A_Config({
|
|
2325
|
-
variables: [
|
|
2326
|
-
...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,
|
|
2327
|
-
...A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY
|
|
2328
|
-
],
|
|
2329
|
-
defaults: {}
|
|
2330
|
-
});
|
|
2331
|
-
container.scope.register(config);
|
|
2332
|
-
}
|
|
2333
|
-
const rootDir = await this.getProjectRoot();
|
|
2334
|
-
config.set("A_CONCEPT_ROOT_FOLDER", rootDir);
|
|
2335
|
-
}
|
|
2336
|
-
async initialize(config) {
|
|
2337
|
-
const data = await this.read([
|
|
2338
|
-
...config.CONFIG_PROPERTIES,
|
|
2339
|
-
...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,
|
|
2340
|
-
...A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY
|
|
2341
|
-
]);
|
|
2342
|
-
config.set(data);
|
|
2343
|
-
}
|
|
2344
|
-
/**
|
|
2345
|
-
* Get the configuration property by Name
|
|
2346
|
-
* @param property
|
|
2347
|
-
*/
|
|
2348
|
-
resolve(property) {
|
|
2349
|
-
return property;
|
|
2350
|
-
}
|
|
2351
|
-
/**
|
|
2352
|
-
* This method reads the configuration and sets the values to the context
|
|
2353
|
-
*
|
|
2354
|
-
* @returns
|
|
2355
|
-
*/
|
|
2356
|
-
async read(variables = []) {
|
|
2357
|
-
return {};
|
|
2358
|
-
}
|
|
2359
|
-
/**
|
|
2360
|
-
* Finds the root directory of the project by locating the folder containing package.json
|
|
2361
|
-
*
|
|
2362
|
-
* @param {string} startPath - The initial directory to start searching from (default is __dirname)
|
|
2363
|
-
* @returns {string|null} - The path to the root directory or null if package.json is not found
|
|
2364
|
-
*/
|
|
2365
|
-
async getProjectRoot(startPath = __dirname) {
|
|
2366
|
-
return process.cwd();
|
|
2367
|
-
}
|
|
2368
|
-
};
|
|
2369
|
-
__decorateClass([
|
|
2370
|
-
A_Concept.Load(),
|
|
2371
|
-
__decorateParam(0, A_Inject(A_Container)),
|
|
2372
|
-
__decorateParam(1, A_Inject(A_Feature)),
|
|
2373
|
-
__decorateParam(2, A_Inject(A_Config))
|
|
2374
|
-
], ConfigReader.prototype, "attachContext", 1);
|
|
2375
|
-
__decorateClass([
|
|
2376
|
-
A_Concept.Load(),
|
|
2377
|
-
__decorateParam(0, A_Inject(A_Config))
|
|
2378
|
-
], ConfigReader.prototype, "initialize", 1);
|
|
2379
|
-
ConfigReader = __decorateClass([
|
|
2380
|
-
__decorateParam(0, A_Inject(A_Polyfill))
|
|
2381
|
-
], ConfigReader);
|
|
2382
|
-
|
|
2383
|
-
// src/lib/A-Config/components/FileConfigReader.component.ts
|
|
2384
|
-
var FileConfigReader = class extends ConfigReader {
|
|
2385
|
-
constructor() {
|
|
2386
|
-
super(...arguments);
|
|
2387
|
-
this.FileData = /* @__PURE__ */ new Map();
|
|
2388
|
-
}
|
|
2389
|
-
/**
|
|
2390
|
-
* Get the configuration property Name
|
|
2391
|
-
* @param property
|
|
2392
|
-
*/
|
|
2393
|
-
getConfigurationProperty_File_Alias(property) {
|
|
2394
|
-
return A_FormatterHelper.toCamelCase(property);
|
|
2395
|
-
}
|
|
2396
|
-
resolve(property) {
|
|
2397
|
-
return this.FileData.get(this.getConfigurationProperty_File_Alias(property));
|
|
2398
|
-
}
|
|
2399
|
-
async read(variables) {
|
|
2400
|
-
const fs = await this.polyfill.fs();
|
|
2401
|
-
try {
|
|
2402
|
-
const data = fs.readFileSync(`${A_Context.concept}.conf.json`, "utf8");
|
|
2403
|
-
const config = JSON.parse(data);
|
|
2404
|
-
this.FileData = new Map(Object.entries(config));
|
|
2405
|
-
return config;
|
|
2406
|
-
} catch (error) {
|
|
2407
|
-
return {};
|
|
2408
|
-
}
|
|
2409
|
-
}
|
|
2410
|
-
};
|
|
2411
|
-
var ENVConfigReader = class extends ConfigReader {
|
|
2412
|
-
async readEnvFile(config, polyfill, feature) {
|
|
2413
|
-
const fs = await polyfill.fs();
|
|
2414
|
-
if (fs.existsSync(".env"))
|
|
2415
|
-
fs.readFileSync(`${config.get("A_CONCEPT_ROOT_FOLDER")}/.env`, "utf-8").split("\n").forEach((line) => {
|
|
2416
|
-
const [key, value] = line.split("=");
|
|
2417
|
-
if (key && value) {
|
|
2418
|
-
process.env[key.trim()] = value.trim();
|
|
2419
|
-
}
|
|
2420
|
-
});
|
|
2421
|
-
}
|
|
2422
|
-
/**
|
|
2423
|
-
* Get the configuration property Name
|
|
2424
|
-
* @param property
|
|
2425
|
-
*/
|
|
2426
|
-
getConfigurationProperty_ENV_Alias(property) {
|
|
2427
|
-
return A_FormatterHelper.toUpperSnakeCase(property);
|
|
2428
|
-
}
|
|
2429
|
-
resolve(property) {
|
|
2430
|
-
return process.env[this.getConfigurationProperty_ENV_Alias(property)];
|
|
2431
|
-
}
|
|
2432
|
-
async read(variables = []) {
|
|
2433
|
-
const allVariables = [
|
|
2434
|
-
...variables,
|
|
2435
|
-
...Object.keys(process.env)
|
|
2436
|
-
];
|
|
2437
|
-
const config = {};
|
|
2438
|
-
allVariables.forEach((variable) => {
|
|
2439
|
-
config[variable] = this.resolve(variable);
|
|
2440
|
-
});
|
|
2441
|
-
return config;
|
|
2442
|
-
}
|
|
2443
|
-
};
|
|
2444
|
-
__decorateClass([
|
|
2445
|
-
A_Concept.Load({
|
|
2446
|
-
before: ["ENVConfigReader.initialize"]
|
|
2447
|
-
}),
|
|
2448
|
-
__decorateParam(0, A_Inject(A_Config)),
|
|
2449
|
-
__decorateParam(1, A_Inject(A_Polyfill)),
|
|
2450
|
-
__decorateParam(2, A_Inject(A_Feature))
|
|
2451
|
-
], ENVConfigReader.prototype, "readEnvFile", 1);
|
|
2452
|
-
|
|
2453
|
-
// src/lib/A-Config/A-Config.container.ts
|
|
2454
|
-
var A_ConfigLoader = class extends A_Container {
|
|
2455
|
-
async prepare(polyfill) {
|
|
2456
|
-
if (!this.scope.has(A_Config)) {
|
|
2457
|
-
const newConfig = new A_Config({
|
|
2458
|
-
variables: [
|
|
2459
|
-
...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,
|
|
2460
|
-
...A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY
|
|
2461
|
-
],
|
|
2462
|
-
defaults: {}
|
|
2463
|
-
});
|
|
2464
|
-
this.scope.register(newConfig);
|
|
2465
|
-
}
|
|
2466
|
-
const fs = await polyfill.fs();
|
|
2467
|
-
try {
|
|
2468
|
-
switch (true) {
|
|
2469
|
-
case (A_Context.environment === "server" && !!fs.existsSync(`${A_Context.concept}.conf.json`)):
|
|
2470
|
-
this.reader = this.scope.resolve(FileConfigReader);
|
|
2471
|
-
break;
|
|
2472
|
-
case (A_Context.environment === "server" && !fs.existsSync(`${A_Context.concept}.conf.json`)):
|
|
2473
|
-
this.reader = this.scope.resolve(ENVConfigReader);
|
|
2474
|
-
break;
|
|
2475
|
-
case A_Context.environment === "browser":
|
|
2476
|
-
this.reader = this.scope.resolve(ENVConfigReader);
|
|
2477
|
-
break;
|
|
2478
|
-
default:
|
|
2479
|
-
throw new A_ConfigError(
|
|
2480
|
-
A_ConfigError.InitializationError,
|
|
2481
|
-
`Environment ${A_Context.environment} is not supported`
|
|
2482
|
-
);
|
|
2483
|
-
}
|
|
2484
|
-
} catch (error) {
|
|
2485
|
-
if (error instanceof A_ScopeError) {
|
|
2486
|
-
throw new A_ConfigError({
|
|
2487
|
-
title: A_ConfigError.InitializationError,
|
|
2488
|
-
description: `Failed to initialize A_ConfigLoader. Reader not found for environment ${A_Context.environment}`,
|
|
2489
|
-
originalError: error
|
|
2490
|
-
});
|
|
2491
|
-
}
|
|
2492
|
-
}
|
|
2493
|
-
}
|
|
2494
|
-
};
|
|
2495
|
-
__decorateClass([
|
|
2496
|
-
A_Concept.Load({
|
|
2497
|
-
before: /.*/
|
|
2498
|
-
}),
|
|
2499
|
-
__decorateParam(0, A_Inject(A_Polyfill))
|
|
2500
|
-
], A_ConfigLoader.prototype, "prepare", 1);
|
|
2501
|
-
|
|
2502
|
-
// src/lib/A-Config/A-Config.types.ts
|
|
2503
|
-
var A_TYPES__ConfigFeature = /* @__PURE__ */ ((A_TYPES__ConfigFeature2) => {
|
|
2504
|
-
return A_TYPES__ConfigFeature2;
|
|
2505
|
-
})(A_TYPES__ConfigFeature || {});
|
|
2506
|
-
var A_ManifestError = class extends A_Error {
|
|
2507
|
-
};
|
|
2508
|
-
A_ManifestError.ManifestInitializationError = "A-Manifest Initialization Error";
|
|
2509
|
-
|
|
2510
|
-
// src/lib/A-Manifest/classes/A-ManifestChecker.class.ts
|
|
2511
|
-
var A_ManifestChecker = class {
|
|
2512
|
-
constructor(manifest, component, method, checkExclusion = false) {
|
|
2513
|
-
this.manifest = manifest;
|
|
2514
|
-
this.component = component;
|
|
2515
|
-
this.method = method;
|
|
2516
|
-
this.checkExclusion = checkExclusion;
|
|
2517
|
-
}
|
|
2518
|
-
for(target) {
|
|
2519
|
-
const result = this.manifest.internal_checkAccess({
|
|
2520
|
-
component: this.component,
|
|
2521
|
-
method: this.method,
|
|
2522
|
-
target
|
|
2523
|
-
});
|
|
2524
|
-
return this.checkExclusion ? !result : result;
|
|
2525
|
-
}
|
|
2526
|
-
};
|
|
2527
|
-
|
|
2528
|
-
// src/lib/A-Manifest/A-Manifest.context.ts
|
|
2529
|
-
var A_Manifest = class extends A_Fragment {
|
|
2530
|
-
/**
|
|
2531
|
-
* A-Manifest is a configuration set that allows to include or exclude component application for the particular methods.
|
|
2532
|
-
*
|
|
2533
|
-
* For example, if A-Scope provides polymorphic A-Component that applies for All A-Entities in it but you have another component that should be used for only One particular Entity, you can use A-Manifest to specify this behavior.
|
|
2534
|
-
*
|
|
2535
|
-
*
|
|
2536
|
-
* By default if Component is provided in the scope - it applies for all entities in it. However, if you want to exclude some entities or include only some entities for the particular component - you can use A-Manifest to define this behavior.
|
|
2537
|
-
*
|
|
2538
|
-
* @param config - Array of component configurations
|
|
2539
|
-
*/
|
|
2540
|
-
constructor(config = []) {
|
|
2541
|
-
super({
|
|
2542
|
-
name: "A-Manifest"
|
|
2543
|
-
});
|
|
2544
|
-
this.rules = [];
|
|
2545
|
-
this.prepare(config);
|
|
2546
|
-
}
|
|
2547
|
-
/**
|
|
2548
|
-
* Should convert received configuration into internal Regexp applicable for internal storage
|
|
2549
|
-
*/
|
|
2550
|
-
prepare(config) {
|
|
2551
|
-
if (!A_TypeGuards.isArray(config))
|
|
2552
|
-
throw new A_ManifestError(
|
|
2553
|
-
A_ManifestError.ManifestInitializationError,
|
|
2554
|
-
`A-Manifest configuration should be an array of configurations`
|
|
2555
|
-
);
|
|
2556
|
-
for (const item of config) {
|
|
2557
|
-
this.processConfigItem(item);
|
|
2558
|
-
}
|
|
2559
|
-
}
|
|
2560
|
-
/**
|
|
2561
|
-
* Process a single configuration item and convert it to internal rules
|
|
2562
|
-
*/
|
|
2563
|
-
processConfigItem(item) {
|
|
2564
|
-
if (!A_TypeGuards.isComponentConstructor(item.component))
|
|
2565
|
-
throw new A_ManifestError(
|
|
2566
|
-
A_ManifestError.ManifestInitializationError,
|
|
2567
|
-
`A-Manifest configuration item should be a A-Component constructor`
|
|
2568
|
-
);
|
|
2569
|
-
const componentRegex = this.constructorToRegex(item.component);
|
|
2570
|
-
if (item.apply || item.exclude) {
|
|
2571
|
-
const methodRegex = /.*/;
|
|
2572
|
-
this.rules.push({
|
|
2573
|
-
componentRegex,
|
|
2574
|
-
methodRegex,
|
|
2575
|
-
applyRegex: item.apply ? this.allowedComponentsToRegex(item.apply) : void 0,
|
|
2576
|
-
excludeRegex: item.exclude ? this.allowedComponentsToRegex(item.exclude) : void 0
|
|
2577
|
-
});
|
|
2578
|
-
}
|
|
2579
|
-
if (item.methods && item.methods.length > 0) {
|
|
2580
|
-
for (const methodConfig of item.methods) {
|
|
2581
|
-
const methodRegex = this.methodToRegex(methodConfig.method);
|
|
2582
|
-
this.rules.push({
|
|
2583
|
-
componentRegex,
|
|
2584
|
-
methodRegex,
|
|
2585
|
-
applyRegex: methodConfig.apply ? this.allowedComponentsToRegex(methodConfig.apply) : void 0,
|
|
2586
|
-
excludeRegex: methodConfig.exclude ? this.allowedComponentsToRegex(methodConfig.exclude) : void 0
|
|
2587
|
-
});
|
|
2588
|
-
}
|
|
2589
|
-
}
|
|
2590
|
-
}
|
|
2591
|
-
/**
|
|
2592
|
-
* Convert a constructor to a regex pattern
|
|
2593
|
-
*/
|
|
2594
|
-
constructorToRegex(ctor) {
|
|
2595
|
-
return new RegExp(`^${this.escapeRegex(ctor.name)}$`);
|
|
2596
|
-
}
|
|
2597
|
-
/**
|
|
2598
|
-
* Convert a method name or regex to a regex pattern
|
|
2599
|
-
*/
|
|
2600
|
-
methodToRegex(method) {
|
|
2601
|
-
if (method instanceof RegExp) {
|
|
2602
|
-
return method;
|
|
2603
|
-
}
|
|
2604
|
-
return new RegExp(`^${this.escapeRegex(method)}$`);
|
|
2605
|
-
}
|
|
2606
|
-
/**
|
|
2607
|
-
* Convert allowed components array or regex to a single regex
|
|
2608
|
-
*/
|
|
2609
|
-
allowedComponentsToRegex(components) {
|
|
2610
|
-
if (components instanceof RegExp) {
|
|
2611
|
-
return components;
|
|
2612
|
-
}
|
|
2613
|
-
const patterns = components.map((ctor) => this.escapeRegex(ctor.name));
|
|
2614
|
-
return new RegExp(`^(${patterns.join("|")})$`);
|
|
2615
|
-
}
|
|
2616
|
-
/**
|
|
2617
|
-
* Escape special regex characters in a string
|
|
2618
|
-
*/
|
|
2619
|
-
escapeRegex(str) {
|
|
2620
|
-
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2621
|
-
}
|
|
2622
|
-
configItemToRegexp(item) {
|
|
2623
|
-
return this.constructorToRegex(item);
|
|
2624
|
-
}
|
|
2625
|
-
ID(component, method) {
|
|
2626
|
-
return `${component.name}.${method}`;
|
|
2627
|
-
}
|
|
2628
|
-
/**
|
|
2629
|
-
* Check if a component and method combination is allowed for a target
|
|
2630
|
-
*/
|
|
2631
|
-
isAllowed(ctor, method) {
|
|
2632
|
-
const componentCtor = typeof ctor === "function" ? ctor : ctor.constructor;
|
|
2633
|
-
return new A_ManifestChecker(this, componentCtor, method);
|
|
2634
|
-
}
|
|
2635
|
-
/**
|
|
2636
|
-
* Internal method to check if access is allowed
|
|
2637
|
-
*/
|
|
2638
|
-
internal_checkAccess(query) {
|
|
2639
|
-
const componentName = query.component.name;
|
|
2640
|
-
const methodName = query.method;
|
|
2641
|
-
const targetName = query.target.name;
|
|
2642
|
-
const matchingRules = this.rules.filter(
|
|
2643
|
-
(rule) => rule.componentRegex.test(componentName) && rule.methodRegex.test(methodName)
|
|
2644
|
-
).sort((a, b) => {
|
|
2645
|
-
const aIsGeneral = a.methodRegex.source === ".*";
|
|
2646
|
-
const bIsGeneral = b.methodRegex.source === ".*";
|
|
2647
|
-
if (aIsGeneral && !bIsGeneral) return 1;
|
|
2648
|
-
if (!aIsGeneral && bIsGeneral) return -1;
|
|
2649
|
-
return 0;
|
|
2650
|
-
});
|
|
2651
|
-
if (matchingRules.length === 0) {
|
|
2652
|
-
return true;
|
|
2653
|
-
}
|
|
2654
|
-
for (const rule of matchingRules) {
|
|
2655
|
-
if (rule.excludeRegex && rule.excludeRegex.test(targetName)) {
|
|
2656
|
-
return false;
|
|
2657
|
-
}
|
|
2658
|
-
if (rule.applyRegex) {
|
|
2659
|
-
return rule.applyRegex.test(targetName);
|
|
2660
|
-
}
|
|
2661
|
-
}
|
|
2662
|
-
return true;
|
|
2663
|
-
}
|
|
2664
|
-
isExcluded(ctor, method) {
|
|
2665
|
-
const componentCtor = typeof ctor === "function" ? ctor : ctor.constructor;
|
|
2666
|
-
return new A_ManifestChecker(this, componentCtor, method, true);
|
|
2667
|
-
}
|
|
2668
|
-
};
|
|
2669
|
-
var A_MemoryContext = class extends A_Fragment {
|
|
2670
|
-
set(param, value) {
|
|
2671
|
-
super.set(param, value);
|
|
2672
|
-
}
|
|
2673
|
-
get(param) {
|
|
2674
|
-
return super.get(param);
|
|
2675
|
-
}
|
|
2676
|
-
};
|
|
2677
|
-
var A_MemoryError = class extends A_Error {
|
|
2678
|
-
};
|
|
2679
|
-
A_MemoryError.MemoryInitializationError = "Memory initialization error";
|
|
2680
|
-
A_MemoryError.MemoryDestructionError = "Memory destruction error";
|
|
2681
|
-
A_MemoryError.MemoryGetError = "Memory GET operation failed";
|
|
2682
|
-
A_MemoryError.MemorySetError = "Memory SET operation failed";
|
|
2683
|
-
A_MemoryError.MemoryDropError = "Memory DROP operation failed";
|
|
2684
|
-
A_MemoryError.MemoryClearError = "Memory CLEAR operation failed";
|
|
2685
|
-
A_MemoryError.MemoryHasError = "Memory HAS operation failed";
|
|
2686
|
-
A_MemoryError.MemorySerializeError = "Memory toJSON operation failed";
|
|
2687
|
-
|
|
2688
|
-
// src/lib/A-Memory/A-Memory.component.ts
|
|
2689
|
-
var _a3, _b3, _c3, _d3, _e2, _f2, _g2, _h2, _i2;
|
|
2690
|
-
var A_Memory = class extends A_Component {
|
|
2691
|
-
get ready() {
|
|
2692
|
-
if (!this._ready) {
|
|
2693
|
-
this._ready = this.init();
|
|
2694
|
-
}
|
|
2695
|
-
return this._ready;
|
|
2696
|
-
}
|
|
2697
|
-
/**
|
|
2698
|
-
* Handles errors during memory operations
|
|
2699
|
-
*/
|
|
2700
|
-
async [_i2 = "onError" /* onError */](...args) {
|
|
2701
|
-
}
|
|
2702
|
-
/**
|
|
2703
|
-
* Handles memory expiration
|
|
2704
|
-
*/
|
|
2705
|
-
async [_h2 = "onExpire" /* onExpire */](...args) {
|
|
2706
|
-
}
|
|
2707
|
-
/**
|
|
2708
|
-
* Initializes the memory context
|
|
2709
|
-
*/
|
|
2710
|
-
async [_g2 = "onInit" /* onInit */](context, ...args) {
|
|
2711
|
-
if (!context) {
|
|
2712
|
-
context = new A_MemoryContext();
|
|
2713
|
-
A_Context.scope(this).register(context);
|
|
2714
|
-
}
|
|
2715
|
-
}
|
|
2716
|
-
async [_f2 = "onDestroy" /* onDestroy */](context, ...args) {
|
|
2717
|
-
context.clear();
|
|
2718
|
-
}
|
|
2719
|
-
/**
|
|
2720
|
-
* Handles the 'get' operation for retrieving a value from memory
|
|
2721
|
-
*/
|
|
2722
|
-
async [_e2 = "onGet" /* onGet */](operation, context, ...args) {
|
|
2723
|
-
operation.succeed(context.get(operation.params.key));
|
|
2724
|
-
}
|
|
2725
|
-
/**
|
|
2726
|
-
* Handles the 'has' operation for checking existence of a key in memory
|
|
2727
|
-
*/
|
|
2728
|
-
async [_d3 = "onHas" /* onHas */](operation, context, ...args) {
|
|
2729
|
-
operation.succeed(context.has(operation.params.key));
|
|
2730
|
-
}
|
|
2731
|
-
/**
|
|
2732
|
-
* Handles the 'set' operation for saving a value in memory
|
|
2733
|
-
*/
|
|
2734
|
-
async [_c3 = "onSet" /* onSet */](operation, context, ...args) {
|
|
2735
|
-
context.set(operation.params.key, operation.params.value);
|
|
2736
|
-
}
|
|
2737
|
-
/**
|
|
2738
|
-
* Handles the 'drop' operation for removing a value from memory
|
|
2739
|
-
*/
|
|
2740
|
-
async [_b3 = "onDrop" /* onDrop */](operation, context, ...args) {
|
|
2741
|
-
context.drop(operation.params.key);
|
|
2742
|
-
}
|
|
2743
|
-
/**
|
|
2744
|
-
* Handles the 'clear' operation for clearing all values from memory
|
|
2745
|
-
*/
|
|
2746
|
-
async [_a3 = "onClear" /* onClear */](operation, context, ...args) {
|
|
2747
|
-
context.clear();
|
|
2748
|
-
}
|
|
2749
|
-
// ======================================================================
|
|
2750
|
-
// =========================A-Memory Methods=============================
|
|
2751
|
-
// ======================================================================
|
|
2752
|
-
/**
|
|
2753
|
-
* Initializes the memory context
|
|
2754
|
-
*/
|
|
2755
|
-
async init() {
|
|
2756
|
-
if (this._ready)
|
|
2757
|
-
return this._ready;
|
|
2758
|
-
const scope = new A_Scope({ name: "A-Memory-Init-Scope" }).inherit(A_Context.scope(this));
|
|
2759
|
-
try {
|
|
2760
|
-
await this.call("onInit" /* onInit */, scope);
|
|
2761
|
-
} catch (error) {
|
|
2762
|
-
const initError = new A_MemoryError({
|
|
2763
|
-
title: A_MemoryError.MemoryInitializationError,
|
|
2764
|
-
description: "An error occurred during memory initialization",
|
|
2765
|
-
originalError: error
|
|
2766
|
-
});
|
|
2767
|
-
scope.register(initError);
|
|
2768
|
-
await this.call("onError" /* onError */, scope);
|
|
2769
|
-
scope.destroy();
|
|
2770
|
-
throw initError;
|
|
2771
|
-
}
|
|
2772
|
-
}
|
|
2773
|
-
/**
|
|
2774
|
-
* Destroys the memory context
|
|
2775
|
-
*
|
|
2776
|
-
* This method is responsible for cleaning up any resources
|
|
2777
|
-
* used by the memory context and resetting its state.
|
|
2778
|
-
*/
|
|
2779
|
-
async destroy() {
|
|
2780
|
-
const scope = new A_Scope({ name: "A-Memory-Destroy-Scope" }).inherit(A_Context.scope(this));
|
|
2781
|
-
try {
|
|
2782
|
-
this._ready = void 0;
|
|
2783
|
-
await this.call("onDestroy" /* onDestroy */, scope);
|
|
2784
|
-
} catch (error) {
|
|
2785
|
-
const destroyError = new A_MemoryError({
|
|
2786
|
-
title: A_MemoryError.MemoryDestructionError,
|
|
2787
|
-
description: "An error occurred during memory destruction",
|
|
2788
|
-
originalError: error
|
|
2789
|
-
});
|
|
2790
|
-
scope.register(destroyError);
|
|
2791
|
-
await this.call("onError" /* onError */, scope);
|
|
2792
|
-
scope.destroy();
|
|
2793
|
-
throw destroyError;
|
|
2794
|
-
}
|
|
2795
|
-
}
|
|
2796
|
-
/**
|
|
2797
|
-
* Retrieves a value from the context memory
|
|
2798
|
-
*
|
|
2799
|
-
* @param key - memory key to retrieve
|
|
2800
|
-
* @returns - value associated with the key or undefined if not found
|
|
2801
|
-
*/
|
|
2802
|
-
async get(key) {
|
|
2803
|
-
const operation = new A_OperationContext("get", { key });
|
|
2804
|
-
const scope = new A_Scope({
|
|
2805
|
-
name: "A-Memory-Get-Operation-Scope",
|
|
2806
|
-
fragments: [operation]
|
|
2807
|
-
});
|
|
2808
|
-
try {
|
|
2809
|
-
await this.call("onGet" /* onGet */, scope);
|
|
2810
|
-
scope.destroy();
|
|
2811
|
-
return operation.result;
|
|
2812
|
-
} catch (error) {
|
|
2813
|
-
const getError = new A_MemoryError({
|
|
2814
|
-
title: A_MemoryError.MemoryGetError,
|
|
2815
|
-
description: `An error occurred while getting the value for key "${String(key)}"`,
|
|
2816
|
-
originalError: error
|
|
2817
|
-
});
|
|
2818
|
-
scope.register(getError);
|
|
2819
|
-
await this.call("onError" /* onError */, scope);
|
|
2820
|
-
scope.destroy();
|
|
2821
|
-
throw getError;
|
|
2822
|
-
}
|
|
2823
|
-
}
|
|
2824
|
-
/**
|
|
2825
|
-
* Checks if a value exists in the context memory
|
|
2826
|
-
*
|
|
2827
|
-
* @param key - memory key to check
|
|
2828
|
-
* @returns - true if key exists, false otherwise
|
|
2829
|
-
*/
|
|
2830
|
-
async has(key) {
|
|
2831
|
-
const operation = new A_OperationContext("has", { key });
|
|
2832
|
-
const scope = new A_Scope({
|
|
2833
|
-
name: "A-Memory-Has-Operation-Scope",
|
|
2834
|
-
fragments: [operation]
|
|
2835
|
-
});
|
|
2836
|
-
try {
|
|
2837
|
-
await this.call("onHas" /* onHas */, scope);
|
|
2838
|
-
scope.destroy();
|
|
2839
|
-
return operation.result;
|
|
2840
|
-
} catch (error) {
|
|
2841
|
-
const getError = new A_MemoryError({
|
|
2842
|
-
title: A_MemoryError.MemoryHasError,
|
|
2843
|
-
description: `An error occurred while checking existence for key "${String(key)}"`,
|
|
2844
|
-
originalError: error
|
|
2845
|
-
});
|
|
2846
|
-
scope.register(getError);
|
|
2847
|
-
await this.call("onError" /* onError */, scope);
|
|
2848
|
-
scope.destroy();
|
|
2849
|
-
throw getError;
|
|
2850
|
-
}
|
|
2851
|
-
}
|
|
2852
|
-
/**
|
|
2853
|
-
* Saves a value in the context memory
|
|
2854
|
-
*
|
|
2855
|
-
* @param key
|
|
2856
|
-
* @param value
|
|
2857
|
-
*/
|
|
2858
|
-
async set(key, value) {
|
|
2859
|
-
const operation = new A_OperationContext("set", { key, value });
|
|
2860
|
-
const scope = new A_Scope({
|
|
2861
|
-
name: "A-Memory-Set-Operation-Scope",
|
|
2862
|
-
fragments: [operation]
|
|
2863
|
-
});
|
|
2864
|
-
try {
|
|
2865
|
-
await this.call("onSet" /* onSet */, scope);
|
|
2866
|
-
} catch (error) {
|
|
2867
|
-
const setError = new A_MemoryError({
|
|
2868
|
-
title: A_MemoryError.MemorySetError,
|
|
2869
|
-
description: `An error occurred while setting the value for key "${String(key)}"`,
|
|
2870
|
-
originalError: error
|
|
2871
|
-
});
|
|
2872
|
-
scope.register(setError);
|
|
2873
|
-
await this.call("onError" /* onError */, scope);
|
|
2874
|
-
scope.destroy();
|
|
2875
|
-
throw setError;
|
|
2876
|
-
}
|
|
2877
|
-
}
|
|
2878
|
-
/**
|
|
2879
|
-
* Removes a value from the context memory by key
|
|
2880
|
-
*
|
|
2881
|
-
* @param key
|
|
2882
|
-
*/
|
|
2883
|
-
async drop(key) {
|
|
2884
|
-
const operation = new A_OperationContext("drop", { key });
|
|
2885
|
-
const scope = new A_Scope({
|
|
2886
|
-
name: "A-Memory-Drop-Operation-Scope",
|
|
2887
|
-
fragments: [operation]
|
|
2888
|
-
});
|
|
2889
|
-
try {
|
|
2890
|
-
await this.call("onDrop" /* onDrop */, scope);
|
|
2891
|
-
} catch (error) {
|
|
2892
|
-
const dropError = new A_MemoryError({
|
|
2893
|
-
title: A_MemoryError.MemoryDropError,
|
|
2894
|
-
description: `An error occurred while dropping the value for key "${String(key)}"`,
|
|
2895
|
-
originalError: error
|
|
2896
|
-
});
|
|
2897
|
-
scope.register(dropError);
|
|
2898
|
-
await this.call("onError" /* onError */, scope);
|
|
2899
|
-
scope.destroy();
|
|
2900
|
-
throw dropError;
|
|
2901
|
-
}
|
|
2902
|
-
}
|
|
2903
|
-
/**
|
|
2904
|
-
* Clears all stored values in the context memory
|
|
2905
|
-
*/
|
|
2906
|
-
async clear() {
|
|
2907
|
-
const operation = new A_OperationContext("clear");
|
|
2908
|
-
const scope = new A_Scope({
|
|
2909
|
-
name: "A-Memory-Clear-Operation-Scope",
|
|
2910
|
-
fragments: [operation]
|
|
2911
|
-
});
|
|
2912
|
-
try {
|
|
2913
|
-
await this.call("onClear" /* onClear */, scope);
|
|
2914
|
-
} catch (error) {
|
|
2915
|
-
const clearError = new A_MemoryError({
|
|
2916
|
-
title: A_MemoryError.MemoryClearError,
|
|
2917
|
-
description: `An error occurred while clearing the memory`,
|
|
2918
|
-
originalError: error
|
|
2919
|
-
});
|
|
2920
|
-
scope.register(clearError);
|
|
2921
|
-
await this.call("onError" /* onError */, scope);
|
|
2922
|
-
scope.destroy();
|
|
2923
|
-
throw clearError;
|
|
2924
|
-
}
|
|
2925
|
-
}
|
|
2926
|
-
/**
|
|
2927
|
-
* Serializes the memory context to a JSON object
|
|
2928
|
-
*
|
|
2929
|
-
* @returns - serialized memory object
|
|
2930
|
-
*/
|
|
2931
|
-
async toJSON() {
|
|
2932
|
-
const operation = new A_OperationContext("serialize");
|
|
2933
|
-
const scope = new A_Scope({
|
|
2934
|
-
name: "A-Memory-Serialize-Operation-Scope",
|
|
2935
|
-
fragments: [operation]
|
|
2936
|
-
});
|
|
2937
|
-
try {
|
|
2938
|
-
await this.call("onSerialize" /* onSerialize */, scope);
|
|
2939
|
-
return operation.result;
|
|
2940
|
-
} catch (error) {
|
|
2941
|
-
const serializeError = new A_MemoryError({
|
|
2942
|
-
title: A_MemoryError.MemorySerializeError,
|
|
2943
|
-
description: `An error occurred while serializing the memory`,
|
|
2944
|
-
originalError: error
|
|
2945
|
-
});
|
|
2946
|
-
scope.register(serializeError);
|
|
2947
|
-
await this.call("onError" /* onError */, scope);
|
|
2948
|
-
scope.destroy();
|
|
2949
|
-
throw serializeError;
|
|
2950
|
-
}
|
|
2951
|
-
}
|
|
2952
|
-
};
|
|
2953
|
-
__decorateClass([
|
|
2954
|
-
A_Feature.Extend()
|
|
2955
|
-
], A_Memory.prototype, _i2, 1);
|
|
2956
|
-
__decorateClass([
|
|
2957
|
-
A_Feature.Extend()
|
|
2958
|
-
], A_Memory.prototype, _h2, 1);
|
|
2959
|
-
__decorateClass([
|
|
2960
|
-
A_Feature.Extend(),
|
|
2961
|
-
__decorateParam(0, A_Inject(A_MemoryContext))
|
|
2962
|
-
], A_Memory.prototype, _g2, 1);
|
|
2963
|
-
__decorateClass([
|
|
2964
|
-
A_Feature.Extend(),
|
|
2965
|
-
__decorateParam(0, A_Inject(A_MemoryContext))
|
|
2966
|
-
], A_Memory.prototype, _f2, 1);
|
|
2967
|
-
__decorateClass([
|
|
2968
|
-
A_Feature.Extend(),
|
|
2969
|
-
__decorateParam(0, A_Dependency.Required()),
|
|
2970
|
-
__decorateParam(0, A_Inject(A_OperationContext)),
|
|
2971
|
-
__decorateParam(1, A_Inject(A_MemoryContext))
|
|
2972
|
-
], A_Memory.prototype, _e2, 1);
|
|
2973
|
-
__decorateClass([
|
|
2974
|
-
A_Feature.Extend(),
|
|
2975
|
-
__decorateParam(0, A_Dependency.Required()),
|
|
2976
|
-
__decorateParam(0, A_Inject(A_OperationContext)),
|
|
2977
|
-
__decorateParam(1, A_Inject(A_MemoryContext))
|
|
2978
|
-
], A_Memory.prototype, _d3, 1);
|
|
2979
|
-
__decorateClass([
|
|
2980
|
-
A_Feature.Extend(),
|
|
2981
|
-
__decorateParam(0, A_Dependency.Required()),
|
|
2982
|
-
__decorateParam(0, A_Inject(A_OperationContext)),
|
|
2983
|
-
__decorateParam(1, A_Inject(A_MemoryContext))
|
|
2984
|
-
], A_Memory.prototype, _c3, 1);
|
|
2985
|
-
__decorateClass([
|
|
2986
|
-
A_Feature.Extend(),
|
|
2987
|
-
__decorateParam(0, A_Dependency.Required()),
|
|
2988
|
-
__decorateParam(0, A_Inject(A_OperationContext)),
|
|
2989
|
-
__decorateParam(1, A_Inject(A_MemoryContext))
|
|
2990
|
-
], A_Memory.prototype, _b3, 1);
|
|
2991
|
-
__decorateClass([
|
|
2992
|
-
A_Feature.Extend(),
|
|
2993
|
-
__decorateParam(0, A_Dependency.Required()),
|
|
2994
|
-
__decorateParam(0, A_Inject(A_OperationContext)),
|
|
2995
|
-
__decorateParam(1, A_Inject(A_MemoryContext))
|
|
2996
|
-
], A_Memory.prototype, _a3, 1);
|
|
2997
|
-
|
|
2998
|
-
// src/lib/A-Schedule/A-Deferred.class.ts
|
|
2999
|
-
var A_Deferred = class {
|
|
3000
|
-
/**
|
|
3001
|
-
* Creates a deferred promise
|
|
3002
|
-
* @returns A promise that can be resolved or rejected later
|
|
3003
|
-
*/
|
|
3004
|
-
constructor() {
|
|
3005
|
-
this.promise = new Promise((resolve, reject) => {
|
|
3006
|
-
this.resolveFn = resolve;
|
|
3007
|
-
this.rejectFn = reject;
|
|
3008
|
-
});
|
|
3009
|
-
}
|
|
3010
|
-
resolve(value) {
|
|
3011
|
-
this.resolveFn(value);
|
|
3012
|
-
}
|
|
3013
|
-
reject(reason) {
|
|
3014
|
-
this.rejectFn(reason);
|
|
3015
|
-
}
|
|
3016
|
-
};
|
|
3017
|
-
var A_ScheduleObject = class {
|
|
3018
|
-
/**
|
|
3019
|
-
* Creates a scheduled object that will execute the action after specified milliseconds
|
|
3020
|
-
*
|
|
3021
|
-
*
|
|
3022
|
-
* @param ms - milliseconds to wait before executing the action
|
|
3023
|
-
* @param action - the action to execute
|
|
3024
|
-
* @param config - configuration options for the schedule object
|
|
3025
|
-
*/
|
|
3026
|
-
constructor(ms, action, config) {
|
|
3027
|
-
this.config = {
|
|
3028
|
-
/**
|
|
3029
|
-
* If the timeout is cleared, should the promise resolve or reject?
|
|
3030
|
-
* BY Default it rejects
|
|
3031
|
-
*
|
|
3032
|
-
* !!!NOTE: If the property is set to true, the promise will resolve with undefined
|
|
3033
|
-
*/
|
|
3034
|
-
resolveOnClear: false
|
|
3035
|
-
};
|
|
3036
|
-
if (config)
|
|
3037
|
-
this.config = { ...this.config, ...config };
|
|
3038
|
-
this.deferred = new A_Deferred();
|
|
3039
|
-
this.timeout = setTimeout(
|
|
3040
|
-
() => action().then((...args) => this.deferred.resolve(...args)).catch((...args) => this.deferred.reject(...args)),
|
|
3041
|
-
ms
|
|
3042
|
-
);
|
|
3043
|
-
}
|
|
3044
|
-
get promise() {
|
|
3045
|
-
return this.deferred.promise;
|
|
3046
|
-
}
|
|
3047
|
-
clear() {
|
|
3048
|
-
if (this.timeout) {
|
|
3049
|
-
clearTimeout(this.timeout);
|
|
3050
|
-
if (this.config.resolveOnClear)
|
|
3051
|
-
this.deferred.resolve(void 0);
|
|
3052
|
-
else
|
|
3053
|
-
this.deferred.reject(new A_Error("Timeout Cleared"));
|
|
3054
|
-
}
|
|
3055
|
-
}
|
|
3056
|
-
};
|
|
3057
|
-
|
|
3058
|
-
// src/lib/A-Schedule/A-Schedule.component.ts
|
|
3059
|
-
var A_Schedule = class extends A_Component {
|
|
3060
|
-
async schedule(date, callback, config) {
|
|
3061
|
-
const timestamp = A_TypeGuards.isString(date) ? new Date(date).getTime() : date;
|
|
3062
|
-
return new A_ScheduleObject(
|
|
3063
|
-
timestamp - Date.now(),
|
|
3064
|
-
callback,
|
|
3065
|
-
config
|
|
3066
|
-
);
|
|
3067
|
-
}
|
|
3068
|
-
/**
|
|
3069
|
-
* Allows to execute callback after particular delay in milliseconds
|
|
3070
|
-
* So the callback will be executed after the specified delay
|
|
3071
|
-
*
|
|
3072
|
-
* @param ms
|
|
3073
|
-
*/
|
|
3074
|
-
async delay(ms, callback, config) {
|
|
3075
|
-
return new A_ScheduleObject(
|
|
3076
|
-
ms,
|
|
3077
|
-
callback,
|
|
3078
|
-
config
|
|
3079
|
-
);
|
|
3080
|
-
}
|
|
3081
|
-
};
|
|
3082
|
-
|
|
3083
|
-
export { A_CONSTANTS__CONFIG_ENV_VARIABLES, A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY, A_Channel, A_ChannelError, A_ChannelFeatures, A_ChannelRequestStatuses, A_Command, A_CommandError, A_CommandFeatures, A_CommandTransitions, A_Command_Status, A_Config, A_ConfigError, A_ConfigLoader, A_Deferred, A_Logger, A_Manifest, A_ManifestChecker, A_ManifestError, A_Memory, A_Polyfill, A_Schedule, A_ScheduleObject, A_TYPES__ConfigFeature, ConfigReader, ENVConfigReader, FileConfigReader };
|
|
3084
|
-
//# sourceMappingURL=index.mjs.map
|
|
1
|
+
import {A_Feature,A_Inject,A_Scope,A_Error,A_Dependency,A_Concept,A_Container,A_TypeGuards,A_Component,A_IdentityHelper,A_Context,A_FormatterHelper,A_Fragment,A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,A_CommonHelper,A_Entity,A_ScopeError}from'@adaas/a-concept';var Ke=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var i=(k,t)=>Ke(k,"name",{value:t,configurable:true});var p=(k,t,e,r)=>{for(var o=r>1?void 0:r?pt(t,e):t,n=k.length-1,s;n>=0;n--)(s=k[n])&&(o=(r?s(t,e,o):s(o))||o);return r&&o&&Ke(t,e,o),o},c=(k,t)=>(e,r)=>t(e,r,k);var ue=class ue extends A_Fragment{constructor(t,e){super(),this.meta.set("name",t),this.meta.set("params",e||{});}get name(){return this._meta.get("name")||this._name}get result(){return this._meta.get("result")}get error(){return this._meta.get("error")}get params(){return this._meta.get("params")||{}}fail(t){this._meta.set("error",t);}succeed(t){this._meta.set("result",t);}toJSON(){return {name:this.name,params:this.params,result:this.result||{},error:this.error?.toJSON()}}};i(ue,"A_OperationContext");var l=ue;var re=class re extends A_Error{constructor(t,e){A_TypeGuards.isString(e)?super(t,e):super(t),e instanceof l&&(this._context=e);}get context(){return this._context}};i(re,"A_ChannelError"),re.MethodNotImplemented="A-Channel Method Not Implemented";var M=re;var dt=(E=>(E.onTimeout="onTimeout",E.onRetry="onRetry",E.onCircuitBreakerOpen="onCircuitBreakerOpen",E.onCache="onCache",E.onConnect="onConnect",E.onDisconnect="onDisconnect",E.onBeforeRequest="onBeforeRequest",E.onRequest="onRequest",E.onAfterRequest="onAfterRequest",E.onError="onError",E.onSend="onSend",E.onConsume="onConsume",E))(dt||{}),ht=(r=>(r.PENDING="PENDING",r.SUCCESS="SUCCESS",r.FAILED="FAILED",r))(ht||{});var ye=class ye extends l{constructor(t){super("request",t);}get status(){return this.result?.status}get data(){return this.result?.data}succeed(t){let e=this.result;super.succeed({...e,data:t,status:"SUCCESS"});}};i(ye,"A_ChannelRequest");var X=ye;var P=class P extends A_Component{constructor(){super();this._processing=false;this._cache=new Map;}get processing(){return this._processing}get initialize(){return this._initialized||(this._initialized=this.connect()),this._initialized}async onConnect(...e){}async onDisconnect(...e){}async onBeforeRequest(...e){}async onRequest(...e){}async onAfterRequest(...e){}async onError(...e){}async onSend(...e){}async connect(){await this.call("onConnect");}async disconnect(){await this.call("onDisconnect");}async request(e){await this.initialize,this._processing=true;let r=new A_Scope({name:`a-channel@scope:request:${A_IdentityHelper.generateTimeId()}`}),o=new X(e);try{return r.register(o),await this.call("onBeforeRequest",r),await this.call("onRequest",r),await this.call("onAfterRequest",r),this._processing=!1,o}catch(n){this._processing=false;let s=new M(n);throw o.fail(s),r.register(s),await this.call("onError",r),r.destroy(),s}}async send(e){await this.initialize,this._processing=true;let r=new A_Scope({name:`a-channel@scope:send:${A_IdentityHelper.generateTimeId()}`}),o=new l("send",e);try{r.inherit(A_Context.scope(this)),r.register(o),await this.call("onSend",r),this._processing=!1;}catch(n){this._processing=false;let s=new M(n);r.register(s),o.fail(s),await this.call("onError",r),r.destroy();}}async consume(){await this.initialize,this._processing=true;let e=new A_Scope({name:`a-channel@scope:consume:${A_IdentityHelper.generateTimeId()}`}),r=new l("consume",{});try{return e.inherit(A_Context.scope(this)),e.register(r),await this.call("onConsume",e),this._processing=!1,r}catch(o){this._processing=false;let n=new M(o);return r.fail(n),await this.call("onError",e),r}}};i(P,"A_Channel"),p([A_Feature.Extend({name:"onConnect"})],P.prototype,"onConnect",1),p([A_Feature.Extend({name:"onDisconnect"})],P.prototype,"onDisconnect",1),p([A_Feature.Extend({name:"onBeforeRequest"})],P.prototype,"onBeforeRequest",1),p([A_Feature.Extend({name:"onRequest"})],P.prototype,"onRequest",1),p([A_Feature.Extend({name:"onAfterRequest"})],P.prototype,"onAfterRequest",1),p([A_Feature.Extend({name:"onError"})],P.prototype,"onError",1),p([A_Feature.Extend({name:"onSend"})],P.prototype,"onSend",1);var Ae=P;var gt=(s=>(s.CREATED="CREATED",s.INITIALIZED="INITIALIZED",s.COMPILED="COMPILED",s.EXECUTING="EXECUTING",s.COMPLETED="COMPLETED",s.FAILED="FAILED",s))(gt||{}),ut=(o=>(o.CREATED_TO_INITIALIZED="created_initialized",o.INITIALIZED_TO_EXECUTING="initialized_executing",o.EXECUTING_TO_COMPLETED="executing_completed",o.EXECUTING_TO_FAILED="executing_failed",o))(ut||{}),yt=(a=>(a.onInit="onInit",a.onBeforeExecute="onBeforeExecute",a.onExecute="onExecute",a.onAfterExecute="onAfterExecute",a.onComplete="onComplete",a.onFail="onFail",a.onError="onError",a))(yt||{});var U=class U extends A_Error{};i(U,"A_CommandError"),U.CommandScopeBindingError="A-Command Scope Binding Error",U.ExecutionError="A-Command Execution Error",U.ResultProcessingError="A-Command Result Processing Error",U.CommandInterruptedError="A-Command Interrupted Error";var L=U;var J=class J extends A_Error{};i(J,"A_StateMachineError"),J.InitializationError="A-StateMachine Initialization Error",J.TransitionError="A-StateMachine Transition Error";var V=J;var At=(o=>(o.onError="onError",o.onInitialize="onInitialize",o.onBeforeTransition="onBeforeTransition",o.onAfterTransition="onAfterTransition",o))(At||{});var Se=class Se extends l{constructor(t){super("a-state-machine-transition",t),this._meta.set("from",t.from),this._meta.set("to",t.to);}get from(){return this._meta.get("from")}get to(){return this._meta.get("to")}};i(Se,"A_StateMachineTransition");var R=Se;var xt,Rt,vt,wt,z=class z extends A_Component{get ready(){return this._initialized||(this._initialized=this.call("onInitialize")),this._initialized}async[wt="onInitialize"](...t){}async[vt="onBeforeTransition"](...t){}async[Rt="onAfterTransition"](...t){}async[xt="onError"](...t){}async transition(t,e,r){await this.ready;let o=`${A_FormatterHelper.toCamelCase(String(t))}_${A_FormatterHelper.toCamelCase(String(e))}`,n=new R({from:String(t),to:String(e),props:r}),s=new A_Scope({name:`A-StateMachine-Transition-Scope-${o}`,fragments:[n]});try{return await this.call("onBeforeTransition",s),await this.call(o,s),await this.call("onAfterTransition",s),s.destroy(),n.result}catch(a){let d=new V({title:V.TransitionError,description:`An error occurred while transitioning to "${o}"`,originalError:a});throw s.register(d),await this.call("onError",s),s.destroy(),d}}};i(z,"A_StateMachine"),p([A_Feature.Extend()],z.prototype,wt,1),p([A_Feature.Extend()],z.prototype,vt,1),p([A_Feature.Extend()],z.prototype,Rt,1),p([A_Feature.Extend()],z.prototype,xt,1);var O=z;var So={},B=[];var xe=class xe extends A_Fragment{constructor(e){super({name:"A_Config"});this.VARIABLES=new Map;this.DEFAULT_ALLOWED_TO_READ_PROPERTIES=[...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,...B];this.config=A_CommonHelper.deepCloneAndMerge(e,{strict:false,defaults:{},variables:A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY}),this.CONFIG_PROPERTIES=this.config.variables?this.config.variables:[],this.config.variables.forEach(r=>{this.VARIABLES.set(A_FormatterHelper.toUpperSnakeCase(r),this.config.defaults[r]);});}get(e){if(this.CONFIG_PROPERTIES.includes(e)||this.DEFAULT_ALLOWED_TO_READ_PROPERTIES.includes(e)||!this.config.strict)return this.VARIABLES.get(A_FormatterHelper.toUpperSnakeCase(e));throw new Error("Property not exists or not allowed to read")}set(e,r){let o=Array.isArray(e)?e:typeof e=="string"?[{property:e,value:r}]:Object.keys(e).map(n=>({property:n,value:e[n]}));for(let{property:n,value:s}of o){let a=s||(this.config?.defaults?this.config.defaults[n]:void 0);this.VARIABLES.set(A_FormatterHelper.toUpperSnakeCase(n),a);}}};i(xe,"A_Config");var f=xe;var We=20,Oo="all",Qe={red:"31",yellow:"33",green:"32",blue:"34",cyan:"36",magenta:"35",gray:"90",brightBlue:"94",brightCyan:"96",brightMagenta:"95",darkGray:"30",lightGray:"37",indigo:"38;5;54",violet:"38;5;93",purple:"38;5;129",lavender:"38;5;183",skyBlue:"38;5;117",steelBlue:"38;5;67",slateBlue:"38;5;62",deepBlue:"38;5;18",lightBlue:"38;5;153",periwinkle:"38;5;111",cornflower:"38;5;69",powder:"38;5;152",charcoal:"38;5;236",silver:"38;5;250",smoke:"38;5;244",slate:"38;5;240"},et=["blue","cyan","magenta","gray","brightBlue","brightCyan","brightMagenta","darkGray","lightGray","indigo","violet","purple","lavender","skyBlue","steelBlue","slateBlue","deepBlue","lightBlue","periwinkle","cornflower","powder","charcoal","silver","smoke","slate"],N={RESET:"\x1B[0m",PREFIX:"\x1B[",SUFFIX:"m"},j={MINUTES_PAD:2,SECONDS_PAD:2,MILLISECONDS_PAD:3,SEPARATOR:":"},T={SCOPE_OPEN:"[",SCOPE_CLOSE:"]",TIME_OPEN:"|",TIME_CLOSE:"|",SEPARATOR:"-------------------------------",INDENT_BASE:3,PIPE:"| "},Z={LOG_LEVEL:"A_LOGGER_LEVEL",DEFAULT_SCOPE_LENGTH:"A_LOGGER_DEFAULT_SCOPE_LENGTH",DEFAULT_SCOPE_COLOR:"A_LOGGER_DEFAULT_SCOPE_COLOR",DEFAULT_LOG_COLOR:"A_LOGGER_DEFAULT_LOG_COLOR"};var v=class extends A_Component{constructor(e,r){super();this.scope=e;this.config=r;this.COLORS=Qe,this.STANDARD_SCOPE_LENGTH=r?.get(Z.DEFAULT_SCOPE_LENGTH)||20;let o=r?.get(Z.DEFAULT_SCOPE_COLOR),n=r?.get(Z.DEFAULT_LOG_COLOR);if(o||n)this.DEFAULT_SCOPE_COLOR=o||this.generateColorFromScopeName(this.scope.name),this.DEFAULT_LOG_COLOR=n||this.generateColorFromScopeName(this.scope.name);else {let s=this.generateComplementaryColorsFromScope(this.scope.name);this.DEFAULT_SCOPE_COLOR=s.scopeColor,this.DEFAULT_LOG_COLOR=s.logColor;}}simpleHash(e){let r=0;for(let o=0;o<e.length;o++){let n=e.charCodeAt(o);r=(r<<5)-r+n,r=r&r;}return Math.abs(r)}generateColorFromScopeName(e){let r=et,n=this.simpleHash(e)%r.length;return r[n]}generateComplementaryColorsFromScope(e){let r=[{scopeColor:"indigo",logColor:"lightBlue"},{scopeColor:"deepBlue",logColor:"cyan"},{scopeColor:"purple",logColor:"lavender"},{scopeColor:"steelBlue",logColor:"skyBlue"},{scopeColor:"slateBlue",logColor:"periwinkle"},{scopeColor:"charcoal",logColor:"silver"},{scopeColor:"violet",logColor:"brightMagenta"},{scopeColor:"darkGray",logColor:"lightGray"},{scopeColor:"cornflower",logColor:"powder"},{scopeColor:"slate",logColor:"smoke"}],n=this.simpleHash(e)%r.length;return r[n]}get scopeLength(){return Math.max(this.scope.name.length,this.STANDARD_SCOPE_LENGTH)}get formattedScope(){let e=this.scope.name,r=this.STANDARD_SCOPE_LENGTH;if(e.length>=r)return e.substring(0,r);let o=r-e.length,n=Math.floor(o/2),s=o-n;return " ".repeat(n)+e+" ".repeat(s)}compile(e,...r){let o=this.getTime(),n=" ".repeat(this.scopeLength+3),s=r.length>1;return [`${N.PREFIX}${this.COLORS[this.DEFAULT_SCOPE_COLOR]}${N.SUFFIX}${T.SCOPE_OPEN}${this.formattedScope}${T.SCOPE_CLOSE}${N.RESET} ${N.PREFIX}${this.COLORS[e]}${N.SUFFIX}${T.TIME_OPEN}${o}${T.TIME_CLOSE}`,s?`
|
|
2
|
+
${n}${T.TIME_OPEN}${T.SEPARATOR}`:"",...r.map((a,d)=>{let b=d>0||s;switch(true){case a instanceof A_Error:return this.compile_A_Error(a);case a instanceof Error:return this.compile_Error(a);case(typeof a=="object"&&a!==null):return this.formatObject(a,b,n);default:return this.formatString(String(a),b,n)}}),s?`
|
|
3
|
+
${n}${T.TIME_OPEN}${T.SEPARATOR}${N.RESET}`:N.RESET]}formatObject(e,r,o){let n;try{n=JSON.stringify(e,null,2);}catch{let d=new WeakSet;n=JSON.stringify(e,(b,m)=>{if(typeof m=="object"&&m!==null){if(d.has(m))return "[Circular Reference]";d.add(m);}return m},2);}let s=n.replace(/\n/g,`
|
|
4
|
+
${o}${T.PIPE}`);return r?`
|
|
5
|
+
${o}${T.PIPE}`+s:s}formatString(e,r,o){return ((r?`
|
|
6
|
+
`:"")+e).replace(/\n/g,`
|
|
7
|
+
${o}${T.PIPE}`)}shouldLog(e){switch(this.config?.get(Z.LOG_LEVEL)||"info"){case "debug":return true;case "info":return e==="info"||e==="warning"||e==="error";case "warn":return e==="warning"||e==="error";case "error":return e==="error";case "all":return true;default:return false}}debug(e,...r){this.shouldLog("debug")&&(typeof e=="string"&&this.COLORS[e]?console.log(...this.compile(e,...r)):console.log(...this.compile(this.DEFAULT_LOG_COLOR,e,...r)));}info(e,...r){this.shouldLog("info")&&(typeof e=="string"&&this.COLORS[e]?console.log(...this.compile(e,...r)):console.log(...this.compile(this.DEFAULT_LOG_COLOR,e,...r)));}log(e,...r){this.info(e,...r);}warning(...e){this.shouldLog("warning")&&console.log(...this.compile("yellow",...e));}error(...e){this.shouldLog("error")&&console.log(...this.compile("red",...e));}log_A_Error(e){let r=this.getTime(),o=" ".repeat(this.scopeLength+3);console.log(`\x1B[31m[${this.formattedScope}] |${r}| ERROR ${e.code}
|
|
8
|
+
${o}| ${e.message}
|
|
9
|
+
${o}| ${e.description}
|
|
10
|
+
${o}|-------------------------------
|
|
11
|
+
${o}| ${e.stack?.split(`
|
|
12
|
+
`).map((n,s)=>s===0?n:`${o}| ${n}`).join(`
|
|
13
|
+
`)||"No stack trace"}
|
|
14
|
+
${o}|-------------------------------
|
|
15
|
+
\x1B[0m`+(e.originalError?`\x1B[31m${o}| Wrapped From ${e.originalError.message}
|
|
16
|
+
${o}|-------------------------------
|
|
17
|
+
${o}| ${e.originalError.stack?.split(`
|
|
18
|
+
`).map((n,s)=>s===0?n:`${o}| ${n}`).join(`
|
|
19
|
+
`)||"No stack trace"}
|
|
20
|
+
${o}|-------------------------------
|
|
21
|
+
\x1B[0m`:"")+(e.link?`\x1B[31m${o}| Read in docs: ${e.link}
|
|
22
|
+
${o}|-------------------------------
|
|
23
|
+
\x1B[0m`:""));}compile_A_Error(e){let r=" ".repeat(this.scopeLength+3);return `
|
|
24
|
+
${r}|-------------------------------
|
|
25
|
+
${r}| Error: | ${e.code}
|
|
26
|
+
${r}|-------------------------------
|
|
27
|
+
${r}|${" ".repeat(10)}| ${e.message}
|
|
28
|
+
${r}|${" ".repeat(10)}| ${e.description}
|
|
29
|
+
${r}|-------------------------------
|
|
30
|
+
${r}| ${e.stack?.split(`
|
|
31
|
+
`).map((o,n)=>n===0?o:`${r}| ${o}`).join(`
|
|
32
|
+
`)||"No stack trace"}
|
|
33
|
+
${r}|-------------------------------`+(e.originalError?`${r}| Wrapped From ${e.originalError.message}
|
|
34
|
+
${r}|-------------------------------
|
|
35
|
+
${r}| ${e.originalError.stack?.split(`
|
|
36
|
+
`).map((o,n)=>n===0?o:`${r}| ${o}`).join(`
|
|
37
|
+
`)||"No stack trace"}
|
|
38
|
+
${r}|-------------------------------`:"")+(e.link?`${r}| Read in docs: ${e.link}
|
|
39
|
+
${r}|-------------------------------`:"")}compile_Error(e){let r=" ".repeat(this.scopeLength+3);return JSON.stringify({name:e.name,message:e.message,stack:e.stack?.split(`
|
|
40
|
+
`).map((o,n)=>n===0?o:`${r}| ${o}`).join(`
|
|
41
|
+
`)},null,2).replace(/\n/g,`
|
|
42
|
+
${r}| `).replace(/\\n/g,`
|
|
43
|
+
`)}getTime(){let e=new Date,r=String(e.getMinutes()).padStart(j.MINUTES_PAD,"0"),o=String(e.getSeconds()).padStart(j.SECONDS_PAD,"0"),n=String(e.getMilliseconds()).padStart(j.MILLISECONDS_PAD,"0");return `${r}${j.SEPARATOR}${o}${j.SEPARATOR}${n}`}};i(v,"A_Logger"),v=p([c(0,A_Inject(A_Scope)),c(1,A_Inject(f))],v);var Dt,Gt,$t,kt,Mt,Ft,Ut,zt,Bt,Yt,Vt,u=class u extends A_Entity{constructor(e){super(e);this._listeners=new Map;}static get code(){return super.entity}get duration(){return this._endTime&&this._startTime?this._endTime.getTime()-this._startTime.getTime():this._startTime?new Date().getTime()-this._startTime.getTime():void 0}get idleTime(){return this._startTime&&this._createdAt?this._startTime.getTime()-this._createdAt.getTime():void 0}get scope(){return this._executionScope}get code(){return this.constructor.code}get status(){return this._status}get createdAt(){return this._createdAt}get startedAt(){return this._startTime}get endedAt(){return this._endTime}get result(){return this._result}get error(){return this._error}get params(){return this._params}get isProcessed(){return this._status==="COMPLETED"||this._status==="FAILED"}async[Vt="onBeforeTransition"](e,r,...o){this.checkScopeInheritance(),r?.debug("yellow",`Command ${this.aseid.toString()} transitioning from ${e.from} to ${e.to}`);}async[Yt="created_initialized"](e,...r){this._status==="CREATED"&&(this._createdAt=new Date,this._status="INITIALIZED",this.emit("onInit"));}async[Bt="initialized_executing"](e,...r){this._status!=="INITIALIZED"&&this._status!=="CREATED"||(this._startTime=new Date,this._status="EXECUTING",this.emit("onExecute"));}async[zt="executing_completed"](e,...r){this._endTime=new Date,this._status="COMPLETED",this.emit("onComplete");}async[Ut="executing_failed"](e,r,...o){this._endTime=new Date,this._status="FAILED",this.emit("onFail");}async[Ft="onInit"](e,...r){await e.transition("CREATED","INITIALIZED");}async[Mt="onBeforeExecute"](e,...r){await e.transition("INITIALIZED","EXECUTING");}async[kt="onExecute"](...e){}async[$t="onAfterExecute"](...e){}async[Gt="onComplete"](e,...r){await e.transition("EXECUTING","COMPLETED");}async[Dt="onFail"](e,r,...o){await e.transition("EXECUTING","FAILED");}async init(){await this.call("onInit",this.scope);}async execute(){if(!this.isProcessed)try{this.checkScopeInheritance();let e=new l("execute-command");this.scope.register(e),await new Promise(async(r,o)=>{try{let n=new A_Feature({name:"onBeforeExecute",component:this,scope:this.scope}),s=new A_Feature({name:"onExecute",component:this,scope:this.scope}),a=new A_Feature({name:"onAfterExecute",component:this,scope:this.scope});this.on("onComplete",()=>{n.interrupt(),s.interrupt(),a.interrupt(),r();}),await n.process(this.scope),await s.process(this.scope),await a.process(this.scope),this._origin==="invoked"&&await this.complete(),r();}catch(n){o(n);}});}catch(e){let r=e instanceof A_Error?e:new L({title:L.ExecutionError,description:`An error occurred while executing command "${this.aseid.toString()}".`,originalError:e});await this.fail(r);}}async complete(e){this.isProcessed||(this._status="COMPLETED",this._result=e,await this.call("onComplete",this.scope),this.scope.destroy());}async fail(e){this.isProcessed||(this._status="FAILED",e&&(this._error=e,this.scope.register(e)),await this.call("onFail",this.scope),this.scope.destroy());}on(e,r){this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r);}off(e,r){this._listeners.get(e)?.delete(r);}emit(e){this._listeners.get(e)?.forEach(async r=>{r(this);});}fromNew(e){super.fromNew(e),this._origin="invoked",this._executionScope=new A_Scope({name:`A-Command-Execution-Scope-${this.aseid.toString()}`,components:[O]}),this._createdAt=new Date,this._params=e,this._status="CREATED";}fromJSON(e){super.fromJSON(e),this._origin="serialized",this._executionScope=new A_Scope({name:`A-Command-Execution-Scope-${this.aseid.toString()}`,components:[O]}),e.createdAt&&(this._createdAt=new Date(e.createdAt)),e.startedAt&&(this._startTime=new Date(e.startedAt)),e.endedAt&&(this._endTime=new Date(e.endedAt)),this._params=e.params,this._status=e.status,e.error&&(this._error=new L(e.error)),e.result&&(this._result=e.result);}toJSON(){return {...super.toJSON(),code:this.code,status:this._status,params:this._params,createdAt:this._createdAt.toISOString(),startedAt:this._startTime?this._startTime.toISOString():void 0,endedAt:this._endTime?this._endTime.toISOString():void 0,duration:this.duration,idleTime:this.idleTime,result:this.result,error:this.error?this.error.toJSON():void 0}}checkScopeInheritance(){let e;try{e=A_Context.scope(this);}catch(r){throw new L({title:L.CommandScopeBindingError,description:`Command ${this.aseid.toString()} is not bound to any context scope. Ensure the command is properly registered within a context before execution.`,originalError:r})}this.scope.isInheritedFrom(A_Context.scope(this))||this.scope.inherit(A_Context.scope(this));}};i(u,"A_Command"),p([A_Feature.Extend(),c(0,A_Inject(R)),c(1,A_Inject(v))],u.prototype,Vt,1),p([A_Feature.Extend(),c(0,A_Inject(R))],u.prototype,Yt,1),p([A_Feature.Extend(),c(0,A_Inject(R))],u.prototype,Bt,1),p([A_Feature.Extend(),c(0,A_Inject(R))],u.prototype,zt,1),p([A_Feature.Extend(),c(0,A_Inject(R)),c(1,A_Inject(A_Error))],u.prototype,Ut,1),p([A_Feature.Extend(),c(0,A_Inject(O))],u.prototype,Ft,1),p([A_Feature.Extend({after:/.*/}),c(0,A_Dependency.Required()),c(0,A_Inject(O))],u.prototype,Mt,1),p([A_Feature.Extend()],u.prototype,kt,1),p([A_Feature.Extend()],u.prototype,$t,1),p([A_Feature.Extend({after:/.*/}),c(0,A_Inject(O))],u.prototype,Gt,1),p([A_Feature.Extend({after:/.*/}),c(0,A_Dependency.Required()),c(0,A_Inject(O)),c(1,A_Inject(l))],u.prototype,Dt,1);var ve=u;var we=class we{constructor(t){this.logger=t;this._initialized=false;}get isInitialized(){return this._initialized}async get(){return this._initialized||await this.init(),this._fs}async init(){try{A_Context.environment==="server"?await this.initServer():this.initBrowser(),this._initialized=!0;}catch{this.initBrowser(),this._initialized=true;}}async initServer(){this._fs=await import('fs');}initBrowser(){this._fs={readFileSync:i((t,e)=>(this.logger.warning("fs.readFileSync not available in browser environment"),""),"readFileSync"),existsSync:i(t=>(this.logger.warning("fs.existsSync not available in browser environment"),false),"existsSync"),createReadStream:i(t=>(this.logger.warning("fs.createReadStream not available in browser environment"),null),"createReadStream")};}};i(we,"A_FSPolyfillClass");var ie=we;var Pe=class Pe{constructor(t){this.logger=t;this._initialized=false;}get isInitialized(){return this._initialized}async get(t){return this._initialized||(this._fsPolyfill=t,await this.init()),this._crypto}async init(){try{A_Context.environment==="server"?await this.initServer():this.initBrowser(),this._initialized=!0;}catch{this.initBrowser(),this._initialized=true;}}async initServer(){let t=await import('crypto');this._crypto={createTextHash:i((e,r="sha384")=>Promise.resolve(`${r}-${t.createHash(r).update(e).digest("base64")}`),"createTextHash"),createFileHash:i((e,r="sha384")=>new Promise(async(o,n)=>{try{if(!this._fsPolyfill)throw new Error("FS polyfill is required for file hashing");let s=t.createHash(r),a=this._fsPolyfill.createReadStream(e);a.on("data",d=>s.update(d)),a.on("end",()=>o(`${r}-${s.digest("base64")}`)),a.on("error",d=>n(d));}catch(s){n(s);}}),"createFileHash")};}initBrowser(){this._crypto={createFileHash:i(()=>(this.logger.warning("File hash not available in browser environment"),Promise.resolve("")),"createFileHash"),createTextHash:i((t,e="SHA-384")=>new Promise(async(r,o)=>{try{if(!crypto.subtle)throw new Error("SubtleCrypto not available");let s=new TextEncoder().encode(t),a=await crypto.subtle.digest(e,s),d=Array.from(new Uint8Array(a)),b=btoa(String.fromCharCode(...d));r(`${e}-${b}`);}catch(n){o(n);}}),"createTextHash")};}};i(Pe,"A_CryptoPolyfillClass");var ne=Pe;var Oe=class Oe{constructor(t){this.logger=t;this._initialized=false;}get isInitialized(){return this._initialized}async get(){return this._initialized||await this.init(),this._http}async init(){try{A_Context.environment==="server"?await this.initServer():this.initBrowser(),this._initialized=!0;}catch{this.initBrowser(),this._initialized=true;}}async initServer(){let t=await import('http');this._http={request:t.request,get:t.get,createServer:t.createServer};}initBrowser(){this._http={request:i((t,e)=>(this.logger.warning("http.request not available in browser/test environment, use fetch instead"),this.createMockRequest(t,e,false)),"request"),get:i((t,e)=>(this.logger.warning("http.get not available in browser/test environment, use fetch instead"),this.createMockRequest(typeof t=="string"?{hostname:t}:t,e,false)),"get"),createServer:i(()=>(this.logger.error("http.createServer not available in browser/test environment"),null),"createServer")};}createMockRequest(t,e,r=false){return {end:i(()=>{if(e){let n={statusCode:200,headers:{},on:i((s,a)=>{s==="data"?setTimeout(()=>a("mock data"),0):s==="end"&&setTimeout(()=>a(),0);},"on"),pipe:i(s=>{s.write&&s.write("mock data"),s.end&&s.end();},"pipe")};setTimeout(()=>e(n),0);}},"end"),write:i(n=>{},"write"),on:i((n,s)=>{},"on")}}};i(Oe,"A_HttpPolyfillClass");var se=Oe;var Le=class Le{constructor(t){this.logger=t;this._initialized=false;}get isInitialized(){return this._initialized}async get(){return this._initialized||await this.init(),this._https}async init(){try{A_Context.environment==="server"?await this.initServer():this.initBrowser(),this._initialized=!0;}catch{this.initBrowser(),this._initialized=true;}}async initServer(){let t=await import('https');this._https={request:t.request,get:t.get,createServer:t.createServer};}initBrowser(){this._https={request:i((t,e)=>(this.logger.warning("https.request not available in browser/test environment, use fetch instead"),this.createMockRequest(t,e,true)),"request"),get:i((t,e)=>(this.logger.warning("https.get not available in browser/test environment, use fetch instead"),this.createMockRequest(typeof t=="string"?{hostname:t}:t,e,true)),"get"),createServer:i(()=>(this.logger.error("https.createServer not available in browser/test environment"),null),"createServer")};}createMockRequest(t,e,r=true){return {end:i(()=>{if(e){let n={statusCode:200,headers:{},on:i((s,a)=>{s==="data"?setTimeout(()=>a("mock data"),0):s==="end"&&setTimeout(()=>a(),0);},"on"),pipe:i(s=>{s.write&&s.write("mock data"),s.end&&s.end();},"pipe")};setTimeout(()=>e(n),0);}},"end"),write:i(n=>{},"write"),on:i((n,s)=>{},"on")}}};i(Le,"A_HttpsPolyfillClass");var ae=Le;var Ie=class Ie{constructor(t){this.logger=t;this._initialized=false;}get isInitialized(){return this._initialized}async get(){return this._initialized||await this.init(),this._path}async init(){try{A_Context.environment==="server"?await this.initServer():this.initBrowser(),this._initialized=!0;}catch{this.initBrowser(),this._initialized=true;}}async initServer(){this._path=await import('path');}initBrowser(){this._path={join:i((...t)=>t.join("/").replace(/\/+/g,"/"),"join"),resolve:i((...t)=>{let e="";for(let r of t)r.startsWith("/")?e=r:e=this._path.join(e,r);return e||"/"},"resolve"),dirname:i(t=>t.split("/").slice(0,-1).join("/")||"/","dirname"),basename:i((t,e)=>{let r=t.split("/").pop()||"";return e&&r.endsWith(e)?r.slice(0,-e.length):r},"basename"),extname:i(t=>{let e=t.split(".");return e.length>1?"."+e.pop():""},"extname"),relative:i((t,e)=>e.replace(t,"").replace(/^\//,""),"relative"),normalize:i(t=>t.replace(/\/+/g,"/").replace(/\/$/,"")||"/","normalize"),isAbsolute:i(t=>t.startsWith("/")||/^[a-zA-Z]:/.test(t),"isAbsolute"),parse:i(t=>{let e=this._path.extname(t),r=this._path.basename(t),o=this._path.basename(t,e);return {root:"/",dir:this._path.dirname(t),base:r,ext:e,name:o}},"parse"),format:i(t=>this._path.join(t.dir||"",t.base||""),"format"),sep:"/",delimiter:":"};}};i(Ie,"A_PathPolyfillClass");var ce=Ie;var be=class be{constructor(t){this.logger=t;this._initialized=false;}get isInitialized(){return this._initialized}async get(){return this._initialized||await this.init(),this._url}async init(){try{A_Context.environment==="server"?await this.initServer():this.initBrowser(),this._initialized=!0;}catch{this.initBrowser(),this._initialized=true;}}async initServer(){let t=await import('url');this._url={parse:t.parse,format:t.format,resolve:t.resolve,URL:t.URL||globalThis.URL,URLSearchParams:t.URLSearchParams||globalThis.URLSearchParams};}initBrowser(){this._url={parse:i(t=>{try{let e=new URL(t);return {protocol:e.protocol,hostname:e.hostname,port:e.port,pathname:e.pathname,search:e.search,hash:e.hash,host:e.host,href:e.href}}catch{return {}}},"parse"),format:i(t=>{try{return new URL("",t.href||`${t.protocol}//${t.host}${t.pathname}${t.search}${t.hash}`).href}catch{return ""}},"format"),resolve:i((t,e)=>{try{return new URL(e,t).href}catch{return e}},"resolve"),URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams};}};i(be,"A_UrlPolyfillClass");var pe=be;var Ne=class Ne{constructor(t){this.logger=t;this._initialized=false;}get isInitialized(){return this._initialized}async get(){return this._initialized||await this.init(),this._buffer}async init(){try{A_Context.environment==="server"?await this.initServer():this.initBrowser(),this._initialized=!0;}catch{this.initBrowser(),this._initialized=true;}}async initServer(){let t=await import('buffer');this._buffer={from:t.Buffer.from,alloc:t.Buffer.alloc,allocUnsafe:t.Buffer.allocUnsafe,isBuffer:t.Buffer.isBuffer,concat:t.Buffer.concat};}initBrowser(){this._buffer={from:i((t,e)=>typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t),"from"),alloc:i((t,e)=>{let r=new Uint8Array(t);return e!==void 0&&r.fill(e),r},"alloc"),allocUnsafe:i(t=>new Uint8Array(t),"allocUnsafe"),isBuffer:i(t=>t instanceof Uint8Array||t instanceof ArrayBuffer,"isBuffer"),concat:i((t,e)=>{let r=e||t.reduce((s,a)=>s+a.length,0),o=new Uint8Array(r),n=0;for(let s of t)o.set(s,n),n+=s.length;return o},"concat")};}};i(Ne,"A_BufferPolyfillClass");var le=Ne;var De=class De{constructor(t){this.logger=t;this._initialized=false;}get isInitialized(){return this._initialized}async get(){return this._initialized||await this.init(),this._process}async init(){try{A_Context.environment==="server"?this.initServer():this.initBrowser(),this._initialized=!0;}catch{this.initBrowser(),this._initialized=true;}}initServer(){this._process={env:process.env,argv:process.argv,platform:process.platform,version:process.version,versions:process.versions,cwd:process.cwd,exit:process.exit,nextTick:process.nextTick};}initBrowser(){this._process={env:{NODE_ENV:"browser",...globalThis.process?.env||{}},argv:["browser"],platform:"browser",version:"browser",versions:{node:"browser"},cwd:i(()=>"/","cwd"),exit:i(t=>{throw this.logger.warning("process.exit not available in browser"),new Error(`Process exit with code ${t}`)},"exit"),nextTick:i((t,...e)=>{setTimeout(()=>t(...e),0);},"nextTick")};}};i(De,"A_ProcessPolyfillClass");var _e=De;var h=class extends A_Component{constructor(e){super();this.logger=e;this._initializing=null;}get ready(){return this._initialized||(this._initialized=this._loadInternal()),this._initialized}async load(){await this.ready;}async attachToWindow(){A_Context.environment==="browser"&&(globalThis.A_Polyfill=this,globalThis.process={env:{NODE_ENV:"production"},cwd:i(()=>"/","cwd")},globalThis.__dirname="/");}async _loadInternal(){this._fsPolyfill=new ie(this.logger),this._cryptoPolyfill=new ne(this.logger),this._httpPolyfill=new se(this.logger),this._httpsPolyfill=new ae(this.logger),this._pathPolyfill=new ce(this.logger),this._urlPolyfill=new pe(this.logger),this._bufferPolyfill=new le(this.logger),this._processPolyfill=new _e(this.logger),await this._fsPolyfill.get(),await this._cryptoPolyfill.get(await this._fsPolyfill.get()),await this._httpPolyfill.get(),await this._httpsPolyfill.get(),await this._pathPolyfill.get(),await this._urlPolyfill.get(),await this._bufferPolyfill.get(),await this._processPolyfill.get();}async fs(){return await this.ready,await this._fsPolyfill.get()}async crypto(){return await this.ready,await this._cryptoPolyfill.get()}async http(){return await this.ready,await this._httpPolyfill.get()}async https(){return await this.ready,await this._httpsPolyfill.get()}async path(){return await this.ready,await this._pathPolyfill.get()}async url(){return await this.ready,await this._urlPolyfill.get()}async buffer(){return await this.ready,await this._bufferPolyfill.get()}async process(){return await this.ready,await this._processPolyfill.get()}};i(h,"A_Polyfill"),p([A_Concept.Load()],h.prototype,"load",1),p([A_Concept.Load()],h.prototype,"attachToWindow",1),h=p([c(0,A_Inject(v))],h);var me=class me extends A_Error{};i(me,"A_ConfigError"),me.InitializationError="A-Config Initialization Error";var D=me;var y=class extends A_Component{constructor(e){super();this.polyfill=e;}async attachContext(e,r,o){o||(o=new f({variables:[...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,...B],defaults:{}}),e.scope.register(o));let n=await this.getProjectRoot();o.set("A_CONCEPT_ROOT_FOLDER",n);}async initialize(e){let r=await this.read([...e.CONFIG_PROPERTIES,...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,...B]);e.set(r);}resolve(e){return e}async read(e=[]){return {}}async getProjectRoot(e=__dirname){return process.cwd()}};i(y,"ConfigReader"),p([A_Concept.Load(),c(0,A_Inject(A_Container)),c(1,A_Inject(A_Feature)),c(2,A_Inject(f))],y.prototype,"attachContext",1),p([A_Concept.Load(),c(0,A_Inject(f))],y.prototype,"initialize",1),y=p([c(0,A_Inject(h))],y);var Ge=class Ge extends y{constructor(){super(...arguments);this.FileData=new Map;}getConfigurationProperty_File_Alias(e){return A_FormatterHelper.toCamelCase(e)}resolve(e){return this.FileData.get(this.getConfigurationProperty_File_Alias(e))}async read(e){let r=await this.polyfill.fs();try{let o=r.readFileSync(`${A_Context.concept}.conf.json`,"utf8"),n=JSON.parse(o);return this.FileData=new Map(Object.entries(n)),n}catch{return {}}}};i(Ge,"FileConfigReader");var Q=Ge;var de=class de extends y{async readEnvFile(t,e,r){let o=await e.fs();o.existsSync(".env")&&o.readFileSync(`${t.get("A_CONCEPT_ROOT_FOLDER")}/.env`,"utf-8").split(`
|
|
44
|
+
`).forEach(n=>{let[s,a]=n.split("=");s&&a&&(process.env[s.trim()]=a.trim());});}getConfigurationProperty_ENV_Alias(t){return A_FormatterHelper.toUpperSnakeCase(t)}resolve(t){return process.env[this.getConfigurationProperty_ENV_Alias(t)]}async read(t=[]){let e=[...t,...Object.keys(process.env)],r={};return e.forEach(o=>{r[o]=this.resolve(o);}),r}};i(de,"ENVConfigReader"),p([A_Concept.Load({before:["ENVConfigReader.initialize"]}),c(0,A_Inject(f)),c(1,A_Inject(h)),c(2,A_Inject(A_Feature))],de.prototype,"readEnvFile",1);var q=de;var he=class he extends A_Container{async prepare(t){if(!this.scope.has(f)){let r=new f({variables:[...A_CONSTANTS__DEFAULT_ENV_VARIABLES_ARRAY,...B],defaults:{}});this.scope.register(r);}let e=await t.fs();try{switch(!0){case(A_Context.environment==="server"&&!!e.existsSync(`${A_Context.concept}.conf.json`)):this.reader=this.scope.resolve(Q);break;case(A_Context.environment==="server"&&!e.existsSync(`${A_Context.concept}.conf.json`)):this.reader=this.scope.resolve(q);break;case A_Context.environment==="browser":this.reader=this.scope.resolve(q);break;default:throw new D(D.InitializationError,`Environment ${A_Context.environment} is not supported`)}}catch(r){if(r instanceof A_ScopeError)throw new D({title:D.InitializationError,description:`Failed to initialize A_ConfigLoader. Reader not found for environment ${A_Context.environment}`,originalError:r})}}};i(he,"A_ConfigLoader"),p([A_Concept.Load({before:/.*/}),c(0,A_Inject(h))],he.prototype,"prepare",1);var ke=he;var gr=(k=>k)(gr||{});var fe={A_LOGGER_LEVEL:"A_LOGGER_LEVEL",A_LOGGER_DEFAULT_SCOPE_LENGTH:"A_LOGGER_DEFAULT_SCOPE_LENGTH",A_LOGGER_DEFAULT_SCOPE_COLOR:"A_LOGGER_DEFAULT_SCOPE_COLOR",A_LOGGER_DEFAULT_LOG_COLOR:"A_LOGGER_DEFAULT_LOG_COLOR"},an=[fe.A_LOGGER_LEVEL,fe.A_LOGGER_DEFAULT_SCOPE_LENGTH,fe.A_LOGGER_DEFAULT_SCOPE_COLOR,fe.A_LOGGER_DEFAULT_LOG_COLOR];var ge=class ge extends A_Error{};i(ge,"A_ManifestError"),ge.ManifestInitializationError="A-Manifest Initialization Error";var G=ge;var Me=class Me{constructor(t,e,r,o=false){this.manifest=t;this.component=e;this.method=r;this.checkExclusion=o;}for(t){let e=this.manifest.internal_checkAccess({component:this.component,method:this.method,target:t});return this.checkExclusion?!e:e}};i(Me,"A_ManifestChecker");var H=Me;var Ue=class Ue extends A_Fragment{constructor(e=[]){super({name:"A-Manifest"});this.rules=[];this.prepare(e);}prepare(e){if(!A_TypeGuards.isArray(e))throw new G(G.ManifestInitializationError,"A-Manifest configuration should be an array of configurations");for(let r of e)this.processConfigItem(r);}processConfigItem(e){if(!A_TypeGuards.isComponentConstructor(e.component))throw new G(G.ManifestInitializationError,"A-Manifest configuration item should be a A-Component constructor");let r=this.constructorToRegex(e.component);if(e.apply||e.exclude){let o=/.*/;this.rules.push({componentRegex:r,methodRegex:o,applyRegex:e.apply?this.allowedComponentsToRegex(e.apply):void 0,excludeRegex:e.exclude?this.allowedComponentsToRegex(e.exclude):void 0});}if(e.methods&&e.methods.length>0)for(let o of e.methods){let n=this.methodToRegex(o.method);this.rules.push({componentRegex:r,methodRegex:n,applyRegex:o.apply?this.allowedComponentsToRegex(o.apply):void 0,excludeRegex:o.exclude?this.allowedComponentsToRegex(o.exclude):void 0});}}constructorToRegex(e){return new RegExp(`^${this.escapeRegex(e.name)}$`)}methodToRegex(e){return e instanceof RegExp?e:new RegExp(`^${this.escapeRegex(e)}$`)}allowedComponentsToRegex(e){if(e instanceof RegExp)return e;let r=e.map(o=>this.escapeRegex(o.name));return new RegExp(`^(${r.join("|")})$`)}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}configItemToRegexp(e){return this.constructorToRegex(e)}ID(e,r){return `${e.name}.${r}`}isAllowed(e,r){let o=typeof e=="function"?e:e.constructor;return new H(this,o,r)}internal_checkAccess(e){let r=e.component.name,o=e.method,n=e.target.name,s=this.rules.filter(a=>a.componentRegex.test(r)&&a.methodRegex.test(o)).sort((a,d)=>{let b=a.methodRegex.source===".*",m=d.methodRegex.source===".*";return b&&!m?1:!b&&m?-1:0});if(s.length===0)return true;for(let a of s){if(a.excludeRegex&&a.excludeRegex.test(n))return false;if(a.applyRegex)return a.applyRegex.test(n)}return true}isExcluded(e,r){let o=typeof e=="function"?e:e.constructor;return new H(this,o,r,true)}};i(Ue,"A_Manifest");var Fe=Ue;var Er=(m=>(m.onInit="onInit",m.onDestroy="onDestroy",m.onExpire="onExpire",m.onError="onError",m.onSerialize="onSerialize",m.onSet="onSet",m.onGet="onGet",m.onDrop="onDrop",m.onClear="onClear",m.onHas="onHas",m))(Er||{});var ze=class ze extends A_Fragment{set(t,e){super.set(t,e);}get(t){return super.get(t)}};i(ze,"A_MemoryContext");var S=ze;var w=class w extends A_Error{};i(w,"A_MemoryError"),w.MemoryInitializationError="Memory initialization error",w.MemoryDestructionError="Memory destruction error",w.MemoryGetError="Memory GET operation failed",w.MemorySetError="Memory SET operation failed",w.MemoryDropError="Memory DROP operation failed",w.MemoryClearError="Memory CLEAR operation failed",w.MemoryHasError="Memory HAS operation failed",w.MemorySerializeError="Memory toJSON operation failed";var _=w;var Cr,xr,Rr,vr,wr,Pr,Or,Lr,Ir,x=class x extends A_Component{get ready(){return this._ready||(this._ready=this.init()),this._ready}async[Ir="onError"](...t){}async[Lr="onExpire"](...t){}async[Or="onInit"](t,...e){t||(t=new S,A_Context.scope(this).register(t));}async[Pr="onDestroy"](t,...e){t.clear();}async[wr="onGet"](t,e,...r){t.succeed(e.get(t.params.key));}async[vr="onHas"](t,e,...r){t.succeed(e.has(t.params.key));}async[Rr="onSet"](t,e,...r){e.set(t.params.key,t.params.value);}async[xr="onDrop"](t,e,...r){e.drop(t.params.key);}async[Cr="onClear"](t,e,...r){e.clear();}async init(){if(this._ready)return this._ready;let t=new A_Scope({name:"A-Memory-Init-Scope"}).inherit(A_Context.scope(this));try{await this.call("onInit",t);}catch(e){let r=new _({title:_.MemoryInitializationError,description:"An error occurred during memory initialization",originalError:e});throw t.register(r),await this.call("onError",t),t.destroy(),r}}async destroy(){let t=new A_Scope({name:"A-Memory-Destroy-Scope"}).inherit(A_Context.scope(this));try{this._ready=void 0,await this.call("onDestroy",t);}catch(e){let r=new _({title:_.MemoryDestructionError,description:"An error occurred during memory destruction",originalError:e});throw t.register(r),await this.call("onError",t),t.destroy(),r}}async get(t){let e=new l("get",{key:t}),r=new A_Scope({name:"A-Memory-Get-Operation-Scope",fragments:[e]});try{return await this.call("onGet",r),r.destroy(),e.result}catch(o){let n=new _({title:_.MemoryGetError,description:`An error occurred while getting the value for key "${String(t)}"`,originalError:o});throw r.register(n),await this.call("onError",r),r.destroy(),n}}async has(t){let e=new l("has",{key:t}),r=new A_Scope({name:"A-Memory-Has-Operation-Scope",fragments:[e]});try{return await this.call("onHas",r),r.destroy(),e.result}catch(o){let n=new _({title:_.MemoryHasError,description:`An error occurred while checking existence for key "${String(t)}"`,originalError:o});throw r.register(n),await this.call("onError",r),r.destroy(),n}}async set(t,e){let r=new l("set",{key:t,value:e}),o=new A_Scope({name:"A-Memory-Set-Operation-Scope",fragments:[r]});try{await this.call("onSet",o);}catch(n){let s=new _({title:_.MemorySetError,description:`An error occurred while setting the value for key "${String(t)}"`,originalError:n});throw o.register(s),await this.call("onError",o),o.destroy(),s}}async drop(t){let e=new l("drop",{key:t}),r=new A_Scope({name:"A-Memory-Drop-Operation-Scope",fragments:[e]});try{await this.call("onDrop",r);}catch(o){let n=new _({title:_.MemoryDropError,description:`An error occurred while dropping the value for key "${String(t)}"`,originalError:o});throw r.register(n),await this.call("onError",r),r.destroy(),n}}async clear(){let t=new l("clear"),e=new A_Scope({name:"A-Memory-Clear-Operation-Scope",fragments:[t]});try{await this.call("onClear",e);}catch(r){let o=new _({title:_.MemoryClearError,description:"An error occurred while clearing the memory",originalError:r});throw e.register(o),await this.call("onError",e),e.destroy(),o}}async toJSON(){let t=new l("serialize"),e=new A_Scope({name:"A-Memory-Serialize-Operation-Scope",fragments:[t]});try{return await this.call("onSerialize",e),t.result}catch(r){let o=new _({title:_.MemorySerializeError,description:"An error occurred while serializing the memory",originalError:r});throw e.register(o),await this.call("onError",e),e.destroy(),o}}};i(x,"A_Memory"),p([A_Feature.Extend()],x.prototype,Ir,1),p([A_Feature.Extend()],x.prototype,Lr,1),p([A_Feature.Extend(),c(0,A_Inject(S))],x.prototype,Or,1),p([A_Feature.Extend(),c(0,A_Inject(S))],x.prototype,Pr,1),p([A_Feature.Extend(),c(0,A_Dependency.Required()),c(0,A_Inject(l)),c(1,A_Inject(S))],x.prototype,wr,1),p([A_Feature.Extend(),c(0,A_Dependency.Required()),c(0,A_Inject(l)),c(1,A_Inject(S))],x.prototype,vr,1),p([A_Feature.Extend(),c(0,A_Dependency.Required()),c(0,A_Inject(l)),c(1,A_Inject(S))],x.prototype,Rr,1),p([A_Feature.Extend(),c(0,A_Dependency.Required()),c(0,A_Inject(l)),c(1,A_Inject(S))],x.prototype,xr,1),p([A_Feature.Extend(),c(0,A_Dependency.Required()),c(0,A_Inject(l)),c(1,A_Inject(S))],x.prototype,Cr,1);var Ye=x;var Ve=class Ve{constructor(){this.promise=new Promise((t,e)=>{this.resolveFn=t,this.rejectFn=e;});}resolve(t){this.resolveFn(t);}reject(t){this.rejectFn(t);}};i(Ve,"A_Deferred");var te=Ve;var je=class je{constructor(t,e,r){this.config={resolveOnClear:false};r&&(this.config={...this.config,...r}),this.deferred=new te,this.timeout=setTimeout(()=>e().then((...o)=>this.deferred.resolve(...o)).catch((...o)=>this.deferred.reject(...o)),t);}get promise(){return this.deferred.promise}clear(){this.timeout&&(clearTimeout(this.timeout),this.config.resolveOnClear?this.deferred.resolve(void 0):this.deferred.reject(new A_Error("Timeout Cleared")));}};i(je,"A_ScheduleObject");var K=je;var He=class He extends A_Component{async schedule(t,e,r){let o=A_TypeGuards.isString(t)?new Date(t).getTime():t;return new K(o-Date.now(),e,r)}async delay(t,e,r){return new K(t,e,r)}};i(He,"A_Schedule");var qe=He;export{So as A_CONSTANTS__CONFIG_ENV_VARIABLES,B as A_CONSTANTS__CONFIG_ENV_VARIABLES_ARRAY,Ae as A_Channel,M as A_ChannelError,dt as A_ChannelFeatures,X as A_ChannelRequest,ht as A_ChannelRequestStatuses,ve as A_Command,L as A_CommandError,yt as A_CommandFeatures,ut as A_CommandTransitions,gt as A_Command_Status,f as A_Config,D as A_ConfigError,ke as A_ConfigLoader,te as A_Deferred,N as A_LOGGER_ANSI,Qe as A_LOGGER_COLORS,Oo as A_LOGGER_DEFAULT_LEVEL,We as A_LOGGER_DEFAULT_SCOPE_LENGTH,Z as A_LOGGER_ENV_KEYS,T as A_LOGGER_FORMAT,et as A_LOGGER_SAFE_RANDOM_COLORS,j as A_LOGGER_TIME_FORMAT,v as A_Logger,fe as A_LoggerEnvVariables,an as A_LoggerEnvVariablesArray,Fe as A_Manifest,H as A_ManifestChecker,G as A_ManifestError,Ye as A_Memory,S as A_MemoryContext,_ as A_MemoryError,Er as A_MemoryFeatures,l as A_OperationContext,h as A_Polyfill,qe as A_Schedule,K as A_ScheduleObject,O as A_StateMachine,V as A_StateMachineError,At as A_StateMachineFeatures,R as A_StateMachineTransition,gr as A_TYPES__ConfigFeature,y as ConfigReader,q as ENVConfigReader,Q as FileConfigReader};//# sourceMappingURL=index.mjs.map
|
|
3085
45
|
//# sourceMappingURL=index.mjs.map
|