UNPKG

@kephas/angular

Version:

Provides integration capabilities with Angular.

1,191 lines (1,179 loc) 55.2 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/forms'), require('@kephas/core'), require('@kephas/ui'), require('@angular/common/http'), require('reflect-metadata'), require('@kephas/commands'), require('rxjs/operators'), require('@kephas/messaging')) : typeof define === 'function' && define.amd ? define('@kephas/angular', ['exports', '@angular/core', '@angular/forms', '@kephas/core', '@kephas/ui', '@angular/common/http', 'reflect-metadata', '@kephas/commands', 'rxjs/operators', '@kephas/messaging'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.kephas = global.kephas || {}, global.kephas.angular = {}), global.ng.core, global.ng.forms, global['@kephas/core'], global['@kephas/ui'], global.ng.common.http, null, global['@kephas/commands'], global.rxjs.operators, global['@kephas/messaging'])); }(this, (function (exports, i0, forms, core, ui, i2, reflectMetadata, commands, operators, messaging) { 'use strict'; /** * Provides base functionality for a widget. * * @export * @class WidgetBase */ var WidgetBase = /** @class */ (function () { /** * Creates an instance of WidgetBase. * @param {ElementRef} elementRef The element reference. * @param {ViewContainerRef} viewContainerRef The view container reference. * @memberof WidgetBase */ function WidgetBase(elementRef, viewContainerRef) { this.elementRef = elementRef; this.viewContainerRef = viewContainerRef; this._isVisible = true; this._readonly = false; var injector = viewContainerRef.injector; this.logger = injector.get(core.Logger); this.notification = injector.get(ui.Notification); this.changeDetector = injector.get(i0.ChangeDetectorRef); } Object.defineProperty(WidgetBase.prototype, "childWidgets", { /** * Gets or sets the child editors query. * * @readonly * @type {QueryList<EditorBase<any>>} * @memberof EditorBase */ get: function () { return this._childWidgets; }, set: function (value) { if (this._childWidgets === value) { return; } var oldValue = this._childWidgets; this._childWidgets = value; this.onChildWidgetsChanged(oldValue, value); }, enumerable: false, configurable: true }); Object.defineProperty(WidgetBase.prototype, "isVisible", { /** * Gets or sets a value indicating whether the widget is visible. * * @readonly * @type {boolean} * @memberof WidgetBase */ get: function () { return this._isVisible; }, set: function (value) { if (this._isVisible === value) { return; } this._isVisible = value; }, enumerable: false, configurable: true }); Object.defineProperty(WidgetBase.prototype, "readonly", { /** * Gets or sets a value indicating whether the editor allows edits or not. * * @readonly * @type {boolean} * @memberof EditorBase */ get: function () { return this._readonly; }, set: function (value) { if (this._readonly === value) { return; } var oldValue = this._readonly; this._readonly = value; this.onReadOnlyChanged(oldValue, value); }, enumerable: false, configurable: true }); /** * A callback method that is invoked immediately after the * default change detector has checked the directive's * data-bound properties for the first time, * and before any of the view or content children have been checked. * It is invoked only once when the directive is instantiated. * * @memberof WidgetBase */ WidgetBase.prototype.ngOnInit = function () { }; /** * A callback method that is invoked immediately after * Angular has completed initialization of a component's view. * It is invoked only once when the view is instantiated. * * @memberof WidgetBase */ WidgetBase.prototype.ngAfterViewInit = function () { }; /** * A callback method that is invoked immediately after the * default change detector has checked data-bound properties * if at least one has changed, and before the view and content * children are checked. * * @param changes The changed properties. * @memberof WidgetBase */ WidgetBase.prototype.ngOnChanges = function (changes) { }; /** * A callback method that performs custom clean-up, invoked immediately * after a directive, pipe, or service instance is destroyed. */ WidgetBase.prototype.ngOnDestroy = function () { }; /** * When overridden in a derived class, this method is called when the read only state changes. * * @protected * @param {boolean} oldValue The old value. * @param {boolean} newValue The new value. * * @memberof WidgetBase */ WidgetBase.prototype.onReadOnlyChanged = function (oldValue, newValue) { }; /** * When overridden in a derived class, this method is called when the child widgets query changed. * * @protected * @param {QueryList<EditorBase<any>>} oldValue The old query. * @param {QueryList<EditorBase<any>>} newValue The new query. * * @memberof EditorBase */ WidgetBase.prototype.onChildWidgetsChanged = function (oldValue, newValue) { }; return WidgetBase; }()); WidgetBase.decorators = [ { type: i0.Component, args: [{ template: '' },] } ]; WidgetBase.ctorParameters = function () { return [ { type: i0.ElementRef }, { type: i0.ViewContainerRef } ]; }; WidgetBase.propDecorators = { childWidgets: [{ type: i0.ViewChildren, args: [WidgetBase,] }], isVisible: [{ type: i0.Input }], readonly: [{ type: i0.Input }] }; /** * This function provides the component as a WidgetBase, * to be able to import it over this base class instead of over its own class. * * For example, use it as @ViewChild(WidgetBase) or @ViewChildren(WidgetBase). * * @export * @param {Type<any>} componentType The component type. * @returns {Provider} The provider. */ function provideWidget(componentType) { return { provide: WidgetBase, useExisting: i0.forwardRef(function () { return componentType; }) }; } /** * This function provides the component as a NG_VALUE_ACCESSOR. * Thus, it is possible to bind it like this: * <my-component [(ngModel)]="boundProperty"></my-component> * * @export * @param {Type<any>} componentType The component type. * @returns {Provider} The provider. */ function provideValueAccessor(componentType) { return { provide: forms.NG_VALUE_ACCESSOR, useExisting: i0.forwardRef(function () { return componentType; }), multi: true }; } /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 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; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } }); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } ; function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } /** * Provides a base implementation for value editors. * * @export * @abstract * @class ValueEditorBase * @implements {OnInit} * @implements {AfterViewInit} * @implements {ControlValueAccessor} * @template TValue The value type. */ var ValueEditorBase = /** @class */ (function (_super) { __extends(ValueEditorBase, _super); /** * Creates an instance of ValueEditorBase. * * @param {ElementRef} elementRef The element reference. * @param {ViewContainerRef} viewContainerRef The view container reference. * @memberof ValueEditorBase */ function ValueEditorBase(elementRef, viewContainerRef) { var _this = _super.call(this, elementRef, viewContainerRef) || this; /** * Gets or sets a value indicating whether the value is changed from the change event. * * @protected * @memberof ValueEditorBase */ _this.valueChangeFromEvent = false; /** * Gets or sets a value indicating whether the value is changed from the value property. * * @protected * @memberof ValueEditorBase */ _this.valueChangeFromValue = false; _this._onChange = function (_) { // The implementation will get overwritten by Angular in RegisterOnChange. }; _this._onTouched = function () { // The implementation will get overwritten by Angular in RegisterOnTouched. }; return _this; } Object.defineProperty(ValueEditorBase.prototype, "value", { /** * Gets or sets the value to edit. * * @type {TValue} * @memberOf ValueEditorBase */ get: function () { return this.getEditorValue(); }, set: function (value) { if (this._valueBeforeChange === value) { return; } this.updateEditor(value); }, enumerable: false, configurable: true }); /** * Updates the underlying editor with the provided value. * * @protected * @param {TValue} value * @returns {boolean} * @memberof ValueEditorBase */ ValueEditorBase.prototype.updateEditor = function (value) { if (this.valueChangeFromValue) { return false; } var prevValueChangeFromValue = this.valueChangeFromValue; this.valueChangeFromValue = true; try { var oldValue = this._valueBeforeChange; this.onValueChanging(oldValue, value); this._valueBeforeChange = value; if (!this.valueChangeFromEvent) { this.setEditorValue(value); value = this.getEditorValue(); } this.onValueChanged(oldValue, value); } catch (error) { this.logger.error(error, 'Error while updating the editor.'); throw error; } finally { this.valueChangeFromValue = prevValueChangeFromValue; } return true; }; /** * Overridable method invoked when the value is about to be changed. * * @protected * @param {(TValue | undefined)} oldValue The old value. * @param {(TValue | undefined)} newValue The new value. * @memberof ValueEditorBase */ ValueEditorBase.prototype.onValueChanging = function (oldValue, newValue) { }; /** * Overridable method invoked after the value was changed. * * @protected * @param {(TValue | undefined)} oldValue The old value. * @param {(TValue | undefined)} newValue The new value. * @memberof ValueEditorBase */ ValueEditorBase.prototype.onValueChanged = function (oldValue, newValue) { this._onChange(newValue); }; /** * Callback invoked from the change event of the underlying editor. * * @protected * @param {*} e * @returns * @memberof PropertyEditorComponent */ ValueEditorBase.prototype.onEditorChange = function (e) { if (this.valueChangeFromValue) { return; } var prevValueChangeFromEvent = this.valueChangeFromEvent; this.valueChangeFromEvent = true; try { var newValue = this.getEditorValueOnChange(e); this.value = newValue; } catch (error) { this.notification.notifyError(error); } finally { this.valueChangeFromEvent = prevValueChangeFromEvent; } }; /** * Gets the underlying editor's value upon change. * * @protected * @param {*} e The change event arguments. * @returns {TValue} The widget value. * @memberof ValueEditorBase */ ValueEditorBase.prototype.getEditorValueOnChange = function (e) { return this.getEditorValue(); }; /** * Write a new value to the element. * * @param {*} obj The new value. * * @memberOf PropertyEditorComponent */ ValueEditorBase.prototype.writeValue = function (obj) { this.value = obj; }; /** * Set the function to be called when the control receives a change event. * * @param {*} fn The callback function. * * @memberOf PropertyEditorComponent */ ValueEditorBase.prototype.registerOnChange = function (fn) { this._onChange = fn; }; /** * Set the function to be called when the control receives a touch event. * * @param {*} fn The callback function. * * @memberOf PropertyEditorComponent */ ValueEditorBase.prototype.registerOnTouched = function (fn) { this._onTouched = fn; }; /** * This function is called when the control status changes to or from "DISABLED". * Depending on the value, it will enable or disable the appropriate DOM element. * * @param {boolean} isDisabled True if the state is disabled. * * @memberOf PropertyEditorComponent */ ValueEditorBase.prototype.setDisabledState = function (isDisabled) { }; return ValueEditorBase; }(WidgetBase)); ValueEditorBase.decorators = [ { type: i0.Component, args: [{ template: '' },] } ]; ValueEditorBase.ctorParameters = function () { return [ { type: i0.ElementRef }, { type: i0.ViewContainerRef } ]; }; ValueEditorBase.propDecorators = { value: [{ type: i0.Input }] }; /** * Base class for HTTP interceptors. * * @export * @extends {AngularHttpInterceptor} */ exports.HttpInterceptor = /** @class */ (function () { function HttpInterceptor() { } return HttpInterceptor; }()); exports.HttpInterceptor = __decorate([ core.SingletonAppServiceContract({ allowMultiple: true, contractToken: i2.HTTP_INTERCEPTORS }) ], exports.HttpInterceptor); core.SingletonAppServiceContract()(i2.XhrFactory); core.AppServiceContract()(i2.HttpBackend); core.AppServiceContract()(i0.Injector); core.AppServiceContract()(i2.HttpXhrBackend); core.AppService({ overridePriority: core.Priority.Low })(i2.HttpXhrBackend); // tslint:disable: max-classes-per-file /** * Browser implementation for an `XhrFactory`. * * @export * @class BrowserXhrFactory * @implements {XhrFactory} */ var BrowserXhrFactory = /** @class */ (function () { function BrowserXhrFactory() { } BrowserXhrFactory.prototype.build = function () { return new XMLHttpRequest(); }; return BrowserXhrFactory; }()); /** * `HttpHandler` which applies an `HttpInterceptor` to an `HttpRequest`. * * */ var HttpInterceptorHandler = /** @class */ (function () { function HttpInterceptorHandler(next, interceptor) { this.next = next; this.interceptor = interceptor; } HttpInterceptorHandler.prototype.handle = function (req) { return this.interceptor.intercept(req, this.next); }; return HttpInterceptorHandler; }()); /** * An injectable `HttpHandler` that applies multiple interceptors * to a request before passing it to the given `HttpBackend`. * * The interceptors are loaded lazily from the injector, to allow * interceptors to themselves inject classes depending indirectly * on `HttpInterceptingHandler` itself. * @see `HttpInterceptor` */ var HttpInterceptingHandler = /** @class */ (function () { /** * Creates an instance of HttpInterceptingHandler. * @param {HttpBackend} backend * @param {Injector} injector * @memberof HttpInterceptingHandler */ function HttpInterceptingHandler(backend, injector) { this.backend = backend; this.injector = injector; this.chain = null; } HttpInterceptingHandler.prototype.handle = function (req) { if (this.chain === null) { var interceptors = this.injector.get(i2.HTTP_INTERCEPTORS, []); this.chain = interceptors.reduceRight(function (next, interceptor) { return new HttpInterceptorHandler(next, interceptor); }, this.backend); } return this.chain.handle(req); }; return HttpInterceptingHandler; }()); HttpInterceptingHandler.ɵprov = i0.ɵɵdefineInjectable({ factory: function HttpInterceptingHandler_Factory() { return new HttpInterceptingHandler(i0.ɵɵinject(i2.HttpBackend), i0.ɵɵinject(i0.INJECTOR)); }, token: HttpInterceptingHandler, providedIn: "root" }); HttpInterceptingHandler.decorators = [ { type: i0.Injectable, args: [{ providedIn: 'root' },] } ]; HttpInterceptingHandler.ctorParameters = function () { return [ { type: i2.HttpBackend }, { type: i0.Injector } ]; }; /** * Registry for HTTP client services. * * @export * @class HttpClientAppServiceInfoRegistry */ var HttpClientAppServiceInfoRegistry = /** @class */ (function () { function HttpClientAppServiceInfoRegistry() { } /** * Gets the providers for the HTTP client. * * @returns {((StaticClassProvider | ExistingProvider)[])} * @memberof HttpClientAppServiceInfoRegistry */ HttpClientAppServiceInfoRegistry.prototype.getHttpClientProviders = function () { return [ { provide: i2.HttpClient, useClass: i2.HttpClient, deps: [i2.HttpHandler] }, { provide: i2.HttpHandler, useClass: HttpInterceptingHandler, deps: [i2.HttpBackend, i0.Injector] }, { provide: i2.HttpBackend, useClass: i2.HttpXhrBackend, deps: [i2.XhrFactory] }, { provide: i2.XhrFactory, useClass: BrowserXhrFactory, deps: [] }, ]; }; return HttpClientAppServiceInfoRegistry; }()); /** * Helper class for registering the services with the Angular injector. * * @export */ var AngularAppServiceInfoRegistry = /** @class */ (function () { /** * Creates an instance of AngularAppServiceInfoRegistry. * * @param {AppServiceInfoRegistry} serviceRegistry The service registry. */ function AngularAppServiceInfoRegistry(serviceRegistry) { this.serviceRegistry = serviceRegistry; core.Requires.HasValue(serviceRegistry, 'serviceRegistry'); } /** * Registers the application services to the Angular DI container. * * @param {...string[]} modules The modules to import to collect the service metadata. */ AngularAppServiceInfoRegistry.prototype.registerServices = function () { var e_1, _a; try { for (var _b = __values(this.serviceRegistry.services), _c = _b.next(); !_c.done; _c = _b.next()) { var serviceMetadata = _c.value; i0.Injectable({ providedIn: 'root' })(serviceMetadata.serviceType); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } }; /** * Gets the providers for the root. * * @returns {StaticClassProvider[]} */ AngularAppServiceInfoRegistry.prototype.getRootProviders = function () { var e_2, _a, e_3, _b; var providers = []; try { for (var _c = __values(this.serviceRegistry.serviceContracts), _d = _c.next(); !_d.done; _d = _c.next()) { var c = _d.value; var serviceContract = c; try { for (var _e = (e_3 = void 0, __values(serviceContract.services)), _f = _e.next(); !_f.done; _f = _e.next()) { var m = _f.value; var serviceMetadata = m; providers.push({ provide: serviceContract.contractToken || serviceContract.contractType, useClass: serviceMetadata.serviceType, multi: serviceContract.allowMultiple, deps: this.getDependencies(serviceMetadata.serviceType), }); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_f && !_f.done && (_b = _e.return)) _b.call(_e); } finally { if (e_3) throw e_3.error; } } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_2) throw e_2.error; } } providers.push.apply(providers, __spread(new HttpClientAppServiceInfoRegistry().getHttpClientProviders())); return providers; }; AngularAppServiceInfoRegistry.prototype.getDependencies = function (serviceType) { var deps = Reflect.getMetadata('design:paramtypes', serviceType); if (!deps && serviceType.ctorParameters) { deps = serviceType.ctorParameters(); } return deps || []; }; return AngularAppServiceInfoRegistry; }()); /** * Gets the application settings. * * @export * @class AppSettings */ exports.AppSettings = /** @class */ (function () { function AppSettings() { } Object.defineProperty(AppSettings.prototype, "baseUrl", { /** * Gets the base URL of the application. * * @readonly * @type {string} * @memberof AppSettings */ get: function () { var baseQuery = document.getElementsByTagName('base'); var baseElement = baseQuery && baseQuery[0]; return (baseElement && baseElement.href) || document.baseURI || '/'; }, enumerable: false, configurable: true }); Object.defineProperty(AppSettings.prototype, "baseApiUrl", { /** * Gets the base API URL of the application. * * @readonly * @type {string} * @memberof AppSettings */ get: function () { return this.baseUrl + "api/"; }, enumerable: false, configurable: true }); return AppSettings; }()); exports.AppSettings = __decorate([ core.AppService({ overridePriority: core.Priority.Low }), core.SingletonAppServiceContract() ], exports.AppSettings); /** * Provides proxied command execution over HTTP. * * @export * @class HttpCommandProcessorClient */ exports.HttpCommandProcessorClient = /** @class */ (function (_super) { __extends(HttpCommandProcessorClient, _super); /** * Initializes a new instance of the CommandProcessor class. * @param {Notification} notification The notification service. * @param {HttpClient} http The HTTP client. * @param {AppSettings} appSettings The application settings. */ function HttpCommandProcessorClient(appSettings, http, notification, logger) { var _this = _super.call(this) || this; _this.appSettings = appSettings; _this.http = http; _this.notification = notification; _this.logger = logger; /** * Gets or sets the base route for the command execution. * * @protected * @type {string} * @memberof CommandProcessor */ _this.baseRoute = 'api/cmd/'; return _this; } /** * Processes the command asynchronously. * @tparam T The command response type. * @param {string} command The command. * @param {{}} [args] Optional. The arguments. * @param {CommandClientContext} [options] Optional. Options controlling the command processing. * @returns {Observable{T}} An observable over the result. */ HttpCommandProcessorClient.prototype.process = function (command, args, options) { var _this = this; var url = this.getHttpGetUrl(command, args, options); var obs = this.http.get(url, this.getHttpGetOptions(command, args, options)); if (options && options.retries) { obs = obs.pipe(operators.retry(options.retries), operators.map(function (response) { return _this._processResponse(response, options); }), operators.catchError(function (error) { return _this._processError(error, options); })); } else { obs = obs.pipe(operators.map(function (response) { return _this._processResponse(response, options); }), operators.catchError(function (error) { return _this._processError(error, options); })); } return obs; }; /** * Gets the HTTP GET URL. * * @protected * @param {string} command The command. * @param {{}} [args] Optional. The arguments. * @param {CommandClientContext} [options] Optional. Options controlling the command processing. * @returns {string} The HTTP GET URL. * @memberof CommandProcessor */ HttpCommandProcessorClient.prototype.getHttpGetUrl = function (command, args, options) { var baseUrl = this.appSettings.baseUrl; if (!baseUrl.endsWith('/')) { baseUrl = baseUrl + '/'; } var url = "" + baseUrl + this.baseRoute + command + "/"; if (args) { url = url + '?' + Object.keys(args) .map(function (key) { return key + "=" + args[key]; }) .join('&'); } return url; }; /** * Gets the HTTP GET options. By default it does not return any options. * * @protected * @param {string} command The command. * @param {{}} [args] Optional. The arguments. * @param {CommandClientContext} [options] Optional. Options controlling the command processing. * @returns {({ * headers?: HttpHeaders | { * [header: string]: string | string[]; * }; * observe?: 'body'; * params?: HttpParams | { * [param: string]: string | string[]; * }; * reportProgress?: boolean; * responseType?: 'json'; * withCredentials?: boolean; * } | undefined)} The options or undefined. * @memberof CommandProcessor */ HttpCommandProcessorClient.prototype.getHttpGetOptions = function (command, args, options) { return undefined; }; HttpCommandProcessorClient.prototype._processResponse = function (response, options) { if (typeof response.severity === 'string') { response.severity = core.LogLevel[response.severity]; } if (response.severity <= core.LogLevel.Error) { throw new commands.CommandError(response.message, response); } if (response.severity === core.LogLevel.Warning) { this.logger.log(response.severity, null, response.message); if (!(options && (options.notifyWarnings === undefined || options.notifyWarnings))) { this.notification.notifyWarning(response); } } if (response.severity <= core.LogLevel.Error) { throw new Error(response.message); } return response; }; HttpCommandProcessorClient.prototype._processError = function (error, options) { this.logger.error(error); if (!(options && (options.notifyErrors === undefined || options.notifyErrors))) { this.notification.notifyError(error); } throw error; }; return HttpCommandProcessorClient; }(commands.CommandProcessorClient)); exports.HttpCommandProcessorClient = __decorate([ core.AppService({ overridePriority: core.Priority.Low }), __metadata("design:paramtypes", [exports.AppSettings, i2.HttpClient, ui.Notification, core.Logger]) ], exports.HttpCommandProcessorClient); /** * Provides proxied message processing over HTTP. * * @export * @class MessageProcessor */ exports.HttpMessageProcessorClient = /** @class */ (function (_super) { __extends(HttpMessageProcessorClient, _super); /** * Initializes a new instance of the HttpMessageProcessor class. * @param {Notification} notification The notification service. * @param {HttpClient} http The HTTP client. * @param {AppSettings} appSettings The application settings. */ function HttpMessageProcessorClient(appSettings, http, notification, logger) { var _this = _super.call(this) || this; _this.appSettings = appSettings; _this.http = http; _this.notification = notification; _this.logger = logger; /** * Gets or sets the base route for the command execution. * * @protected * @type {string} * @memberof MessageProcessor */ _this.baseRoute = 'api/msg/'; return _this; } /** * Processes the message asynchronously. * @tparam T The message response type. * @param {{}} message The message. * @param {MessagingClientContext} [options] Optional. Options controlling the message processing. * @returns {Observable{T}} An observable over the result. */ HttpMessageProcessorClient.prototype.process = function (message, options) { var _this = this; var url = this.getHttpPostUrl(message, options); var obs = this.http.post(url, message, this.getHttpPostOptions(message, options)); var responseObj = (options && options.retries) ? obs.pipe(operators.retry(options.retries), operators.map(function (response) { return _this._processResponse(response, options); }), operators.catchError(function (error) { return _this._processError(error, options); })) : obs.pipe(operators.map(function (response) { return _this._processResponse(response, options); }), operators.catchError(function (error) { return _this._processError(error, options); })); return responseObj; }; /** * Gets the HTTP GET URL. * * @protected * @param {{}} message The message. * @param {MessagingClientContext} [options] Optional. Options controlling the command processing. * @returns {string} The HTTP GET URL. * @memberof MessageProcessor */ HttpMessageProcessorClient.prototype.getHttpPostUrl = function (message, options) { var baseUrl = this.appSettings.baseUrl; if (!baseUrl.endsWith('/')) { baseUrl = baseUrl + '/'; } var url = "" + baseUrl + this.baseRoute; return url; }; /** * Gets the HTTP GET options. By default it does not return any options. * * @protected * @param {string} command The command. * @param {{}} [args] Optional. The arguments. * @param {MessagingClientContext} [options] Optional. Options controlling the command processing. * @returns {({ * headers?: HttpHeaders | { * [header: string]: string | string[]; * }; * observe?: 'body'; * params?: HttpParams | { * [param: string]: string | string[]; * }; * reportProgress?: boolean; * responseType?: 'json'; * withCredentials?: boolean; * } | undefined)} The options or undefined. * @memberof MessageProcessor */ HttpMessageProcessorClient.prototype.getHttpPostOptions = function (message, options) { return undefined; }; HttpMessageProcessorClient.prototype._processResponse = function (rawResponse, options) { if (rawResponse.exception) { var errorInfo = rawResponse.exception; if (typeof errorInfo.severity === 'string') { errorInfo.severity = core.LogLevel[errorInfo.severity]; } throw new messaging.MessagingError(errorInfo.message, errorInfo); } var response = rawResponse.message; if (typeof response.severity === 'string') { response.severity = core.LogLevel[response.severity];