@adaas/a-utils 0.1.13 → 0.1.15

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