@adaas/a-utils 0.1.12 → 0.1.14

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.d.ts CHANGED
@@ -1,30 +1,443 @@
1
- import { A_Component, A_Error, A_TYPES__Error_Serialized, A_TYPES__Entity_Serialized, A_Meta, A_TYPES__FeatureExtendDecoratorMeta, A_TYPES__FeatureDefineDecoratorMeta, A_Entity, A_Scope, A_TYPES__ConceptENVVariables, A_TYPES__Fragment_Constructor, A_Fragment, A_Container, A_Feature, A_TYPES__Component_Constructor, A_TYPES__Entity_Constructor } from '@adaas/a-concept';
1
+ import { A_Fragment, A_Error, A_Component, A_TYPES__Error_Serialized, A_TYPES__Entity_Serialized, A_Meta, A_TYPES__FeatureExtendDecoratorMeta, A_TYPES__FeatureDefineDecoratorMeta, A_Entity, A_Scope, A_TYPES__ConceptENVVariables, A_TYPES__Fragment_Constructor, A_Container, A_Feature, A_TYPES__Component_Constructor, A_TYPES__Entity_Constructor } from '@adaas/a-concept';
2
2
  import { A_TYPES__Container_Constructor } from '@adaas/a-concept/dist/src/global/A-Container/A-Container.types';
3
3
 
