@xpert-ai/plugin-sdk 3.7.0 → 3.7.1

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/index.cjs.js CHANGED
@@ -4,11 +4,15 @@ var common = require('@nestjs/common');
4
4
  var constants = require('@nestjs/common/constants');
5
5
  var lodashEs = require('lodash-es');
6
6
  var core = require('@nestjs/core');
7
+ var contracts = require('@metad/contracts');
8
+ var node_async_hooks = require('node:async_hooks');
9
+ var passportJwt = require('passport-jwt');
10
+ var jsonwebtoken = require('jsonwebtoken');
11
+ var node_crypto = require('node:crypto');
7
12
  var cqrs = require('@nestjs/cqrs');
8
13
  var fs = require('fs');
9
14
  var http = require('http');
10
15
  var https = require('https');
11
- var contracts = require('@metad/contracts');
12
16
  var tools = require('@langchain/core/tools');
13
17
  var zod = require('zod');
14
18
  var fsPromises = require('fs/promises');
@@ -16,10 +20,6 @@ var path = require('path');
16
20
  var i18next = require('i18next');
17
21
  var FsBackend = require('i18next-fs-backend');
18
22
  var yaml = require('yaml');
19
- var node_async_hooks = require('node:async_hooks');
20
- var passportJwt = require('passport-jwt');
21
- var jsonwebtoken = require('jsonwebtoken');
22
- var node_crypto = require('node:crypto');
23
23
  var _axios = require('axios');
24
24
  var openai = require('@langchain/openai');
25
25
  var documents = require('@langchain/core/documents');
@@ -84,6 +84,11 @@ var _axios__namespace = /*#__PURE__*/_interopNamespaceDefault(_axios);
84
84
  };
85
85
  }
86
86
 
87
+ const ORGANIZATION_METADATA_KEY = 'xpert:organizationId';
88
+ const PLUGIN_METADATA_KEY = 'xpert:pluginName';
89
+ const GLOBAL_ORGANIZATION_SCOPE = 'global';
90
+ const STRATEGY_META_KEY = 'XPERT_STRATEGY_META_KEY';
91
+
87
92
  function _extends() {
88
93
  _extends = Object.assign || function assign(target) {
89
94
  for(var i = 1; i < arguments.length; i++){
@@ -114,52 +119,1154 @@ function createPluginLogger(scope, baseMeta = {}) {
114
119
  };
115
120
  }
116
121
 
117
- const INTEGRATION_STRATEGY = 'INTEGRATION_STRATEGY';
118
- const IntegrationStrategyKey = (provider)=>common.SetMetadata(INTEGRATION_STRATEGY, provider);
119
-
120
- function __decorate(decorators, target, key, desc) {
121
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
122
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
123
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
124
- return c > 3 && r && Object.defineProperty(target, key, r), r;
125
- }
126
- function __metadata(metadataKey, metadataValue) {
127
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
128
- }
129
- typeof SuppressedError === "function" ? SuppressedError : function _SuppressedError(error, suppressed, message) {
130
- var e = new Error(message);
131
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
122
+ const INTEGRATION_STRATEGY = 'INTEGRATION_STRATEGY';
123
+ const IntegrationStrategyKey = (provider)=>common.applyDecorators(common.SetMetadata(INTEGRATION_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, INTEGRATION_STRATEGY));
124
+
125
+ /******************************************************************************
126
+ Copyright (c) Microsoft Corporation.
127
+
128
+ Permission to use, copy, modify, and/or distribute this software for any
129
+ purpose with or without fee is hereby granted.
130
+
131
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
132
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
133
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
134
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
135
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
136
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
137
+ PERFORMANCE OF THIS SOFTWARE.
138
+ ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ function _instanceof$2(left, right) {
139
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
140
+ return !!right[Symbol.hasInstance](left);
141
+ } else {
142
+ return left instanceof right;
143
+ }
144
+ }
145
+ var extendStatics = function extendStatics1(d, b) {
146
+ extendStatics = Object.setPrototypeOf || _instanceof$2({
147
+ __proto__: []
148
+ }, Array) && function(d, b) {
149
+ d.__proto__ = b;
150
+ } || function(d, b) {
151
+ for(var p in b)if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
152
+ };
153
+ return extendStatics(d, b);
154
+ };
155
+ function __extends(d, b) {
156
+ if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
157
+ extendStatics(d, b);
158
+ function __() {
159
+ this.constructor = d;
160
+ }
161
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
162
+ }
163
+ function __decorate(decorators, target, key, desc) {
164
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
165
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
166
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
167
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
168
+ }
169
+ function __metadata(metadataKey, metadataValue) {
170
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
171
+ }
172
+ function __values(o) {
173
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
174
+ if (m) return m.call(o);
175
+ if (o && typeof o.length === "number") return {
176
+ next: function next() {
177
+ if (o && i >= o.length) o = void 0;
178
+ return {
179
+ value: o && o[i++],
180
+ done: !o
181
+ };
182
+ }
183
+ };
184
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
185
+ }
186
+ function __read(o, n) {
187
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
188
+ if (!m) return o;
189
+ var i = m.call(o), r, ar = [], e;
190
+ try {
191
+ while((n === void 0 || n-- > 0) && !(r = i.next()).done)ar.push(r.value);
192
+ } catch (error) {
193
+ e = {
194
+ error: error
195
+ };
196
+ } finally{
197
+ try {
198
+ if (r && !r.done && (m = i["return"])) m.call(i);
199
+ } finally{
200
+ if (e) throw e.error;
201
+ }
202
+ }
203
+ return ar;
204
+ }
205
+ function __spreadArray(to, from, pack) {
206
+ if (pack || arguments.length === 2) for(var i = 0, l = from.length, ar; i < l; i++){
207
+ if (ar || !(i in from)) {
208
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
209
+ ar[i] = from[i];
210
+ }
211
+ }
212
+ return to.concat(ar || Array.prototype.slice.call(from));
213
+ }
214
+ typeof SuppressedError === "function" ? SuppressedError : function _SuppressedError(error, suppressed, message) {
215
+ var e = new Error(message);
216
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
217
+ };
218
+
219
+ function isFunction(value) {
220
+ return typeof value === "function";
221
+ }
222
+
223
+ function createErrorClass(createImpl) {
224
+ var _super = function _super(instance) {
225
+ Error.call(instance);
226
+ instance.stack = new Error().stack;
227
+ };
228
+ var ctorFunc = createImpl(_super);
229
+ ctorFunc.prototype = Object.create(Error.prototype);
230
+ ctorFunc.prototype.constructor = ctorFunc;
231
+ return ctorFunc;
232
+ }
233
+
234
+ var UnsubscriptionError = createErrorClass(function(_super) {
235
+ return function UnsubscriptionErrorImpl(errors) {
236
+ _super(this);
237
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
238
+ return i + 1 + ") " + err.toString();
239
+ }).join("\n ") : "";
240
+ this.name = "UnsubscriptionError";
241
+ this.errors = errors;
242
+ };
243
+ });
244
+
245
+ function arrRemove(arr, item) {
246
+ if (arr) {
247
+ var index = arr.indexOf(item);
248
+ 0 <= index && arr.splice(index, 1);
249
+ }
250
+ }
251
+
252
+ function _instanceof$1(left, right) {
253
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
254
+ return !!right[Symbol.hasInstance](left);
255
+ } else {
256
+ return left instanceof right;
257
+ }
258
+ }
259
+ var Subscription = function() {
260
+ function Subscription(initialTeardown) {
261
+ this.initialTeardown = initialTeardown;
262
+ this.closed = false;
263
+ this._parentage = null;
264
+ this._finalizers = null;
265
+ }
266
+ Subscription.prototype.unsubscribe = function() {
267
+ var e_1, _a, e_2, _b;
268
+ var errors;
269
+ if (!this.closed) {
270
+ this.closed = true;
271
+ var _parentage = this._parentage;
272
+ if (_parentage) {
273
+ this._parentage = null;
274
+ if (Array.isArray(_parentage)) {
275
+ try {
276
+ for(var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()){
277
+ var parent_1 = _parentage_1_1.value;
278
+ parent_1.remove(this);
279
+ }
280
+ } catch (e_1_1) {
281
+ e_1 = {
282
+ error: e_1_1
283
+ };
284
+ } finally{
285
+ try {
286
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
287
+ } finally{
288
+ if (e_1) throw e_1.error;
289
+ }
290
+ }
291
+ } else {
292
+ _parentage.remove(this);
293
+ }
294
+ }
295
+ var initialFinalizer = this.initialTeardown;
296
+ if (isFunction(initialFinalizer)) {
297
+ try {
298
+ initialFinalizer();
299
+ } catch (e) {
300
+ errors = _instanceof$1(e, UnsubscriptionError) ? e.errors : [
301
+ e
302
+ ];
303
+ }
304
+ }
305
+ var _finalizers = this._finalizers;
306
+ if (_finalizers) {
307
+ this._finalizers = null;
308
+ try {
309
+ for(var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()){
310
+ var finalizer = _finalizers_1_1.value;
311
+ try {
312
+ execFinalizer(finalizer);
313
+ } catch (err) {
314
+ errors = errors !== null && errors !== void 0 ? errors : [];
315
+ if (_instanceof$1(err, UnsubscriptionError)) {
316
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
317
+ } else {
318
+ errors.push(err);
319
+ }
320
+ }
321
+ }
322
+ } catch (e_2_1) {
323
+ e_2 = {
324
+ error: e_2_1
325
+ };
326
+ } finally{
327
+ try {
328
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
329
+ } finally{
330
+ if (e_2) throw e_2.error;
331
+ }
332
+ }
333
+ }
334
+ if (errors) {
335
+ throw new UnsubscriptionError(errors);
336
+ }
337
+ }
338
+ };
339
+ Subscription.prototype.add = function(teardown) {
340
+ var _a;
341
+ if (teardown && teardown !== this) {
342
+ if (this.closed) {
343
+ execFinalizer(teardown);
344
+ } else {
345
+ if (_instanceof$1(teardown, Subscription)) {
346
+ if (teardown.closed || teardown._hasParent(this)) {
347
+ return;
348
+ }
349
+ teardown._addParent(this);
350
+ }
351
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
352
+ }
353
+ }
354
+ };
355
+ Subscription.prototype._hasParent = function(parent) {
356
+ var _parentage = this._parentage;
357
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
358
+ };
359
+ Subscription.prototype._addParent = function(parent) {
360
+ var _parentage = this._parentage;
361
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [
362
+ _parentage,
363
+ parent
364
+ ] : parent;
365
+ };
366
+ Subscription.prototype._removeParent = function(parent) {
367
+ var _parentage = this._parentage;
368
+ if (_parentage === parent) {
369
+ this._parentage = null;
370
+ } else if (Array.isArray(_parentage)) {
371
+ arrRemove(_parentage, parent);
372
+ }
373
+ };
374
+ Subscription.prototype.remove = function(teardown) {
375
+ var _finalizers = this._finalizers;
376
+ _finalizers && arrRemove(_finalizers, teardown);
377
+ if (_instanceof$1(teardown, Subscription)) {
378
+ teardown._removeParent(this);
379
+ }
380
+ };
381
+ Subscription.EMPTY = function() {
382
+ var empty = new Subscription();
383
+ empty.closed = true;
384
+ return empty;
385
+ }();
386
+ return Subscription;
387
+ }();
388
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
389
+ function isSubscription(value) {
390
+ return _instanceof$1(value, Subscription) || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
391
+ }
392
+ function execFinalizer(finalizer) {
393
+ if (isFunction(finalizer)) {
394
+ finalizer();
395
+ } else {
396
+ finalizer.unsubscribe();
397
+ }
398
+ }
399
+
400
+ var config = {
401
+ Promise: undefined};
402
+
403
+ var timeoutProvider = {
404
+ setTimeout: function setTimeout1(handler, timeout) {
405
+ var args = [];
406
+ for(var _i = 2; _i < arguments.length; _i++){
407
+ args[_i - 2] = arguments[_i];
408
+ }
409
+ return setTimeout.apply(void 0, __spreadArray([
410
+ handler,
411
+ timeout
412
+ ], __read(args)));
413
+ },
414
+ clearTimeout: function clearTimeout1(handle) {
415
+ return (clearTimeout)(handle);
416
+ },
417
+ delegate: undefined
418
+ };
419
+
420
+ function reportUnhandledError(err) {
421
+ timeoutProvider.setTimeout(function() {
422
+ {
423
+ throw err;
424
+ }
425
+ });
426
+ }
427
+
428
+ function noop() {}
429
+
430
+ function errorContext(cb) {
431
+ {
432
+ cb();
433
+ }
434
+ }
435
+
436
+ var Subscriber = function(_super) {
437
+ __extends(Subscriber, _super);
438
+ function Subscriber(destination) {
439
+ var _this = _super.call(this) || this;
440
+ _this.isStopped = false;
441
+ if (destination) {
442
+ _this.destination = destination;
443
+ if (isSubscription(destination)) {
444
+ destination.add(_this);
445
+ }
446
+ } else {
447
+ _this.destination = EMPTY_OBSERVER;
448
+ }
449
+ return _this;
450
+ }
451
+ Subscriber.create = function(next, error, complete) {
452
+ return new SafeSubscriber(next, error, complete);
453
+ };
454
+ Subscriber.prototype.next = function(value) {
455
+ if (this.isStopped) ; else {
456
+ this._next(value);
457
+ }
458
+ };
459
+ Subscriber.prototype.error = function(err) {
460
+ if (this.isStopped) ; else {
461
+ this.isStopped = true;
462
+ this._error(err);
463
+ }
464
+ };
465
+ Subscriber.prototype.complete = function() {
466
+ if (this.isStopped) ; else {
467
+ this.isStopped = true;
468
+ this._complete();
469
+ }
470
+ };
471
+ Subscriber.prototype.unsubscribe = function() {
472
+ if (!this.closed) {
473
+ this.isStopped = true;
474
+ _super.prototype.unsubscribe.call(this);
475
+ this.destination = null;
476
+ }
477
+ };
478
+ Subscriber.prototype._next = function(value) {
479
+ this.destination.next(value);
480
+ };
481
+ Subscriber.prototype._error = function(err) {
482
+ try {
483
+ this.destination.error(err);
484
+ } finally{
485
+ this.unsubscribe();
486
+ }
487
+ };
488
+ Subscriber.prototype._complete = function() {
489
+ try {
490
+ this.destination.complete();
491
+ } finally{
492
+ this.unsubscribe();
493
+ }
494
+ };
495
+ return Subscriber;
496
+ }(Subscription);
497
+ var ConsumerObserver = function() {
498
+ function ConsumerObserver(partialObserver) {
499
+ this.partialObserver = partialObserver;
500
+ }
501
+ ConsumerObserver.prototype.next = function(value) {
502
+ var partialObserver = this.partialObserver;
503
+ if (partialObserver.next) {
504
+ try {
505
+ partialObserver.next(value);
506
+ } catch (error) {
507
+ handleUnhandledError(error);
508
+ }
509
+ }
510
+ };
511
+ ConsumerObserver.prototype.error = function(err) {
512
+ var partialObserver = this.partialObserver;
513
+ if (partialObserver.error) {
514
+ try {
515
+ partialObserver.error(err);
516
+ } catch (error) {
517
+ handleUnhandledError(error);
518
+ }
519
+ } else {
520
+ handleUnhandledError(err);
521
+ }
522
+ };
523
+ ConsumerObserver.prototype.complete = function() {
524
+ var partialObserver = this.partialObserver;
525
+ if (partialObserver.complete) {
526
+ try {
527
+ partialObserver.complete();
528
+ } catch (error) {
529
+ handleUnhandledError(error);
530
+ }
531
+ }
532
+ };
533
+ return ConsumerObserver;
534
+ }();
535
+ var SafeSubscriber = function(_super) {
536
+ __extends(SafeSubscriber, _super);
537
+ function SafeSubscriber(observerOrNext, error, complete) {
538
+ var _this = _super.call(this) || this;
539
+ var partialObserver;
540
+ if (isFunction(observerOrNext) || !observerOrNext) {
541
+ partialObserver = {
542
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
543
+ error: error !== null && error !== void 0 ? error : undefined,
544
+ complete: complete !== null && complete !== void 0 ? complete : undefined
545
+ };
546
+ } else {
547
+ {
548
+ partialObserver = observerOrNext;
549
+ }
550
+ }
551
+ _this.destination = new ConsumerObserver(partialObserver);
552
+ return _this;
553
+ }
554
+ return SafeSubscriber;
555
+ }(Subscriber);
556
+ function handleUnhandledError(error) {
557
+ {
558
+ reportUnhandledError(error);
559
+ }
560
+ }
561
+ function defaultErrorHandler(err) {
562
+ throw err;
563
+ }
564
+ var EMPTY_OBSERVER = {
565
+ closed: true,
566
+ next: noop,
567
+ error: defaultErrorHandler,
568
+ complete: noop
569
+ };
570
+
571
+ var observable = function() {
572
+ return typeof Symbol === "function" && Symbol.observable || "@@observable";
573
+ }();
574
+
575
+ function identity(x) {
576
+ return x;
577
+ }
578
+
579
+ function pipeFromArray(fns) {
580
+ if (fns.length === 0) {
581
+ return identity;
582
+ }
583
+ if (fns.length === 1) {
584
+ return fns[0];
585
+ }
586
+ return function piped(input) {
587
+ return fns.reduce(function(prev, fn) {
588
+ return fn(prev);
589
+ }, input);
590
+ };
591
+ }
592
+
593
+ function _instanceof(left, right) {
594
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
595
+ return !!right[Symbol.hasInstance](left);
596
+ } else {
597
+ return left instanceof right;
598
+ }
599
+ }
600
+ var Observable = function() {
601
+ function Observable(subscribe) {
602
+ if (subscribe) {
603
+ this._subscribe = subscribe;
604
+ }
605
+ }
606
+ Observable.prototype.lift = function(operator) {
607
+ var observable = new Observable();
608
+ observable.source = this;
609
+ observable.operator = operator;
610
+ return observable;
611
+ };
612
+ Observable.prototype.subscribe = function(observerOrNext, error, complete) {
613
+ var _this = this;
614
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
615
+ errorContext(function() {
616
+ var _a = _this, operator = _a.operator, source = _a.source;
617
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
618
+ });
619
+ return subscriber;
620
+ };
621
+ Observable.prototype._trySubscribe = function(sink) {
622
+ try {
623
+ return this._subscribe(sink);
624
+ } catch (err) {
625
+ sink.error(err);
626
+ }
627
+ };
628
+ Observable.prototype.forEach = function(next, promiseCtor) {
629
+ var _this = this;
630
+ promiseCtor = getPromiseCtor(promiseCtor);
631
+ return new promiseCtor(function(resolve, reject) {
632
+ var subscriber = new SafeSubscriber({
633
+ next: function next1(value) {
634
+ try {
635
+ next(value);
636
+ } catch (err) {
637
+ reject(err);
638
+ subscriber.unsubscribe();
639
+ }
640
+ },
641
+ error: reject,
642
+ complete: resolve
643
+ });
644
+ _this.subscribe(subscriber);
645
+ });
646
+ };
647
+ Observable.prototype._subscribe = function(subscriber) {
648
+ var _a;
649
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
650
+ };
651
+ Observable.prototype[observable] = function() {
652
+ return this;
653
+ };
654
+ Observable.prototype.pipe = function() {
655
+ var operations = [];
656
+ for(var _i = 0; _i < arguments.length; _i++){
657
+ operations[_i] = arguments[_i];
658
+ }
659
+ return pipeFromArray(operations)(this);
660
+ };
661
+ Observable.prototype.toPromise = function(promiseCtor) {
662
+ var _this = this;
663
+ promiseCtor = getPromiseCtor(promiseCtor);
664
+ return new promiseCtor(function(resolve, reject) {
665
+ var value;
666
+ _this.subscribe(function(x) {
667
+ return value = x;
668
+ }, function(err) {
669
+ return reject(err);
670
+ }, function() {
671
+ return resolve(value);
672
+ });
673
+ });
674
+ };
675
+ Observable.create = function(subscribe) {
676
+ return new Observable(subscribe);
677
+ };
678
+ return Observable;
679
+ }();
680
+ function getPromiseCtor(promiseCtor) {
681
+ var _a;
682
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
683
+ }
684
+ function isObserver(value) {
685
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
686
+ }
687
+ function isSubscriber(value) {
688
+ return value && _instanceof(value, Subscriber) || isObserver(value) && isSubscription(value);
689
+ }
690
+
691
+ function hasLift(source) {
692
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
693
+ }
694
+ function operate(init) {
695
+ return function(source) {
696
+ if (hasLift(source)) {
697
+ return source.lift(function(liftedSource) {
698
+ try {
699
+ return init(liftedSource, this);
700
+ } catch (err) {
701
+ this.error(err);
702
+ }
703
+ });
704
+ }
705
+ throw new TypeError("Unable to lift unknown Observable type");
706
+ };
707
+ }
708
+
709
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
710
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
711
+ }
712
+ var OperatorSubscriber = function(_super) {
713
+ __extends(OperatorSubscriber, _super);
714
+ function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
715
+ var _this = _super.call(this, destination) || this;
716
+ _this.onFinalize = onFinalize;
717
+ _this.shouldUnsubscribe = shouldUnsubscribe;
718
+ _this._next = onNext ? function(value) {
719
+ try {
720
+ onNext(value);
721
+ } catch (err) {
722
+ destination.error(err);
723
+ }
724
+ } : _super.prototype._next;
725
+ _this._error = onError ? function(err) {
726
+ try {
727
+ onError(err);
728
+ } catch (err) {
729
+ destination.error(err);
730
+ } finally{
731
+ this.unsubscribe();
732
+ }
733
+ } : _super.prototype._error;
734
+ _this._complete = onComplete ? function() {
735
+ try {
736
+ onComplete();
737
+ } catch (err) {
738
+ destination.error(err);
739
+ } finally{
740
+ this.unsubscribe();
741
+ }
742
+ } : _super.prototype._complete;
743
+ return _this;
744
+ }
745
+ OperatorSubscriber.prototype.unsubscribe = function() {
746
+ var _a;
747
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
748
+ var closed_1 = this.closed;
749
+ _super.prototype.unsubscribe.call(this);
750
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
751
+ }
752
+ };
753
+ return OperatorSubscriber;
754
+ }(Subscriber);
755
+
756
+ var ObjectUnsubscribedError = createErrorClass(function(_super) {
757
+ return function ObjectUnsubscribedErrorImpl() {
758
+ _super(this);
759
+ this.name = "ObjectUnsubscribedError";
760
+ this.message = "object unsubscribed";
761
+ };
762
+ });
763
+
764
+ var Subject = function(_super) {
765
+ __extends(Subject, _super);
766
+ function Subject() {
767
+ var _this = _super.call(this) || this;
768
+ _this.closed = false;
769
+ _this.currentObservers = null;
770
+ _this.observers = [];
771
+ _this.isStopped = false;
772
+ _this.hasError = false;
773
+ _this.thrownError = null;
774
+ return _this;
775
+ }
776
+ Subject.prototype.lift = function(operator) {
777
+ var subject = new AnonymousSubject(this, this);
778
+ subject.operator = operator;
779
+ return subject;
780
+ };
781
+ Subject.prototype._throwIfClosed = function() {
782
+ if (this.closed) {
783
+ throw new ObjectUnsubscribedError();
784
+ }
785
+ };
786
+ Subject.prototype.next = function(value) {
787
+ var _this = this;
788
+ errorContext(function() {
789
+ var e_1, _a;
790
+ _this._throwIfClosed();
791
+ if (!_this.isStopped) {
792
+ if (!_this.currentObservers) {
793
+ _this.currentObservers = Array.from(_this.observers);
794
+ }
795
+ try {
796
+ for(var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()){
797
+ var observer = _c.value;
798
+ observer.next(value);
799
+ }
800
+ } catch (e_1_1) {
801
+ e_1 = {
802
+ error: e_1_1
803
+ };
804
+ } finally{
805
+ try {
806
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
807
+ } finally{
808
+ if (e_1) throw e_1.error;
809
+ }
810
+ }
811
+ }
812
+ });
813
+ };
814
+ Subject.prototype.error = function(err) {
815
+ var _this = this;
816
+ errorContext(function() {
817
+ _this._throwIfClosed();
818
+ if (!_this.isStopped) {
819
+ _this.hasError = _this.isStopped = true;
820
+ _this.thrownError = err;
821
+ var observers = _this.observers;
822
+ while(observers.length){
823
+ observers.shift().error(err);
824
+ }
825
+ }
826
+ });
827
+ };
828
+ Subject.prototype.complete = function() {
829
+ var _this = this;
830
+ errorContext(function() {
831
+ _this._throwIfClosed();
832
+ if (!_this.isStopped) {
833
+ _this.isStopped = true;
834
+ var observers = _this.observers;
835
+ while(observers.length){
836
+ observers.shift().complete();
837
+ }
838
+ }
839
+ });
840
+ };
841
+ Subject.prototype.unsubscribe = function() {
842
+ this.isStopped = this.closed = true;
843
+ this.observers = this.currentObservers = null;
844
+ };
845
+ Object.defineProperty(Subject.prototype, "observed", {
846
+ get: function get() {
847
+ var _a;
848
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
849
+ },
850
+ enumerable: false,
851
+ configurable: true
852
+ });
853
+ Subject.prototype._trySubscribe = function(subscriber) {
854
+ this._throwIfClosed();
855
+ return _super.prototype._trySubscribe.call(this, subscriber);
856
+ };
857
+ Subject.prototype._subscribe = function(subscriber) {
858
+ this._throwIfClosed();
859
+ this._checkFinalizedStatuses(subscriber);
860
+ return this._innerSubscribe(subscriber);
861
+ };
862
+ Subject.prototype._innerSubscribe = function(subscriber) {
863
+ var _this = this;
864
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
865
+ if (hasError || isStopped) {
866
+ return EMPTY_SUBSCRIPTION;
867
+ }
868
+ this.currentObservers = null;
869
+ observers.push(subscriber);
870
+ return new Subscription(function() {
871
+ _this.currentObservers = null;
872
+ arrRemove(observers, subscriber);
873
+ });
874
+ };
875
+ Subject.prototype._checkFinalizedStatuses = function(subscriber) {
876
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
877
+ if (hasError) {
878
+ subscriber.error(thrownError);
879
+ } else if (isStopped) {
880
+ subscriber.complete();
881
+ }
882
+ };
883
+ Subject.prototype.asObservable = function() {
884
+ var observable = new Observable();
885
+ observable.source = this;
886
+ return observable;
887
+ };
888
+ Subject.create = function(destination, source) {
889
+ return new AnonymousSubject(destination, source);
890
+ };
891
+ return Subject;
892
+ }(Observable);
893
+ var AnonymousSubject = function(_super) {
894
+ __extends(AnonymousSubject, _super);
895
+ function AnonymousSubject(destination, source) {
896
+ var _this = _super.call(this) || this;
897
+ _this.destination = destination;
898
+ _this.source = source;
899
+ return _this;
900
+ }
901
+ AnonymousSubject.prototype.next = function(value) {
902
+ var _a, _b;
903
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
904
+ };
905
+ AnonymousSubject.prototype.error = function(err) {
906
+ var _a, _b;
907
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
908
+ };
909
+ AnonymousSubject.prototype.complete = function() {
910
+ var _a, _b;
911
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
912
+ };
913
+ AnonymousSubject.prototype._subscribe = function(subscriber) {
914
+ var _a, _b;
915
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
916
+ };
917
+ return AnonymousSubject;
918
+ }(Subject);
919
+
920
+ function filter(predicate, thisArg) {
921
+ return operate(function(source, subscriber) {
922
+ var index = 0;
923
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
924
+ return predicate.call(thisArg, value, index++) && subscriber.next(value);
925
+ }));
926
+ });
927
+ }
928
+
929
+ // request-context.ts
930
+ class RequestContext {
931
+ static currentRequestContext() {
932
+ const session = getRequestContext();
933
+ return session;
934
+ }
935
+ static currentRequest() {
936
+ const requestContext = RequestContext.currentRequestContext();
937
+ if (requestContext) {
938
+ return requestContext.request;
939
+ }
940
+ return null;
941
+ }
942
+ static currentTenantId() {
943
+ const user = RequestContext.currentUser();
944
+ if (user) {
945
+ return user.tenantId;
946
+ }
947
+ return null;
948
+ }
949
+ static currentUserId() {
950
+ const user = RequestContext.currentUser();
951
+ if (user) {
952
+ return user.id;
953
+ }
954
+ return null;
955
+ }
956
+ static currentRoleId() {
957
+ const user = RequestContext.currentUser();
958
+ if (user) {
959
+ return user.roleId;
960
+ }
961
+ return null;
962
+ }
963
+ static currentUser(throwError) {
964
+ const requestContext = RequestContext.currentRequestContext();
965
+ if (requestContext) {
966
+ // tslint:disable-next-line
967
+ const user = requestContext.request['user'];
968
+ if (user) {
969
+ return user;
970
+ }
971
+ }
972
+ if (throwError) {
973
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
974
+ }
975
+ return null;
976
+ }
977
+ static hasPermission(permission, throwError) {
978
+ return this.hasPermissions([
979
+ permission
980
+ ], throwError);
981
+ }
982
+ /**
983
+ * Retrieves the language code from the headers of the current request.
984
+ * @returns The language code (LanguagesEnum) extracted from the headers, or the default language (ENGLISH) if not found.
985
+ */ static getLanguageCode() {
986
+ // Retrieve the current request
987
+ const req = RequestContext.currentRequest();
988
+ // Variable to store the extracted language code
989
+ let lang;
990
+ // Check if a request exists
991
+ if (req) {
992
+ // Check if the 'language' header exists in the request
993
+ if (req.headers && req.headers['language']) {
994
+ // If found, set the lang variable
995
+ lang = req.headers['language'];
996
+ }
997
+ }
998
+ // Return the extracted language code or the default language (ENGLISH) if not found
999
+ return lang || contracts.LanguagesEnum.English;
1000
+ }
1001
+ static getOrganizationId() {
1002
+ const req = this.currentRequest();
1003
+ let organizationId;
1004
+ const keys = [
1005
+ 'organization-id'
1006
+ ];
1007
+ if (req) {
1008
+ for (const key of keys){
1009
+ if (req.headers && req.headers[key]) {
1010
+ organizationId = req.headers[key];
1011
+ break;
1012
+ }
1013
+ }
1014
+ }
1015
+ return organizationId;
1016
+ }
1017
+ static hasPermissions(findPermissions, throwError) {
1018
+ const requestContext = RequestContext.currentRequestContext();
1019
+ if (requestContext) {
1020
+ // tslint:disable-next-line
1021
+ const token = passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
1022
+ if (token) {
1023
+ const { permissions } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
1024
+ if (permissions) {
1025
+ const found = permissions.filter((value)=>findPermissions.indexOf(value) >= 0);
1026
+ if (found.length === findPermissions.length) {
1027
+ return true;
1028
+ }
1029
+ } else {
1030
+ return false;
1031
+ }
1032
+ }
1033
+ }
1034
+ if (throwError) {
1035
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
1036
+ }
1037
+ return false;
1038
+ }
1039
+ static hasAnyPermission(findPermissions, throwError) {
1040
+ const requestContext = RequestContext.currentRequestContext();
1041
+ if (requestContext) {
1042
+ // tslint:disable-next-line
1043
+ const token = passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
1044
+ if (token) {
1045
+ const { permissions } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
1046
+ const found = permissions.filter((value)=>findPermissions.indexOf(value) >= 0);
1047
+ if (found.length > 0) {
1048
+ return true;
1049
+ }
1050
+ }
1051
+ }
1052
+ if (throwError) {
1053
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
1054
+ }
1055
+ return false;
1056
+ }
1057
+ static currentToken(throwError) {
1058
+ const requestContext = RequestContext.currentRequestContext();
1059
+ if (requestContext) {
1060
+ // tslint:disable-next-line
1061
+ return passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
1062
+ }
1063
+ if (throwError) {
1064
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
1065
+ }
1066
+ return null;
1067
+ }
1068
+ /**
1069
+ * Checks if the current user has a specific role.
1070
+ * @param {RolesEnum} role - The role to check.
1071
+ * @param {boolean} throwError - Flag indicating whether to throw an error if the role is not granted.
1072
+ * @returns {boolean} - True if the user has the role, otherwise false.
1073
+ */ static hasRole(role, throwError) {
1074
+ return this.hasRoles([
1075
+ role
1076
+ ], throwError);
1077
+ }
1078
+ /**
1079
+ * Checks if the current request context has any of the specified roles.
1080
+ *
1081
+ * @param roles - An array of roles to check.
1082
+ * @param throwError - Whether to throw an error if no roles are found.
1083
+ * @returns True if any of the required roles are found, otherwise false.
1084
+ */ static hasRoles(roles, throwError) {
1085
+ const context = RequestContext.currentRequestContext();
1086
+ if (context) {
1087
+ try {
1088
+ // tslint:disable-next-line
1089
+ const token = this.currentToken();
1090
+ if (token) {
1091
+ const { role } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
1092
+ return roles.includes(role != null ? role : null);
1093
+ } else if (this.currentUser().role) {
1094
+ return roles.includes(this.currentUser().role.name);
1095
+ }
1096
+ } catch (error) {
1097
+ if (error instanceof jsonwebtoken.JsonWebTokenError) {
1098
+ return false;
1099
+ } else {
1100
+ throw error;
1101
+ }
1102
+ }
1103
+ }
1104
+ if (throwError) {
1105
+ throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
1106
+ }
1107
+ return false;
1108
+ }
1109
+ constructor(request, response, reqId, userId, extras = {}){
1110
+ this.request = request;
1111
+ this.response = response;
1112
+ this.reqId = reqId;
1113
+ this.userId = userId;
1114
+ this.extras = extras;
1115
+ }
1116
+ }
1117
+ const als = new node_async_hooks.AsyncLocalStorage();
1118
+ function getRequestContext() {
1119
+ return als.getStore();
1120
+ }
1121
+
1122
+ // request-context.middleware.ts
1123
+ exports.RequestContextMiddleware = class RequestContextMiddleware {
1124
+ use(req, _res, next) {
1125
+ var _req_user;
1126
+ const reqId = req.headers['x-request-id'] || node_crypto.randomUUID();
1127
+ // The userId can be placed in the authentication result here.
1128
+ const userId = (_req_user = req['user']) == null ? void 0 : _req_user['id'];
1129
+ const ctx = new RequestContext(req, _res, reqId, userId);
1130
+ als.run(ctx, next);
1131
+ }
1132
+ };
1133
+ exports.RequestContextMiddleware = __decorate([
1134
+ common.Injectable()
1135
+ ], exports.RequestContextMiddleware);
1136
+ function runWithRequestContext(req, res, next) {
1137
+ var _req_user;
1138
+ const reqId = req.headers['x-request-id'] || node_crypto.randomUUID();
1139
+ const userId = (_req_user = req['user']) == null ? void 0 : _req_user['id'];
1140
+ const ctx = new RequestContext(req, res, reqId, userId);
1141
+ // Enable ALS scope
1142
+ als.run(ctx, next);
1143
+ }
1144
+
1145
+ exports.StrategyBus = class StrategyBus {
1146
+ upsert(strategyType, entry) {
1147
+ this.subject.next({
1148
+ type: 'UPSERT',
1149
+ strategyType,
1150
+ entry
1151
+ });
1152
+ }
1153
+ remove(orgId, pluginName) {
1154
+ this.subject.next({
1155
+ type: 'REMOVE',
1156
+ orgId,
1157
+ pluginName
1158
+ });
1159
+ }
1160
+ constructor(){
1161
+ this.subject = new Subject();
1162
+ this.events$ = this.subject.asObservable();
1163
+ }
132
1164
  };
1165
+ exports.StrategyBus = __decorate([
1166
+ common.Injectable()
1167
+ ], exports.StrategyBus);
133
1168
 
134
1169
  class BaseStrategyRegistry {
135
1170
  onModuleInit() {
1171
+ this.bus.events$.pipe(filter((event)=>!event.strategyType || event.strategyType === this.strategyKey)).subscribe((evt)=>{
1172
+ this.logger.debug(`Received strategy bus event: ${JSON.stringify(evt)}`);
1173
+ if (evt.type === 'UPSERT') {
1174
+ this.upsert(evt.entry.instance);
1175
+ } else if (evt.type === 'REMOVE') {
1176
+ this.remove(evt.orgId, evt.pluginName);
1177
+ }
1178
+ });
136
1179
  const providers = this.discoveryService.getProviders();
137
1180
  for (const wrapper of providers){
138
1181
  const { instance } = wrapper;
139
1182
  if (!instance) continue;
140
- const type = this.reflector.get(this.strategyKey, instance.constructor);
141
- if (type) {
142
- this.strategies.set(type, instance);
1183
+ this.upsert(instance);
1184
+ }
1185
+ }
1186
+ upsert(instance) {
1187
+ const type = this.reflector.get(this.strategyKey, instance.constructor);
1188
+ if (type) {
1189
+ var _instance_metatype;
1190
+ const target = (_instance_metatype = instance.metatype) != null ? _instance_metatype : instance.constructor;
1191
+ var _this_reflector_get;
1192
+ const organizationId = (_this_reflector_get = this.reflector.get(ORGANIZATION_METADATA_KEY, target)) != null ? _this_reflector_get : GLOBAL_ORGANIZATION_SCOPE;
1193
+ var _this_strategies_get;
1194
+ const orgMap = (_this_strategies_get = this.strategies.get(organizationId)) != null ? _this_strategies_get : new Map();
1195
+ orgMap.set(type, instance);
1196
+ this.strategies.set(organizationId, orgMap);
1197
+ const pluginName = this.reflector.get(PLUGIN_METADATA_KEY, target);
1198
+ this.logger.debug(`Registered strategy of type ${type} for organization ${organizationId} from plugin ${pluginName}`);
1199
+ if (pluginName) {
1200
+ var _this_pluginStrategies_get;
1201
+ const pluginStrategies = (_this_pluginStrategies_get = this.pluginStrategies.get(pluginName)) != null ? _this_pluginStrategies_get : new Set();
1202
+ pluginStrategies.add(type);
1203
+ this.pluginStrategies.set(pluginName, pluginStrategies);
143
1204
  }
144
1205
  }
145
1206
  }
146
- get(type) {
147
- const strategy = this.strategies.get(type);
1207
+ /**
1208
+ * Remove all strategies registered by the given plugin for the given organization.
1209
+ */ remove(organizationId, pluginName) {
1210
+ const strategies = this.pluginStrategies.get(pluginName);
1211
+ const orgMap = this.strategies.get(organizationId);
1212
+ for (const type of strategies != null ? strategies : []){
1213
+ orgMap == null ? void 0 : orgMap.delete(type);
1214
+ }
1215
+ }
1216
+ /**
1217
+ * Resolve organization id, falling back to request context org or global scope.
1218
+ */ resolveOrganization(organizationId) {
1219
+ var _ref;
1220
+ return (_ref = organizationId != null ? organizationId : RequestContext.getOrganizationId()) != null ? _ref : GLOBAL_ORGANIZATION_SCOPE;
1221
+ }
1222
+ /**
1223
+ * Get strategy by type from the given organization including global strategies as fallback.
1224
+ *
1225
+ * @param type
1226
+ * @param organizationId
1227
+ * @returns
1228
+ */ get(type, organizationId) {
1229
+ var _this_strategies_get, _this_strategies_get1;
1230
+ organizationId != null ? organizationId : organizationId = RequestContext.getOrganizationId();
1231
+ const orgKey = this.resolveOrganization(organizationId);
1232
+ var _this_strategies_get_get;
1233
+ const strategy = (_this_strategies_get_get = (_this_strategies_get = this.strategies.get(orgKey)) == null ? void 0 : _this_strategies_get.get(type)) != null ? _this_strategies_get_get : orgKey === GLOBAL_ORGANIZATION_SCOPE ? undefined : (_this_strategies_get1 = this.strategies.get(GLOBAL_ORGANIZATION_SCOPE)) == null ? void 0 : _this_strategies_get1.get(type);
148
1234
  if (!strategy) {
149
1235
  throw new Error(`No strategy found for type ${type}`);
150
1236
  }
151
1237
  return strategy;
152
1238
  }
153
- list() {
154
- return Array.from(this.strategies.values());
1239
+ /**
1240
+ * List all strategies for the given organization including global strategies, or only global strategies if global org is specified.
1241
+ *
1242
+ * @param organizationId
1243
+ * @returns
1244
+ */ list(organizationId) {
1245
+ var _this_strategies_get, _this_strategies_get1;
1246
+ organizationId != null ? organizationId : organizationId = RequestContext.getOrganizationId();
1247
+ const orgKey = this.resolveOrganization(organizationId);
1248
+ var _this_strategies_get_values;
1249
+ const scoped = (_this_strategies_get_values = (_this_strategies_get = this.strategies.get(orgKey)) == null ? void 0 : _this_strategies_get.values()) != null ? _this_strategies_get_values : [];
1250
+ var _this_strategies_get_values1;
1251
+ const global = orgKey === GLOBAL_ORGANIZATION_SCOPE ? [] : (_this_strategies_get_values1 = (_this_strategies_get1 = this.strategies.get(GLOBAL_ORGANIZATION_SCOPE)) == null ? void 0 : _this_strategies_get1.values()) != null ? _this_strategies_get_values1 : [];
1252
+ return Array.from(new Set([
1253
+ ...scoped,
1254
+ ...global
1255
+ ]));
155
1256
  }
156
1257
  constructor(strategyKey, discoveryService, reflector){
157
1258
  this.strategyKey = strategyKey;
158
1259
  this.discoveryService = discoveryService;
159
1260
  this.reflector = reflector;
1261
+ this.logger = new common.Logger(BaseStrategyRegistry.name);
160
1262
  this.strategies = new Map();
1263
+ this.pluginStrategies = new Map();
161
1264
  }
162
1265
  }
1266
+ __decorate([
1267
+ common.Inject(exports.StrategyBus),
1268
+ __metadata("design:type", typeof exports.StrategyBus === "undefined" ? Object : exports.StrategyBus)
1269
+ ], BaseStrategyRegistry.prototype, "bus", void 0);
163
1270
 
164
1271
  exports.IntegrationStrategyRegistry = class IntegrationStrategyRegistry extends BaseStrategyRegistry {
165
1272
  constructor(discoveryService, reflector){
@@ -176,7 +1283,7 @@ exports.IntegrationStrategyRegistry = __decorate([
176
1283
  ], exports.IntegrationStrategyRegistry);
177
1284
 
178
1285
  const WORKFLOW_TRIGGER_STRATEGY = 'WORKFLOW_TRIGGER_STRATEGY';
179
- const WorkflowTriggerStrategy = (provider)=>common.SetMetadata(WORKFLOW_TRIGGER_STRATEGY, provider);
1286
+ const WorkflowTriggerStrategy = (provider)=>common.applyDecorators(common.SetMetadata(WORKFLOW_TRIGGER_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, WORKFLOW_TRIGGER_STRATEGY));
180
1287
 
181
1288
  exports.WorkflowTriggerRegistry = class WorkflowTriggerRegistry extends BaseStrategyRegistry {
182
1289
  constructor(discoveryService, reflector){
@@ -195,7 +1302,7 @@ exports.WorkflowTriggerRegistry = __decorate([
195
1302
  const WORKFLOW_NODE_STRATEGY = 'WORKFLOW_NODE_STRATEGY';
196
1303
  /**
197
1304
  * Decorator to mark a provider as a Workflow Node Strategy
198
- */ const WorkflowNodeStrategy = (provider)=>common.SetMetadata(WORKFLOW_NODE_STRATEGY, provider);
1305
+ */ const WorkflowNodeStrategy = (provider)=>common.applyDecorators(common.SetMetadata(WORKFLOW_NODE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, WORKFLOW_NODE_STRATEGY));
199
1306
 
200
1307
  exports.WorkflowNodeRegistry = class WorkflowNodeRegistry extends BaseStrategyRegistry {
201
1308
  constructor(discoveryService, reflector){
@@ -223,7 +1330,7 @@ exports.WorkflowNodeRegistry = __decorate([
223
1330
  WrapWorkflowNodeExecutionCommand.type = '[Workflow] Wrap Workflow Node Execution';
224
1331
 
225
1332
  const VECTOR_STORE_STRATEGY = 'VECTOR_STORE_STRATEGY';
226
- const VectorStoreStrategy = (provider)=>common.SetMetadata(VECTOR_STORE_STRATEGY, provider);
1333
+ const VectorStoreStrategy = (provider)=>common.applyDecorators(common.SetMetadata(VECTOR_STORE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, VECTOR_STORE_STRATEGY));
227
1334
 
228
1335
  exports.VectorStoreRegistry = class VectorStoreRegistry extends BaseStrategyRegistry {
229
1336
  constructor(discoveryService, reflector){
@@ -240,7 +1347,7 @@ exports.VectorStoreRegistry = __decorate([
240
1347
  ], exports.VectorStoreRegistry);
241
1348
 
242
1349
  const TEXT_SPLITTER_STRATEGY = 'TEXT_SPLITTER_STRATEGY';
243
- const TextSplitterStrategy = (provider)=>common.SetMetadata(TEXT_SPLITTER_STRATEGY, provider);
1350
+ const TextSplitterStrategy = (provider)=>common.applyDecorators(common.SetMetadata(TEXT_SPLITTER_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, TEXT_SPLITTER_STRATEGY));
244
1351
 
245
1352
  exports.TextSplitterRegistry = class TextSplitterRegistry extends BaseStrategyRegistry {
246
1353
  constructor(discoveryService, reflector){
@@ -259,7 +1366,7 @@ exports.TextSplitterRegistry = __decorate([
259
1366
  const DOCUMENT_SOURCE_STRATEGY = 'DOCUMENT_SOURCE_STRATEGY';
260
1367
  /**
261
1368
  * Decorator to mark a provider as a Document Source Strategy
262
- */ const DocumentSourceStrategy = (provider)=>common.SetMetadata(DOCUMENT_SOURCE_STRATEGY, provider);
1369
+ */ const DocumentSourceStrategy = (provider)=>common.applyDecorators(common.SetMetadata(DOCUMENT_SOURCE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, DOCUMENT_SOURCE_STRATEGY));
263
1370
 
264
1371
  exports.DocumentSourceRegistry = class DocumentSourceRegistry extends BaseStrategyRegistry {
265
1372
  constructor(discoveryService, reflector){
@@ -278,7 +1385,7 @@ exports.DocumentSourceRegistry = __decorate([
278
1385
  const DOCUMENT_TRANSFORMER_STRATEGY = 'DOCUMENT_TRANSFORMER_STRATEGY';
279
1386
  /**
280
1387
  * Decorator to mark a provider as a Document Transformer Strategy
281
- */ const DocumentTransformerStrategy = (provider)=>common.SetMetadata(DOCUMENT_TRANSFORMER_STRATEGY, provider);
1388
+ */ const DocumentTransformerStrategy = (provider)=>common.applyDecorators(common.SetMetadata(DOCUMENT_TRANSFORMER_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, DOCUMENT_TRANSFORMER_STRATEGY));
282
1389
 
283
1390
  exports.DocumentTransformerRegistry = class DocumentTransformerRegistry extends BaseStrategyRegistry {
284
1391
  constructor(discoveryService, reflector){
@@ -297,7 +1404,7 @@ exports.DocumentTransformerRegistry = __decorate([
297
1404
  const RETRIEVER_STRATEGY = 'RETRIEVER_STRATEGY';
298
1405
  /**
299
1406
  * Decorator to mark a provider as a Retriever Strategy
300
- */ const RetrieverStrategy = (provider)=>common.SetMetadata(RETRIEVER_STRATEGY, provider);
1407
+ */ const RetrieverStrategy = (provider)=>common.applyDecorators(common.SetMetadata(RETRIEVER_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, RETRIEVER_STRATEGY));
301
1408
 
302
1409
  exports.RetrieverRegistry = class RetrieverRegistry extends BaseStrategyRegistry {
303
1410
  constructor(discoveryService, reflector){
@@ -372,7 +1479,7 @@ async function downloadRemoteFile(url, dest) {
372
1479
  const IMAGE_UNDERSTANDING_STRATEGY = 'IMAGE_UNDERSTANDING_STRATEGY';
373
1480
  /**
374
1481
  * Decorator to mark a provider as an Image Understanding Strategy
375
- */ const ImageUnderstandingStrategy = (provider)=>common.SetMetadata(IMAGE_UNDERSTANDING_STRATEGY, provider);
1482
+ */ const ImageUnderstandingStrategy = (provider)=>common.applyDecorators(common.SetMetadata(IMAGE_UNDERSTANDING_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, IMAGE_UNDERSTANDING_STRATEGY));
376
1483
 
377
1484
  exports.ImageUnderstandingRegistry = class ImageUnderstandingRegistry extends BaseStrategyRegistry {
378
1485
  constructor(discoveryService, reflector){
@@ -389,7 +1496,7 @@ exports.ImageUnderstandingRegistry = __decorate([
389
1496
  ], exports.ImageUnderstandingRegistry);
390
1497
 
391
1498
  const KNOWLEDGE_STRATEGY = 'KNOWLEDGE_STRATEGY';
392
- const KnowledgeStrategyKey = (provider)=>common.SetMetadata(KNOWLEDGE_STRATEGY, provider);
1499
+ const KnowledgeStrategyKey = (provider)=>common.applyDecorators(common.SetMetadata(KNOWLEDGE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, KNOWLEDGE_STRATEGY));
393
1500
 
394
1501
  exports.KnowledgeStrategyRegistry = class KnowledgeStrategyRegistry extends BaseStrategyRegistry {
395
1502
  constructor(discoveryService, reflector){
@@ -408,7 +1515,7 @@ exports.KnowledgeStrategyRegistry = __decorate([
408
1515
  const TOOLSET_STRATEGY = 'TOOLSET_STRATEGY';
409
1516
  /**
410
1517
  * Decorator to mark a provider as a Toolset Strategy
411
- */ const ToolsetStrategy = (provider)=>common.SetMetadata(TOOLSET_STRATEGY, provider);
1518
+ */ const ToolsetStrategy = (provider)=>common.applyDecorators(common.SetMetadata(TOOLSET_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, TOOLSET_STRATEGY));
412
1519
 
413
1520
  exports.ToolsetRegistry = class ToolsetRegistry extends BaseStrategyRegistry {
414
1521
  constructor(discoveryService, reflector){
@@ -712,224 +1819,8 @@ function getErrorMessage(err) {
712
1819
  return error;
713
1820
  }
714
1821
 
715
- // request-context.ts
716
- class RequestContext {
717
- static currentRequestContext() {
718
- const session = getRequestContext();
719
- return session;
720
- }
721
- static currentRequest() {
722
- const requestContext = RequestContext.currentRequestContext();
723
- if (requestContext) {
724
- return requestContext.request;
725
- }
726
- return null;
727
- }
728
- static currentTenantId() {
729
- const user = RequestContext.currentUser();
730
- if (user) {
731
- return user.tenantId;
732
- }
733
- return null;
734
- }
735
- static currentUserId() {
736
- const user = RequestContext.currentUser();
737
- if (user) {
738
- return user.id;
739
- }
740
- return null;
741
- }
742
- static currentRoleId() {
743
- const user = RequestContext.currentUser();
744
- if (user) {
745
- return user.roleId;
746
- }
747
- return null;
748
- }
749
- static currentUser(throwError) {
750
- const requestContext = RequestContext.currentRequestContext();
751
- if (requestContext) {
752
- // tslint:disable-next-line
753
- const user = requestContext.request['user'];
754
- if (user) {
755
- return user;
756
- }
757
- }
758
- if (throwError) {
759
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
760
- }
761
- return null;
762
- }
763
- static hasPermission(permission, throwError) {
764
- return this.hasPermissions([
765
- permission
766
- ], throwError);
767
- }
768
- /**
769
- * Retrieves the language code from the headers of the current request.
770
- * @returns The language code (LanguagesEnum) extracted from the headers, or the default language (ENGLISH) if not found.
771
- */ static getLanguageCode() {
772
- // Retrieve the current request
773
- const req = RequestContext.currentRequest();
774
- // Variable to store the extracted language code
775
- let lang;
776
- // Check if a request exists
777
- if (req) {
778
- // Check if the 'language' header exists in the request
779
- if (req.headers && req.headers['language']) {
780
- // If found, set the lang variable
781
- lang = req.headers['language'];
782
- }
783
- }
784
- // Return the extracted language code or the default language (ENGLISH) if not found
785
- return lang || contracts.LanguagesEnum.English;
786
- }
787
- static getOrganizationId() {
788
- const req = this.currentRequest();
789
- let organizationId;
790
- const keys = [
791
- 'organization-id'
792
- ];
793
- if (req) {
794
- for (const key of keys){
795
- if (req.headers && req.headers[key]) {
796
- organizationId = req.headers[key];
797
- break;
798
- }
799
- }
800
- }
801
- return organizationId;
802
- }
803
- static hasPermissions(findPermissions, throwError) {
804
- const requestContext = RequestContext.currentRequestContext();
805
- if (requestContext) {
806
- // tslint:disable-next-line
807
- const token = passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
808
- if (token) {
809
- const { permissions } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
810
- if (permissions) {
811
- const found = permissions.filter((value)=>findPermissions.indexOf(value) >= 0);
812
- if (found.length === findPermissions.length) {
813
- return true;
814
- }
815
- } else {
816
- return false;
817
- }
818
- }
819
- }
820
- if (throwError) {
821
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
822
- }
823
- return false;
824
- }
825
- static hasAnyPermission(findPermissions, throwError) {
826
- const requestContext = RequestContext.currentRequestContext();
827
- if (requestContext) {
828
- // tslint:disable-next-line
829
- const token = passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
830
- if (token) {
831
- const { permissions } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
832
- const found = permissions.filter((value)=>findPermissions.indexOf(value) >= 0);
833
- if (found.length > 0) {
834
- return true;
835
- }
836
- }
837
- }
838
- if (throwError) {
839
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
840
- }
841
- return false;
842
- }
843
- static currentToken(throwError) {
844
- const requestContext = RequestContext.currentRequestContext();
845
- if (requestContext) {
846
- // tslint:disable-next-line
847
- return passportJwt.ExtractJwt.fromAuthHeaderAsBearerToken()(requestContext.request);
848
- }
849
- if (throwError) {
850
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
851
- }
852
- return null;
853
- }
854
- /**
855
- * Checks if the current user has a specific role.
856
- * @param {RolesEnum} role - The role to check.
857
- * @param {boolean} throwError - Flag indicating whether to throw an error if the role is not granted.
858
- * @returns {boolean} - True if the user has the role, otherwise false.
859
- */ static hasRole(role, throwError) {
860
- return this.hasRoles([
861
- role
862
- ], throwError);
863
- }
864
- /**
865
- * Checks if the current request context has any of the specified roles.
866
- *
867
- * @param roles - An array of roles to check.
868
- * @param throwError - Whether to throw an error if no roles are found.
869
- * @returns True if any of the required roles are found, otherwise false.
870
- */ static hasRoles(roles, throwError) {
871
- const context = RequestContext.currentRequestContext();
872
- if (context) {
873
- try {
874
- // tslint:disable-next-line
875
- const token = this.currentToken();
876
- if (token) {
877
- const { role } = jsonwebtoken.verify(token, process.env['JWT_SECRET']);
878
- return roles.includes(role != null ? role : null);
879
- } else if (this.currentUser().role) {
880
- return roles.includes(this.currentUser().role.name);
881
- }
882
- } catch (error) {
883
- if (error instanceof jsonwebtoken.JsonWebTokenError) {
884
- return false;
885
- } else {
886
- throw error;
887
- }
888
- }
889
- }
890
- if (throwError) {
891
- throw new common.HttpException('Unauthorized', common.HttpStatus.UNAUTHORIZED);
892
- }
893
- return false;
894
- }
895
- constructor(request, response, reqId, userId, extras = {}){
896
- this.request = request;
897
- this.response = response;
898
- this.reqId = reqId;
899
- this.userId = userId;
900
- this.extras = extras;
901
- }
902
- }
903
- const als = new node_async_hooks.AsyncLocalStorage();
904
- function getRequestContext() {
905
- return als.getStore();
906
- }
907
-
908
- // request-context.middleware.ts
909
- exports.RequestContextMiddleware = class RequestContextMiddleware {
910
- use(req, _res, next) {
911
- var _req_user;
912
- const reqId = req.headers['x-request-id'] || node_crypto.randomUUID();
913
- // The userId can be placed in the authentication result here.
914
- const userId = (_req_user = req['user']) == null ? void 0 : _req_user['id'];
915
- const ctx = new RequestContext(req, _res, reqId, userId);
916
- als.run(ctx, next);
917
- }
918
- };
919
- exports.RequestContextMiddleware = __decorate([
920
- common.Injectable()
921
- ], exports.RequestContextMiddleware);
922
- function runWithRequestContext(req, res, next) {
923
- var _req_user;
924
- const reqId = req.headers['x-request-id'] || node_crypto.randomUUID();
925
- const userId = (_req_user = req['user']) == null ? void 0 : _req_user['id'];
926
- const ctx = new RequestContext(req, res, reqId, userId);
927
- // Enable ALS scope
928
- als.run(ctx, next);
929
- }
930
-
931
1822
  const DATASOURCE_STRATEGY = 'DATASOURCE_STRATEGY';
932
- const DataSourceStrategy = (provider)=>common.SetMetadata(DATASOURCE_STRATEGY, provider);
1823
+ const DataSourceStrategy = (provider)=>common.applyDecorators(common.SetMetadata(DATASOURCE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, DATASOURCE_STRATEGY));
933
1824
 
934
1825
  exports.DataSourceStrategyRegistry = class DataSourceStrategyRegistry extends BaseStrategyRegistry {
935
1826
  constructor(discoveryService, reflector){
@@ -1242,6 +2133,7 @@ function AIModelProviderStrategy(provider) {
1242
2133
  }
1243
2134
  const dir = file ? path.dirname(file) : process.cwd();
1244
2135
  return function(target) {
2136
+ common.SetMetadata(STRATEGY_META_KEY, AI_MODEL_PROVIDER)(target);
1245
2137
  // Ensure NestJS is discoverable
1246
2138
  common.SetMetadata(AI_MODEL_PROVIDER, provider)(target);
1247
2139
  // Write custom path (does not affect Discovery)
@@ -2160,7 +3052,7 @@ class Speech2TextChatModel extends chat_models.BaseChatModel {
2160
3052
  CreateModelClientCommand.type = '[AI Model] Create Model Client';
2161
3053
 
2162
3054
  const AGENT_MIDDLEWARE_STRATEGY = 'AGENT_MIDDLEWARE_STRATEGY';
2163
- const AgentMiddlewareStrategy = (provider)=>common.SetMetadata(AGENT_MIDDLEWARE_STRATEGY, provider);
3055
+ const AgentMiddlewareStrategy = (provider)=>common.applyDecorators(common.SetMetadata(AGENT_MIDDLEWARE_STRATEGY, provider), common.SetMetadata(STRATEGY_META_KEY, AGENT_MIDDLEWARE_STRATEGY));
2164
3056
 
2165
3057
  exports.AgentMiddlewareRegistry = class AgentMiddlewareRegistry extends BaseStrategyRegistry {
2166
3058
  constructor(discoveryService, reflector){
@@ -2210,6 +3102,7 @@ exports.AiModelNotFoundException = AiModelNotFoundException;
2210
3102
  exports.BaseHTTPQueryRunner = BaseHTTPQueryRunner;
2211
3103
  exports.BaseQueryRunner = BaseQueryRunner;
2212
3104
  exports.BaseSQLQueryRunner = BaseSQLQueryRunner;
3105
+ exports.BaseStrategyRegistry = BaseStrategyRegistry;
2213
3106
  exports.BaseTool = BaseTool;
2214
3107
  exports.BaseToolset = BaseToolset;
2215
3108
  exports.BuiltinToolset = BuiltinToolset;
@@ -2223,6 +3116,7 @@ exports.DOCUMENT_TRANSFORMER_STRATEGY = DOCUMENT_TRANSFORMER_STRATEGY;
2223
3116
  exports.DataSourceStrategy = DataSourceStrategy;
2224
3117
  exports.DocumentSourceStrategy = DocumentSourceStrategy;
2225
3118
  exports.DocumentTransformerStrategy = DocumentTransformerStrategy;
3119
+ exports.GLOBAL_ORGANIZATION_SCOPE = GLOBAL_ORGANIZATION_SCOPE;
2226
3120
  exports.IMAGE_UNDERSTANDING_STRATEGY = IMAGE_UNDERSTANDING_STRATEGY;
2227
3121
  exports.INTEGRATION_STRATEGY = INTEGRATION_STRATEGY;
2228
3122
  exports.ImageUnderstandingStrategy = ImageUnderstandingStrategy;
@@ -2232,8 +3126,10 @@ exports.KNOWLEDGE_STRATEGY = KNOWLEDGE_STRATEGY;
2232
3126
  exports.KnowledgeStrategyKey = KnowledgeStrategyKey;
2233
3127
  exports.LLMUsage = LLMUsage;
2234
3128
  exports.LargeLanguageModel = LargeLanguageModel;
3129
+ exports.ORGANIZATION_METADATA_KEY = ORGANIZATION_METADATA_KEY;
2235
3130
  exports.OpenAICompatibleReranker = OpenAICompatibleReranker;
2236
3131
  exports.PLUGIN_METADATA = PLUGIN_METADATA;
3132
+ exports.PLUGIN_METADATA_KEY = PLUGIN_METADATA_KEY;
2237
3133
  exports.PROVIDE_AI_MODEL_LLM = PROVIDE_AI_MODEL_LLM;
2238
3134
  exports.PROVIDE_AI_MODEL_MODERATION = PROVIDE_AI_MODEL_MODERATION;
2239
3135
  exports.PROVIDE_AI_MODEL_RERANK = PROVIDE_AI_MODEL_RERANK;
@@ -2244,6 +3140,7 @@ exports.RETRIEVER_STRATEGY = RETRIEVER_STRATEGY;
2244
3140
  exports.RequestContext = RequestContext;
2245
3141
  exports.RerankModel = RerankModel;
2246
3142
  exports.RetrieverStrategy = RetrieverStrategy;
3143
+ exports.STRATEGY_META_KEY = STRATEGY_META_KEY;
2247
3144
  exports.Speech2TextChatModel = Speech2TextChatModel;
2248
3145
  exports.SpeechToTextModel = SpeechToTextModel;
2249
3146
  exports.TEXT_SPLITTER_STRATEGY = TEXT_SPLITTER_STRATEGY;