4
+ declare enum A_ChannelRequestStatuses {
5
+ /**
6
+ * Request is pending
7
+ */
8
+ PENDING = "PENDING",
9
+ /***
10
+ * Request was successful
11
+ */
12
+ SUCCESS = "SUCCESS",
13
+ /**
14
+ * Request failed
15
+ */
16
+ FAILED = "FAILED"
17
+ }
18
+
19
+ type A_ChannelRequestContext_Serialized<_ParamsType extends Record<string, any> = Record<string, any>, _ResultType extends Record<string, any> = Record<string, any>> = {
20
+ params: _ParamsType;
21
+ result?: _ResultType;
22
+ status: string;
23
+ errors?: string[];
24
+ };
25
+
26
+ declare class A_ChannelRequestContext<_ParamsType extends Record<string, any> = Record<string, any>, _ResultType extends Record<string, any> = Record<string, any>> extends A_Fragment {
27
+ protected _params: _ParamsType;
28
+ protected _result?: _ResultType;
29
+ protected _errors: Set<Error>;
30
+ protected _status: A_ChannelRequestStatuses;
31
+ constructor(params?: Partial<_ParamsType>);
32
+ /**
33
+ * Returns the status of the request
34
+ */
35
+ get status(): A_ChannelRequestStatuses;
36
+ /**
37
+ * Returns the parameters of the request
38
+ */
39
+ get failed(): boolean;
40
+ /**
41
+ * Returns the Params of the Request
42
+ */
43
+ get params(): _ParamsType;
44
+ /**
45
+ * Returns the Result of the Request
46
+ */
47
+ get data(): _ResultType | undefined;
48
+ get errors(): Set<Error> | undefined;
49
+ /**
50
+ * Adds an error to the context
51
+ *
52
+ * @param error
53
+ */
54
+ fail(error: A_Error): void;
55
+ /**
56
+ * Sets the result of the request
57
+ *
58
+ * @param result
59
+ */
60
+ succeed(result: _ResultType): void;
61
+ /**
62
+ * Serializes the context to a JSON object
63
+ *
64
+ * @returns
65
+ */
66
+ toJSON(): A_ChannelRequestContext_Serialized<_ParamsType, _ResultType>;
67
+ }
68
+
69
+ /**
70
+ * A-Channel - A powerful, extensible communication channel component
71
+ *
72
+ * A-Channel provides a structured approach to implementing various communication patterns
73
+ * such as HTTP clients, WebSocket connections, message queues, and other messaging systems.
74
+ * It offers a complete lifecycle management system with extensible hooks for custom behavior.
75
+ *
76
+ * ## Key Features:
77
+ * - 🔄 **Lifecycle Management** - Complete connection and processing lifecycle with hooks
78
+ * - 📡 **Multiple Communication Patterns** - Request/Response and Fire-and-Forget messaging
79
+ * - 🛡️ **Error Handling** - Comprehensive error capture and management
80
+ * - 🎯 **Type Safety** - Full TypeScript support with generic types
81
+ * - 🔧 **Extensible** - Component-based architecture for custom behavior
82
+ * - ⚡ **Concurrent Processing** - Handle multiple requests simultaneously
83
+ *
84
+ * ## Basic Usage:
85
+ * ```typescript
86
+ * const channel = new A_Channel();
87
+ * A_Context.root.register(channel);
88
+ *
89
+ * // Request/Response pattern
90
+ * const response = await channel.request({ action: 'getData', id: 123 });
91
+ *
92
+ * // Fire-and-forget pattern
93
+ * await channel.send({ type: 'notification', message: 'Hello World' });
94
+ * ```
95
+ *
96
+ * ## Custom Implementation:
97
+ * ```typescript
98
+ * class HttpChannel extends A_Channel {}
99
+ *
100
+ * class HttpProcessor extends A_Component {
101
+ * @A_Feature.Extend({ scope: [HttpChannel] })
102
+ * async [A_ChannelFeatures.onRequest](
103
+ * @A_Inject(A_ChannelRequestContext) context: A_ChannelRequestContext
104
+ * ) {
105
+ * const response = await fetch(context.params.url);
106
+ * (context as any)._result = await response.json();
107
+ * }
108
+ * }
109
+ * ```
110
+ *
111
+ * @see {@link ./README.md} For complete documentation and examples
112
+ */
4
113
  declare class A_Channel extends A_Component {
5
114
  /**
6
- * Indicates whether the channel is processing requests
115
+ * Indicates whether the channel is currently processing requests.
116
+ * This flag is managed automatically during request/send operations.
117
+ *
118
+ * @readonly
7
119
  */
8
120
  protected _processing: boolean;
9
121
  /**
10
- * Indicates whether the channel is connected
122
+ * Promise that resolves when the channel initialization is complete.
123
+ * Ensures that onConnect lifecycle hook has been executed before
124
+ * any communication operations.
125
+ *
126
+ * @private
11
127
  */
12
128
  protected _initialized?: Promise<void>;
13
129
  /**
14
- * Indicates whether the channel is processing requests
15
- */
130
+ * Internal cache storage for channel-specific data.
131
+ * Can be used by custom implementations for caching responses,
132
+ * connection pools, or other channel-specific state.
133
+ *
134
+ * @protected
135
+ */
136
+ protected _cache: Map<string, any>;
137
+ /**
138
+ * Creates a new A_Channel instance.
139
+ *
140
+ * The channel must be registered with A_Context before use:
141
+ * ```typescript
142
+ * const channel = new A_Channel();
143
+ * A_Context.root.register(channel);
144
+ * ```
145
+ */
146
+ constructor();
147
+ /**
148
+ * Indicates whether the channel is currently processing requests.
149
+ *
150
+ * @returns {boolean} True if channel is processing, false otherwise
151
+ */
16
152
  get processing(): boolean;
17
153
  /**
18
- * Indicates whether the channel is connected
154
+ * Promise that resolves when the channel is fully initialized.
155
+ *
156
+ * Automatically calls the onConnect lifecycle hook if not already called.
157
+ * This ensures the channel is ready for communication operations.
158
+ *
159
+ * @returns {Promise<void>} Promise that resolves when initialization is complete
19
160
  */
20
161
  get initialize(): Promise<void>;
162
+ /**
163
+ * Connection lifecycle hook - called during channel initialization.
164
+ *
165
+ * Override this method in custom components to implement connection logic:
166
+ * - Initialize network connections
167
+ * - Load configuration
168
+ * - Validate environment
169
+ * - Set up connection pools
170
+ *
171
+ * @example
172
+ * ```typescript
173
+ * class DatabaseChannel extends A_Channel {}
174
+ *
175
+ * class DatabaseConnector extends A_Component {
176
+ * @A_Feature.Extend({ scope: [DatabaseChannel] })
177
+ * async [A_ChannelFeatures.onConnect]() {
178
+ * await this.initializeDatabase();
179
+ * console.log('Database channel connected');
180
+ * }
181
+ * }
182
+ * ```
183
+ */
184
+ onConnect(...args: any[]): Promise<void>;
185
+ /**
186
+ * Disconnection lifecycle hook - called during channel cleanup.
187
+ *
188
+ * Override this method in custom components to implement cleanup logic:
189
+ * - Close network connections
190
+ * - Save state
191
+ * - Release resources
192
+ * - Clear caches
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * @A_Feature.Extend({ scope: [DatabaseChannel] })
197
+ * async [A_ChannelFeatures.onDisconnect]() {
198
+ * await this.closeConnections();
199
+ * console.log('Database channel disconnected');
200
+ * }
201
+ * ```
202
+ */
203
+ onDisconnect(...args: any[]): Promise<void>;
204
+ /**
205
+ * Pre-request processing hook - called before main request processing.
206
+ *
207
+ * Use this hook for:
208
+ * - Request validation
209
+ * - Authentication
210
+ * - Rate limiting
211
+ * - Logging
212
+ * - Request transformation
213
+ *
214
+ * @example
215
+ * ```typescript
216
+ * @A_Feature.Extend({ scope: [HttpChannel] })
217
+ * async [A_ChannelFeatures.onBeforeRequest](
218
+ * @A_Inject(A_ChannelRequestContext) context: A_ChannelRequestContext
219
+ * ) {
220
+ * // Validate required parameters
221
+ * if (!context.params.url) {
222
+ * throw new Error('URL is required');
223
+ * }
224
+ * }
225
+ * ```
226
+ */
227
+ onBeforeRequest(...args: any[]): Promise<void>;
228
+ /**
229
+ * Main request processing hook - core business logic goes here.
230
+ *
231
+ * This is where the main communication logic should be implemented:
232
+ * - Make HTTP requests
233
+ * - Send messages to queues
234
+ * - Execute database queries
235
+ * - Process business logic
236
+ *
237
+ * Set the result in the context: `(context as any)._result = yourResult;`
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * @A_Feature.Extend({ scope: [HttpChannel] })
242
+ * async [A_ChannelFeatures.onRequest](
243
+ * @A_Inject(A_ChannelRequestContext) context: A_ChannelRequestContext
244
+ * ) {
245
+ * const response = await fetch(context.params.url);
246
+ * (context as any)._result = await response.json();
247
+ * }
248
+ * ```
249
+ */
250
+ onRequest(...args: any[]): Promise<void>;
251
+ /**
252
+ * Post-request processing hook - called after successful request processing.
253
+ *
254
+ * Use this hook for:
255
+ * - Response transformation
256
+ * - Logging
257
+ * - Analytics
258
+ * - Caching results
259
+ * - Cleanup
260
+ *
261
+ * @example
262
+ * ```typescript
263
+ * @A_Feature.Extend({ scope: [HttpChannel] })
264
+ * async [A_ChannelFeatures.onAfterRequest](
265
+ * @A_Inject(A_ChannelRequestContext) context: A_ChannelRequestContext
266
+ * ) {
267
+ * console.log(`Request completed in ${Date.now() - context.startTime}ms`);
268
+ * await this.cacheResponse(context.params, context.data);
269
+ * }
270
+ * ```
271
+ */
272
+ onAfterRequest(...args: any[]): Promise<void>;
273
+ /**
274
+ * Error handling hook - called when any operation fails.
275
+ *
276
+ * Use this hook for:
277
+ * - Error logging
278
+ * - Error transformation
279
+ * - Alerting
280
+ * - Retry logic
281
+ * - Fallback mechanisms
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * @A_Feature.Extend({ scope: [HttpChannel] })
286
+ * async [A_ChannelFeatures.onError](
287
+ * @A_Inject(A_ChannelRequestContext) context: A_ChannelRequestContext
288
+ * ) {
289
+ * console.error('Request failed:', context.params, context.failed);
290
+ * await this.logError(context);
291
+ * await this.sendAlert(context);
292
+ * }
293
+ * ```
294
+ */
295
+ onError(...args: any[]): Promise<void>;
296
+ /**
297
+ * Send operation hook - called for fire-and-forget messaging.
298
+ *
299
+ * Use this hook for:
300
+ * - Message broadcasting
301
+ * - Event publishing
302
+ * - Notification sending
303
+ * - Queue operations
304
+ *
305
+ * @example
306
+ * ```typescript
307
+ * @A_Feature.Extend({ scope: [EventChannel] })
308
+ * async [A_ChannelFeatures.onSend](
309
+ * @A_Inject(A_ChannelRequestContext) context: A_ChannelRequestContext
310
+ * ) {
311
+ * const { eventType, payload } = context.params;
312
+ * await this.publishEvent(eventType, payload);
313
+ * }
314
+ * ```
315
+ */
316
+ onSend(...args: any[]): Promise<void>;
317
+ /**
318
+ * Initializes the channel by calling the onConnect lifecycle hook.
319
+ *
320
+ * This method is called automatically when accessing the `initialize` property.
321
+ * You can also call it manually if needed.
322
+ *
323
+ * @returns {Promise<void>} Promise that resolves when connection is established
324
+ */
21
325
  connect(): Promise<void>;
22
- request(params: any): Promise<any>;
23
- send(message: any): Promise<void>;
326
+ /**
327
+ * Disconnects the channel by calling the onDisconnect lifecycle hook.
328
+ *
329
+ * Use this method to properly cleanup resources when the channel is no longer needed.
330
+ *
331
+ * @returns {Promise<void>} Promise that resolves when cleanup is complete
332
+ */
333
+ disconnect(): Promise<void>;
334
+ /**
335
+ * Sends a request and waits for a response (Request/Response pattern).
336
+ *
337
+ * This method follows the complete request lifecycle:
338
+ * 1. Ensures channel is initialized
339
+ * 2. Creates request scope and context
340
+ * 3. Calls onBeforeRequest hook
341
+ * 4. Calls onRequest hook (main processing)
342
+ * 5. Calls onAfterRequest hook
343
+ * 6. Returns the response context
344
+ *
345
+ * If any step fails, the onError hook is called and the error is captured
346
+ * in the returned context.
347
+ *
348
+ * @template _ParamsType The type of request parameters
349
+ * @template _ResultType The type of response data
350
+ * @param params The request parameters
351
+ * @returns {Promise<A_ChannelRequestContext<_ParamsType, _ResultType>>} Request context with response
352
+ *
353
+ * @example
354
+ * ```typescript
355
+ * // Basic usage
356
+ * const response = await channel.request({ action: 'getData', id: 123 });
357
+ *
358
+ * // Typed usage
359
+ * interface UserRequest { userId: string; }
360
+ * interface UserResponse { name: string; email: string; }
361
+ *
362
+ * const userResponse = await channel.request<UserRequest, UserResponse>({
363
+ * userId: 'user-123'
364
+ * });
365
+ *
366
+ * if (!userResponse.failed) {
367
+ * console.log('User:', userResponse.data.name);
368
+ * }
369
+ * ```
370
+ */
371
+ request<_ParamsType extends Record<string, any> = Record<string, any>, _ResultType extends Record<string, any> = Record<string, any>>(params: _ParamsType): Promise<A_ChannelRequestContext<_ParamsType, _ResultType>>;
372
+ /**
373
+ * Sends a fire-and-forget message (Send pattern).
374
+ *
375
+ * This method is used for one-way communication where no response is expected:
376
+ * - Event broadcasting
377
+ * - Notification sending
378
+ * - Message queuing
379
+ * - Logging operations
380
+ *
381
+ * The method follows this lifecycle:
382
+ * 1. Ensures channel is initialized
383
+ * 2. Creates send scope and context
384
+ * 3. Calls onSend hook
385
+ * 4. Completes without returning data
386
+ *
387
+ * If the operation fails, the onError hook is called but no error is thrown
388
+ * to the caller (fire-and-forget semantics).
389
+ *
390
+ * @template _ParamsType The type of message parameters
391
+ * @param message The message to send
392
+ * @returns {Promise<void>} Promise that resolves when send is complete
393
+ *
394
+ * @example
395
+ * ```typescript
396
+ * // Send notification
397
+ * await channel.send({
398
+ * type: 'user.login',
399
+ * userId: 'user-123',
400
+ * timestamp: new Date().toISOString()
401
+ * });
402
+ *
403
+ * // Send to message queue
404
+ * await channel.send({
405
+ * queue: 'email-queue',
406
+ * payload: {
407
+ * to: 'user@example.com',
408
+ * subject: 'Welcome!',
409
+ * body: 'Welcome to our service!'
410
+ * }
411
+ * });
412
+ * ```
413
+ */
414
+ send<_ParamsType extends Record<string, any> = Record<string, any>>(message: _ParamsType): Promise<void>;
415
+ /**
416
+ * @deprecated This method is deprecated and will be removed in future versions.
417
+ * Use request() or send() methods instead depending on your communication pattern.
418
+ *
419
+ * For request/response pattern: Use request()
420
+ * For fire-and-forget pattern: Use send()
421
+ * For consumer patterns: Implement custom consumer logic using request() in a loop
422
+ */
423
+ consume<T extends Record<string, any> = Record<string, any>>(): Promise<A_ChannelRequestContext<any, T>>;
24
424
  }
25
425
 
26
426
  declare class A_ChannelError extends A_Error {
27
427
  static readonly MethodNotImplemented = "A-Channel Method Not Implemented";
428
+ protected _context?: A_ChannelRequestContext;
429
+ /**
430
+ * Channel Error allows to keep track of errors within a channel if something goes wrong
431
+ *
432
+ *
433
+ * @param originalError
434
+ * @param context
435
+ */
436
+ constructor(originalError: string | A_Error | Error | any, context?: A_ChannelRequestContext | string);
437
+ /***
438
+ * Returns Context of the error
439
+ */
440
+ get context(): A_ChannelRequestContext | undefined;
28
441
  }
29
442
 
30
443
  declare enum A_TYPES__CommandMetaKey {
@@ -206,6 +619,12 @@ declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Comm
206
619
  params: InvokeType | A_TYPES__Command_Serialized<InvokeType, ResultType> | string);
207
620
  init(): Promise<void>;
208
621
  compile(): Promise<void>;
622
+ /**
623
+ * Processes the command execution
624
+ *
625
+ * @returns
626
+ */
627
+ process(): Promise<void>;
209
628
  /**
210
629
  * Executes the command logic.
211
630
  */
@@ -258,9 +677,11 @@ declare class A_Command<InvokeType extends A_TYPES__Command_Init = A_TYPES__Comm
258
677
  * @returns
259
678
  */
260
679
  toJSON(): A_TYPES__Command_Serialized<InvokeType, ResultType>;
680
+ protected checkScopeInheritance(): void;
261
681
  }
262
682
 
263
683
  declare class A_CommandError extends A_Error {
684
+ static readonly CommandScopeBindingError = "A-Command Scope Binding Error";
264
685
  }
265
686
 
266
687
  interface Ifspolyfill {