process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
(function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./src/worker.ts");
/******/ })
/************************************************************************/
/******/ ({

/***/ "../../packages/open-access-api/index.ts":
/*!*****************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/index.ts ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./src/OpenAccessAPI */ "../../packages/open-access-api/src/OpenAccessAPI.ts"));
__export(__webpack_require__(/*! ./src/instance */ "../../packages/open-access-api/src/instance.ts"));
__export(__webpack_require__(/*! ./src/endpoints */ "../../packages/open-access-api/src/endpoints.ts"));
__export(__webpack_require__(/*! ./src/types */ "../../packages/open-access-api/src/types.ts"));


/***/ }),

/***/ "../../packages/open-access-api/src/OpenAccessAPI.ts":
/*!*****************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/OpenAccessAPI.ts ***!
  \*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fetch_1 = __webpack_require__(/*! ./fetch */ "../../packages/open-access-api/src/fetch.ts");
const query_string_1 = __webpack_require__(/*! ./query-string */ "../../packages/open-access-api/src/query-string.ts");
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ./utils */ "../../packages/open-access-api/src/utils.ts");
const DEFAULT_CONCURRENCY = 20;
const DEFAULT_RETRIES = 3;
const DEFAULT_RETRIES_DELAY = 100;
const DEFAULT_QUEUE_INTERVAL_CHECK = 1000;
/**
 * A client for Open Access API.
 */
class OpenAccessAPI {
    /**
     * @param {Options} options
     * @param {String} accessToken
     */
    constructor(options, accessToken) {
        this._onTokenExpired = R.noop;
        this._options = {
            retry: DEFAULT_RETRIES,
            retryDelay: DEFAULT_RETRIES_DELAY,
            concurrency: DEFAULT_CONCURRENCY,
            queueCheckInterval: DEFAULT_QUEUE_INTERVAL_CHECK,
            returnEmpty: false,
            ...options,
        };
        this._accessToken = accessToken;
        this._jobsSubject = new Rx.Subject();
        this._jobs$ = this._jobsSubject.pipe(Rx.flatMap(item => item, this._options.concurrency), Rx.share());
        this._queueSubject = new Rx.Subject();
        this._completedQueuesSubject = new Rx.Subject();
        this._nextReqId = 0;
        this._requestsCount = 0;
        this._queueSubject
            .pipe(Rx.bufferTime(this._options.queueCheckInterval), Rx.filter(ids => ids.length > 0), Rx.flatMap(arr => Rx.of(arr).pipe(Rx.zip(Rx.defer(() => this._fetch({
            method: 'GET',
            url: '/queue',
            reqOpts: this._getReqOptions(),
        }).pipe(Rx.retry()))))))
            .subscribe(([ids, queues]) => {
            const completedMap = R.pipe(queues.item_list, R.filter((item) => item.status === 'complete'), R.indexBy(x => x.id));
            ids.forEach(id => {
                if (completedMap[id]) {
                    this._completedQueuesSubject.next(id);
                }
                else {
                    this._queueSubject.next(id);
                }
            });
        });
        this._completedQueues$ = this._completedQueuesSubject.pipe(Rx.flatMap(id => this._fetch({
            url: `/queue/${id}`,
            method: 'GET',
            reqOpts: this._getReqOptions(),
        }).pipe(Rx.retry())), Rx.share());
    }
    _fetch(fetchOptions) {
        const { url, query, method, reqOpts, decode } = fetchOptions;
        const auth = R.getOr(fetchOptions, ['auth'], true);
        const requestBody = fetchOptions.body && JSON.stringify(fetchOptions.body);
        const { baseURL, version, applicationId } = this._options;
        const combinedQuery = { version, ...(query || {}) };
        if (reqOpts.queue) {
            combinedQuery.queue = true;
        }
        if (reqOpts.version) {
            combinedQuery.version = reqOpts.version;
        }
        const queryStr = query_string_1.queryString.stringify(combinedQuery);
        const relativeUrl = `${url}?${queryStr}`;
        const fullUrl = `${baseURL}/api/openaccess${relativeUrl}`;
        if (auth && !this._accessToken) {
            this._onTokenExpired();
            throw new Error('Access token is not set');
        }
        const headers = {
            'application-id': applicationId,
            'content-type': 'application/json',
        };
        if (auth && this._accessToken !== 'skip') {
            headers['Session-Token'] = this._accessToken;
        }
        return Rx.defer(() => {
            this._requestsCount++;
            return fetch_1.fetch(fullUrl, {
                method,
                headers,
                body: requestBody,
                credentials: 'include',
            }).then(res => res
                .json()
                .catch(() => 'no-response')
                .then((body) => {
                if (decode) {
                    body = utils_1.decodeEscapeCodesInObject(body);
                }
                if (!res.ok) {
                    const err = new Error(body.error.message);
                    err.body = body;
                    err.status = res.status;
                    err.url = fullUrl;
                    err.method = method;
                    throw err;
                }
                return body;
            }));
        }).pipe(Rx.retryWhen(errors => errors.pipe(Rx.scan((errorCount, err) => {
            if (errorCount >= reqOpts.retry || err.status < 500) {
                if (auth && err.status === 401) {
                    this._onTokenExpired();
                    this._accessToken = null;
                }
                throw err;
            }
            return errorCount + 1;
        }, 0), Rx.flatMap(errorCount => {
            return Rx.timer(errorCount * reqOpts.retryDelay);
        }))), Rx.catchError(error => {
            if (reqOpts.returnEmpty &&
                (!error.status || error.status >= 500) &&
                method === 'GET') {
                if (url === '/instances') {
                    return Rx.of({
                        page_number: 0,
                        page_size: 0,
                        total_pages: 0,
                        total_items: 0,
                        count: 0,
                        items: [],
                    });
                }
            }
            return Rx.throwObs(error);
        }), Rx.flatMap(body => {
            if (reqOpts.queue) {
                this._queueSubject.next(body.id);
                return this._completedQueues$.pipe(Rx.filter(result => result.id === body.id), Rx.map(result => result.response), Rx.take(1));
            }
            return Rx.of(body);
        }));
    }
    _processRequest(request) {
        return this._processRequests([request]).pipe(Rx.map(arr => arr[0].result));
    }
    _processRequests(requests, notify) {
        return Rx.Observable.create((observer) => {
            const id = ++this._nextReqId;
            const cancel$ = new Rx.Subject();
            const subscription = this._jobs$
                .pipe(Rx.filter((x) => x.id === id), Rx.take(requests.length), Rx.toArray())
                .subscribe((arr) => {
                arr.sort((source, other) => source.index - other.index);
                const errors = R.pipe(arr, R.filter((item) => item.type === 'error'), R.map(item => item.error));
                if (errors.length) {
                    const [firstError, ...rest] = errors;
                    firstError.otherErrors = rest;
                    observer.error(firstError);
                }
                else {
                    observer.next(arr);
                }
                observer.complete();
            }, err => {
                // shouldn't go here because all errors should be caught
                observer.error(err);
            });
            requests.forEach((fetchOptions, index) => {
                this._jobsSubject.next(cancel$.pipe(Rx.take(1), Rx.map(() => ({ id, index, type: 'canceled' })), Rx.race(Rx.of(null).pipe(
                // add delay and it won't be executed if the request is already cancelled
                Rx.delay(0), Rx.switchMap(() => this._fetch(fetchOptions).pipe(Rx.map(result => ({
                    id,
                    index,
                    type: 'success',
                    result,
                })), Rx.tap(() => {
                    if (notify) {
                        notify.next(fetchOptions);
                    }
                }), Rx.catchError(error => Rx.of({ id, index, type: 'error', error }))))))));
            });
            return () => {
                cancel$.next();
                subscription.unsubscribe();
            };
        });
    }
    _getReqOptions(reqOpts) {
        return {
            ...R.pick(this._options, ['retry', 'retryDelay', 'version']),
            ...(reqOpts || {}),
        };
    }
    setAccessToken(accessToken) {
        this._accessToken = accessToken;
    }
    onTokenExpired(callback) {
        this._onTokenExpired = callback;
        return this;
    }
    _createGetInstancesFetch(opts, reqOpts = { version: '1.2' }) {
        return {
            url: '/instances',
            method: 'GET',
            query: {
                type_name: opts.typeName,
                filter: opts.filter,
                page_number: opts.pageNumber,
                page_size: opts.pageSize,
                order_by: opts.orderBy,
            },
            reqOpts: { ...this._getReqOptions(reqOpts) },
        };
    }
    _createGetCardholdersFetch(opts, reqOpts) {
        const query = utils_1.toSnakeCase(opts);
        if (query.access_level_list) {
            query.access_level_list = JSON.stringify(query.access_level_list);
        }
        return {
            url: '/cardholders',
            method: 'GET',
            reqOpts: this._getReqOptions(reqOpts),
            query,
        };
    }
}
exports.OpenAccessAPI = OpenAccessAPI;


/***/ }),

/***/ "../../packages/open-access-api/src/auth/getDirectories.ts":
/*!***********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/auth/getDirectories.ts ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getDirectories = (reqOpts) => {
    const fetchOptions = {
        url: '/directories',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        auth: false,
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((result) => result.item_list.map((x) => x.property_value_map)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/auth/getIdentityProvider.ts":
/*!****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/auth/getIdentityProvider.ts ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getIdentityProvider = (opts, reqOpts) => {
    const fetchOptions = {
        url: '/identity_provider_url',
        method: 'GET',
        query: {
            directory_id: opts.directoryId,
            redirect_url: opts.redirectUrl,
            response_mode: opts.responseMode,
        },
        auth: false,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((body) => body.url));
};


/***/ }),

/***/ "../../packages/open-access-api/src/auth/getSession.ts":
/*!*******************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/auth/getSession.ts ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getSession = (reqOpts) => {
    const fetchOptions = {
        url: '/session',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/auth/login.ts":
/*!**************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/auth/login.ts ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.login = (values, reqOpts) => {
    const fetchOptions = {
        url: '/authentication',
        method: 'POST',
        auth: false,
        body: {
            directory_id: values.directoryId,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        query: {},
    };
    if ('oidcToken' in values) {
        fetchOptions.body.oidc_token = values.oidcToken;
        fetchOptions.reqOpts.version = '2.0';
    }
    else {
        fetchOptions.body.user_name = values.username;
        fetchOptions.body.password = values.password;
    }
    return instance_1.api._processRequest(fetchOptions).pipe(Rx.map((input) => ({
        sessionToken: input.session_token,
        tokenExpirationTime: input.token_expiration_time,
        warning: input.warning,
    })));
};


/***/ }),

/***/ "../../packages/open-access-api/src/auth/logout.ts":
/*!***************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/auth/logout.ts ***!
  \***************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.logout = (reqOpts) => {
    const fetchOptions = {
        url: '/authentication',
        method: 'DELETE',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.tap(() => instance_1.api.setAccessToken(null)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/badge/addPrintRequest.ts":
/*!*************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/badge/addPrintRequest.ts ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.addPrintRequest = (badgeKey, options, reqOpts) => {
    const fetchOptions = {
        url: `/badge/${badgeKey}/print_request`,
        method: 'POST',
        body: options,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/badge/getBadgePrinters.ts":
/*!**************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/badge/getBadgePrinters.ts ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getBadgePrinters = (badgeTypeId, reqOpts) => {
    const fetchOptions = {
        url: '/badge_printers',
        method: 'GET',
        query: {
            badge_type_id: badgeTypeId == null ? undefined : badgeTypeId,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions).pipe(Rx.map((result) => result.printers.map((item) => ({
        badgeTypeId: item.badge_type_id,
        printerName: item.printer_name,
        workstation: item.workstation,
    }))));
};


/***/ }),

/***/ "../../packages/open-access-api/src/badge/getPrintRequest.ts":
/*!*************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/badge/getPrintRequest.ts ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getPrintRequest = (id, reqOpts) => {
    const fetchOptions = {
        url: `/badge/${id}/print_request`,
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/badge/issueMobileCredential.ts":
/*!*******************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/badge/issueMobileCredential.ts ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.issueMobileCredential = (badgeKey, options, reqOpts) => {
    const fetchOptions = {
        url: `/badge/${badgeKey}/issue_mobile_credential`,
        method: 'POST',
        body: {
            mobile_device_id: options.mobileDeviceId,
            send_email: options.sendEmail,
            mobile_issuance_method: options.mobileIssuanceMethod,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions).pipe(Rx.map((result) => ({
        mobileDeviceActivationCode: result.mobile_device_activation_code,
        mobileIssuanceMessage: result.mobile_issuance_message,
    })));
};


/***/ }),

/***/ "../../packages/open-access-api/src/cardholders/getDirectoryAccounts.ts":
/*!************************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/cardholders/getDirectoryAccounts.ts ***!
  \************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getDirectoryAccounts = (opts, reqOpts) => {
    const fetchOptions = {
        url: '/directory_accounts',
        method: 'GET',
        query: {
            filter: opts.filter,
            directory_id: opts.directory_id,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/cardholders/getDirectoryMatches.ts":
/*!***********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/cardholders/getDirectoryMatches.ts ***!
  \***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
exports.getDirectoryMatches = (opts, reqOpts) => {
    const maxMatches = 100;
    const requests = R.chunk(opts.cardholderIds, maxMatches).map(ids => ({
        url: '/directory_accounts_matching_cardholders',
        method: 'GET',
        query: {
            cardholder_ids: JSON.stringify(ids),
            filter: opts.filter,
            directory_id: opts.directoryId,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    }));
    return instance_1.api._processRequests(requests).pipe(Rx.map(arr => arr.reduce((combined, { result }) => ({
        failureItems: combined.failureItems.concat(result.failure_list.item_list),
        successfulItems: combined.successfulItems.concat(result.successful_list.item_list),
    }), {
        failureItems: [],
        successfulItems: [],
    })));
};


/***/ }),

/***/ "../../packages/open-access-api/src/console/addCard.ts":
/*!*******************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/console/addCard.ts ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.addCard = (card, reqOpts) => {
    const fetchOptions = {
        url: '/console/cards',
        method: 'POST',
        body: card,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/console/deleteCard.ts":
/*!**********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/console/deleteCard.ts ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.deleteCard = (cardId, reqOpts) => {
    const fetchOptions = {
        url: '/console/cards',
        method: 'DELETE',
        query: {
            card_id: cardId,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/console/getLayout.ts":
/*!*********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/console/getLayout.ts ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getLayout = (layoutId, reqOpts) => {
    const fetchOptions = {
        url: '/console/layouts',
        method: 'GET',
        query: {
            layout_id: layoutId,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/console/updateLayout.ts":
/*!************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/console/updateLayout.ts ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.updateLayout = (layout, reqOpts) => {
    const fetchOptions = {
        url: '/console/layouts',
        method: 'PUT',
        body: layout,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/endpoints.ts":
/*!*************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/endpoints.ts ***!
  \*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
// auth
__export(__webpack_require__(/*! ./auth/getDirectories */ "../../packages/open-access-api/src/auth/getDirectories.ts"));
__export(__webpack_require__(/*! ./auth/getIdentityProvider */ "../../packages/open-access-api/src/auth/getIdentityProvider.ts"));
__export(__webpack_require__(/*! ./auth/login */ "../../packages/open-access-api/src/auth/login.ts"));
__export(__webpack_require__(/*! ./auth/logout */ "../../packages/open-access-api/src/auth/logout.ts"));
__export(__webpack_require__(/*! ./auth/getSession */ "../../packages/open-access-api/src/auth/getSession.ts"));
// badge
__export(__webpack_require__(/*! ./badge/issueMobileCredential */ "../../packages/open-access-api/src/badge/issueMobileCredential.ts"));
__export(__webpack_require__(/*! ./badge/getBadgePrinters */ "../../packages/open-access-api/src/badge/getBadgePrinters.ts"));
__export(__webpack_require__(/*! ./badge/addPrintRequest */ "../../packages/open-access-api/src/badge/addPrintRequest.ts"));
__export(__webpack_require__(/*! ./badge/getPrintRequest */ "../../packages/open-access-api/src/badge/getPrintRequest.ts"));
// user
__export(__webpack_require__(/*! ./user/addManagedAccessLevels */ "../../packages/open-access-api/src/user/addManagedAccessLevels.ts"));
__export(__webpack_require__(/*! ./user/addUserSegments */ "../../packages/open-access-api/src/user/addUserSegments.ts"));
__export(__webpack_require__(/*! ./user/deleteManagedAccessLevels */ "../../packages/open-access-api/src/user/deleteManagedAccessLevels.ts"));
__export(__webpack_require__(/*! ./user/deleteUserSegments */ "../../packages/open-access-api/src/user/deleteUserSegments.ts"));
__export(__webpack_require__(/*! ./user/getEditableSegments */ "../../packages/open-access-api/src/user/getEditableSegments.ts"));
__export(__webpack_require__(/*! ./user/getLoggedInUser */ "../../packages/open-access-api/src/user/getLoggedInUser.ts"));
__export(__webpack_require__(/*! ./user/getManagedAccessLevels */ "../../packages/open-access-api/src/user/getManagedAccessLevels.ts"));
__export(__webpack_require__(/*! ./user/getUser */ "../../packages/open-access-api/src/user/getUser.ts"));
__export(__webpack_require__(/*! ./user/getUserSegments */ "../../packages/open-access-api/src/user/getUserSegments.ts"));
__export(__webpack_require__(/*! ./user/updatePassword */ "../../packages/open-access-api/src/user/updatePassword.ts"));
__export(__webpack_require__(/*! ./user/updateUser */ "../../packages/open-access-api/src/user/updateUser.ts"));
// instances
__export(__webpack_require__(/*! ./instances/addInstance */ "../../packages/open-access-api/src/instances/addInstance.ts"));
__export(__webpack_require__(/*! ./instances/bulkModifyInstance */ "../../packages/open-access-api/src/instances/bulkModifyInstance.ts"));
__export(__webpack_require__(/*! ./instances/createUserPreference */ "../../packages/open-access-api/src/instances/createUserPreference.ts"));
__export(__webpack_require__(/*! ./instances/deleteInstance */ "../../packages/open-access-api/src/instances/deleteInstance.ts"));
__export(__webpack_require__(/*! ./instances/deleteUserPreference */ "../../packages/open-access-api/src/instances/deleteUserPreference.ts"));
__export(__webpack_require__(/*! ./instances/executeMethod */ "../../packages/open-access-api/src/instances/executeMethod.ts"));
__export(__webpack_require__(/*! ./instances/getAllInstances */ "../../packages/open-access-api/src/instances/getAllInstances.ts"));
__export(__webpack_require__(/*! ./instances/getAllInstancesWithProgress */ "../../packages/open-access-api/src/instances/getAllInstancesWithProgress.ts"));
__export(__webpack_require__(/*! ./instances/getCardholders */ "../../packages/open-access-api/src/instances/getCardholders.ts"));
__export(__webpack_require__(/*! ./instances/getAllCardholders */ "../../packages/open-access-api/src/instances/getAllCardholders.ts"));
__export(__webpack_require__(/*! ./instances/getAllCardholdersWithProgress */ "../../packages/open-access-api/src/instances/getAllCardholdersWithProgress.ts"));
__export(__webpack_require__(/*! ./instances/getInstances */ "../../packages/open-access-api/src/instances/getInstances.ts"));
__export(__webpack_require__(/*! ./instances/getLoggedEvents */ "../../packages/open-access-api/src/instances/getLoggedEvents.ts"));
__export(__webpack_require__(/*! ./instances/getSingleInstances */ "../../packages/open-access-api/src/instances/getSingleInstances.ts"));
__export(__webpack_require__(/*! ./instances/getType */ "../../packages/open-access-api/src/instances/getType.ts"));
__export(__webpack_require__(/*! ./instances/getUserPreferences */ "../../packages/open-access-api/src/instances/getUserPreferences.ts"));
__export(__webpack_require__(/*! ./instances/modifyInstance */ "../../packages/open-access-api/src/instances/modifyInstance.ts"));
__export(__webpack_require__(/*! ./instances/updateUserPreference */ "../../packages/open-access-api/src/instances/updateUserPreference.ts"));
__export(__webpack_require__(/*! ./instances/sendIncomingEvents */ "../../packages/open-access-api/src/instances/sendIncomingEvents.ts"));
// settings
__export(__webpack_require__(/*! ./settings/getAuthorizationWarning */ "../../packages/open-access-api/src/settings/getAuthorizationWarning.ts"));
__export(__webpack_require__(/*! ./settings/getCardholderOptions */ "../../packages/open-access-api/src/settings/getCardholderOptions.ts"));
__export(__webpack_require__(/*! ./settings/getEnterpriseSettings */ "../../packages/open-access-api/src/settings/getEnterpriseSettings.ts"));
__export(__webpack_require__(/*! ./settings/getPasswordSettings */ "../../packages/open-access-api/src/settings/getPasswordSettings.ts"));
__export(__webpack_require__(/*! ./settings/getSegmentationSettings */ "../../packages/open-access-api/src/settings/getSegmentationSettings.ts"));
__export(__webpack_require__(/*! ./settings/updatePasswordSettings */ "../../packages/open-access-api/src/settings/updatePasswordSettings.ts"));
__export(__webpack_require__(/*! ./settings/getVisitSettings */ "../../packages/open-access-api/src/settings/getVisitSettings.ts"));
__export(__webpack_require__(/*! ./settings/updateVisitSettings */ "../../packages/open-access-api/src/settings/updateVisitSettings.ts"));
__export(__webpack_require__(/*! ./settings/getVersion */ "../../packages/open-access-api/src/settings/getVersion.ts"));
__export(__webpack_require__(/*! ./settings/getInstantRewindTimeInSeconds */ "../../packages/open-access-api/src/settings/getInstantRewindTimeInSeconds.ts"));
// settings
__export(__webpack_require__(/*! ./cardholders/getDirectoryAccounts */ "../../packages/open-access-api/src/cardholders/getDirectoryAccounts.ts"));
__export(__webpack_require__(/*! ./cardholders/getDirectoryMatches */ "../../packages/open-access-api/src/cardholders/getDirectoryMatches.ts"));
// misc
__export(__webpack_require__(/*! ./misc/onTokenExpired */ "../../packages/open-access-api/src/misc/onTokenExpired.ts"));
__export(__webpack_require__(/*! ./misc/setAccessToken */ "../../packages/open-access-api/src/misc/setAccessToken.ts"));
__export(__webpack_require__(/*! ./misc/keepAlive */ "../../packages/open-access-api/src/misc/keepAlive.ts"));
__export(__webpack_require__(/*! ./misc/getSuspExpiration */ "../../packages/open-access-api/src/misc/getSuspExpiration.ts"));
// console
__export(__webpack_require__(/*! ./console/getLayout */ "../../packages/open-access-api/src/console/getLayout.ts"));
__export(__webpack_require__(/*! ./console/updateLayout */ "../../packages/open-access-api/src/console/updateLayout.ts"));
__export(__webpack_require__(/*! ./console/addCard */ "../../packages/open-access-api/src/console/addCard.ts"));
__export(__webpack_require__(/*! ./console/deleteCard */ "../../packages/open-access-api/src/console/deleteCard.ts"));
// recorders
__export(__webpack_require__(/*! ./recorders/getVideoRecorders */ "../../packages/open-access-api/src/recorders/getVideoRecorders.ts"));
__export(__webpack_require__(/*! ./recorders/getAllVideoRecorders */ "../../packages/open-access-api/src/recorders/getAllVideoRecorders.ts"));
__export(__webpack_require__(/*! ./recorders/getVideoRecorderAuthData */ "../../packages/open-access-api/src/recorders/getVideoRecorderAuthData.ts"));
// maps
__export(__webpack_require__(/*! ./maps/getAllMapDevices */ "../../packages/open-access-api/src/maps/getAllMapDevices.ts"));
__export(__webpack_require__(/*! ./maps/getAllMapIconGroups */ "../../packages/open-access-api/src/maps/getAllMapIconGroups.ts"));
__export(__webpack_require__(/*! ./maps/getMapDevices */ "../../packages/open-access-api/src/maps/getMapDevices.ts"));
__export(__webpack_require__(/*! ./maps/getMapIconGroups */ "../../packages/open-access-api/src/maps/getMapIconGroups.ts"));
__export(__webpack_require__(/*! ./maps/getMapIcons */ "../../packages/open-access-api/src/maps/getMapIcons.ts"));
__export(__webpack_require__(/*! ./maps/getMaps */ "../../packages/open-access-api/src/maps/getMaps.ts"));
__export(__webpack_require__(/*! ./maps/getAllMaps */ "../../packages/open-access-api/src/maps/getAllMaps.ts"));
__export(__webpack_require__(/*! ./maps/getSingleMap */ "../../packages/open-access-api/src/maps/getSingleMap.ts"));


/***/ }),

/***/ "../../packages/open-access-api/src/fetch.ts":
/*!*********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/fetch.ts ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fetchOrg = __importStar(__webpack_require__(/*! isomorphic-fetch */ "isomorphic-fetch"));
exports.fetch = global.fetch || fetchOrg.default || fetchOrg;


/***/ }),

/***/ "../../packages/open-access-api/src/instance.ts":
/*!************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instance.ts ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.setApi = (newApi) => {
    exports.api = newApi;
};
exports.getApi = () => exports.api;


/***/ }),

/***/ "../../packages/open-access-api/src/instances/addInstance.ts":
/*!*************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/addInstance.ts ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.addInstance = (typeName, values, reqOpts) => {
    const fetchOptions = {
        url: '/instances',
        method: 'POST',
        body: {
            type_name: typeName,
            property_value_map: values,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((result) => result.property_value_map));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/bulkModifyInstance.ts":
/*!********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/bulkModifyInstance.ts ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.bulkModifyInstance = (options, reqOpts) => {
    const fetchOptions = {
        url: '/property_bulk_update',
        method: 'PUT',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        body: options,
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/createUserPreference.ts":
/*!**********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/createUserPreference.ts ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.createUserPreference = (opts, reqOpts) => {
    const fetchOptions = {
        url: '/user_preferences',
        method: 'POST',
        body: utils_1.toSnakeCase(opts),
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((x) => x.preference_id));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/deleteInstance.ts":
/*!****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/deleteInstance.ts ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.deleteInstance = (typeName, values, reqOpts) => {
    const fetchOptions = {
        url: '/instances',
        method: 'DELETE',
        body: {
            type_name: typeName,
            property_value_map: values,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/deleteUserPreference.ts":
/*!**********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/deleteUserPreference.ts ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.deleteUserPreference = (preferenceId, reqOpts) => {
    const fetchOptions = {
        url: '/user_preferences',
        method: 'DELETE',
        body: utils_1.toSnakeCase({ preferenceId }),
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/executeMethod.ts":
/*!***************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/executeMethod.ts ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
const jest_1 = __webpack_require__(/*! utils/jest */ "../../packages/utils/jest.ts");
exports.executeMethod = jest_1.mockable((opts, reqOpts) => {
    const fetchOptions = {
        url: '/execute_method',
        query: utils_1.toSnakeCase(R.pick(opts, ['typeName', 'methodName'])),
        body: utils_1.toSnakeCase(R.pick(opts, ['propertyValueMap', 'inParameterValueMap'])),
        method: 'POST',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((result) => result.out_parameter_value_map));
});


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getAllCardholders.ts":
/*!*******************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getAllCardholders.ts ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
const MAX_PAGE = 100;
exports.getAllCardholders = (opts, reqOpts, extraOptions) => {
    return utils_1.getAllPages({
        api: instance_1.api,
        getPageFetchOptions: pageNumber => instance_1.api._createGetCardholdersFetch({
            ...opts,
            pageSize: MAX_PAGE,
            pageNumber,
        }, reqOpts),
    }, extraOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getAllCardholdersWithProgress.ts":
/*!*******************************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getAllCardholdersWithProgress.ts ***!
  \*******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const getAllCardholders_1 = __webpack_require__(/*! ./getAllCardholders */ "../../packages/open-access-api/src/instances/getAllCardholders.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getAllCardholdersWithProgress = (opts, reqOpts, maxPages) => {
    return utils_1.getAllWithProgress(onProgress => getAllCardholders_1.getAllCardholders(opts, reqOpts, {
        maxPages,
        onProgress,
    }));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getAllInstances.ts":
/*!*****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getAllInstances.ts ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const MAX_PAGE = 100;
exports.getAllInstances = (opts, reqOpts, extraOptions) => {
    return utils_1.getAllPages({
        api: instance_1.api,
        getPageFetchOptions: pageNumber => instance_1.api._createGetInstancesFetch({
            ...opts,
            pageSize: MAX_PAGE,
            pageNumber,
        }, reqOpts),
    }, extraOptions).pipe(Rx.map(items => {
        utils_1.fixIdStr(opts.typeName, items);
        items.forEach((item, index) => {
            items[index] = utils_1.decodeEscapeCodesInObject(item);
        });
        return items;
    }));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getAllInstancesWithProgress.ts":
/*!*****************************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getAllInstancesWithProgress.ts ***!
  \*****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const getAllInstances_1 = __webpack_require__(/*! ./getAllInstances */ "../../packages/open-access-api/src/instances/getAllInstances.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getAllInstancesWithProgress = (opts, reqOpts, maxPages) => {
    return utils_1.getAllWithProgress(onProgress => getAllInstances_1.getAllInstances(opts, reqOpts, {
        maxPages,
        onProgress,
    }));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getCardholders.ts":
/*!****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getCardholders.ts ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getCardholders = (opts, reqOpts) => {
    return instance_1.api
        ._processRequest(instance_1.api._createGetCardholdersFetch(opts, reqOpts))
        .pipe(Rx.map(input => utils_1.mapInstances(input)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getInstances.ts":
/*!**************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getInstances.ts ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getInstances = (opts, reqOpts) => {
    const fetchOptions = instance_1.api._createGetInstancesFetch({ pageNumber: 1, ...opts }, reqOpts);
    return instance_1.api._processRequest(fetchOptions).pipe(Rx.map(input => {
        const mapped = utils_1.mapInstances(input);
        utils_1.fixIdStr(opts.typeName, mapped.items);
        mapped.items.forEach((item, index) => {
            mapped.items[index] = utils_1.decodeEscapeCodesInObject(item);
        });
        return mapped;
    }));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getLoggedEvents.ts":
/*!*****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getLoggedEvents.ts ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getLoggedEvents = (opts, reqOpts) => {
    const fetchOptions = {
        url: '/logged_events',
        method: 'GET',
        query: {
            filter: opts.filter,
            page_number: opts.pageNumber || 1,
            page_size: opts.pageSize,
            order_by: opts.orderBy,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions).pipe(Rx.map((input) => ({
        pageNumber: input.page_number,
        pageSize: input.page_size,
        totalPages: input.total_pages,
        total: input.total_items,
        count: input.count,
        items: input.item_list || [],
    })));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getSingleInstances.ts":
/*!********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getSingleInstances.ts ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const getInstances_1 = __webpack_require__(/*! ./getInstances */ "../../packages/open-access-api/src/instances/getInstances.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getSingleInstances = (opts, reqOpts) => {
    return getInstances_1.getInstances(opts, reqOpts).pipe(Rx.map(result => utils_1.processSingleInstance(result, opts)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getType.ts":
/*!*********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getType.ts ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getType = (typeName, reqOpts) => {
    const fetchOptions = {
        url: '/type',
        query: {
            type_name: typeName,
        },
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/getUserPreferences.ts":
/*!********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/getUserPreferences.ts ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getUserPreferences = (opts, reqOpts) => {
    const fetchOptions = {
        url: '/user_preferences',
        method: 'GET',
        query: utils_1.toSnakeCase(opts),
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions).pipe(Rx.map((x) => x.preference_list), Rx.map(R.map(utils_1.toCamelCase)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/modifyInstance.ts":
/*!****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/modifyInstance.ts ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.modifyInstance = (typeName, values, reqOpts) => {
    const fetchOptions = {
        url: '/instances',
        method: 'PUT',
        body: {
            type_name: typeName,
            property_value_map: values,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((result) => result.property_value_map));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/sendIncomingEvents.ts":
/*!********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/sendIncomingEvents.ts ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.sendIncomingEvents = (incomingEvents, reqOpts) => {
    const fetchOptions = {
        url: '/send_incoming_events',
        method: 'POST',
        body: {
            incoming_event_list: incomingEvents,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((result) => result.failure_list.item_list));
};


/***/ }),

/***/ "../../packages/open-access-api/src/instances/updateUserPreference.ts":
/*!**********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/instances/updateUserPreference.ts ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.updateUserPreference = (opts, reqOpts) => {
    const fetchOptions = {
        url: '/user_preferences',
        method: 'PUT',
        body: utils_1.toSnakeCase(opts),
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map(R.omit(['version'])), Rx.map(utils_1.toCamelCase));
};


/***/ }),

/***/ "../../packages/open-access-api/src/maps/getAllMapDevices.ts":
/*!*************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/maps/getAllMapDevices.ts ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
const MAX_PAGE = 100;
exports.getAllMapDevices = (mapId, opts, reqOpts) => {
    return utils_1.getAllPages({
        noItemWrap: true,
        api: instance_1.api,
        getPageFetchOptions: pageNumber => ({
            method: 'get',
            url: `/maps/${mapId}/devices`,
            query: {
                filter: opts === null || opts === void 0 ? void 0 : opts.filter,
                page_number: pageNumber,
                page_size: MAX_PAGE,
                order_by: opts === null || opts === void 0 ? void 0 : opts.orderBy,
            },
            decode: true,
            reqOpts: instance_1.api._getReqOptions(reqOpts),
        }),
    });
};


/***/ }),

/***/ "../../packages/open-access-api/src/maps/getAllMapIconGroups.ts":
/*!****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/maps/getAllMapIconGroups.ts ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
const MAX_PAGE = 100;
exports.getAllMapIconGroups = (opts, reqOpts) => {
    return utils_1.getAllPages({
        noItemWrap: true,
        api: instance_1.api,
        getPageFetchOptions: pageNumber => ({
            method: 'get',
            url: `/map_icon_groups`,
            query: {
                filter: opts === null || opts === void 0 ? void 0 : opts.filter,
                page_number: pageNumber,
                page_size: MAX_PAGE,
                order_by: opts === null || opts === void 0 ? void 0 : opts.orderBy,
            },
            decode: true,
            reqOpts: instance_1.api._getReqOptions(reqOpts),
        }),
    });
};


/***/ }),

/***/ "../../packages/open-access-api/src/maps/getAllMaps.ts":
/*!*******************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/maps/getAllMaps.ts ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
const MAX_PAGE = 100;
exports.getAllMaps = (opts, reqOpts) => {
    return utils_1.getAllPages({
        noItemWrap: true,
        api: instance_1.api,
        getPageFetchOptions: pageNumber => ({
            method: 'get',
            url: '/maps',
            query: {
                map_filter: opts.mapFilter,
                map_device_filter: opts.mapDeviceFilter,
                page_number: pageNumber,
                page_size: MAX_PAGE,
                order_by: opts.orderBy,
            },
            decode: true,
            reqOpts: instance_1.api._getReqOptions(reqOpts),
        }),
    }).pipe(Rx.map(items => {
        items.forEach(item => {
            if (!item.device_count) {
                item.device_count = 0;
            }
        });
        return items;
    }));
};


/***/ }),

/***/ "../../packages/open-access-api/src/maps/getMapDevices.ts":
/*!**********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/maps/getMapDevices.ts ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getMapDevices = (mapId, opts, reqOpts) => {
    return instance_1.api
        ._processRequest({
        method: 'get',
        url: `/maps/${mapId}/devices`,
        query: {
            filter: opts.filter,
            page_number: opts.pageNumber,
            page_size: opts.pageSize,
            order_by: opts.orderBy,
        },
        decode: true,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    })
        .pipe(Rx.map(result => utils_1.mapInstances(result, true)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/maps/getMapIconGroups.ts":
/*!*************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/maps/getMapIconGroups.ts ***!
  \*************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getMapIconGroups = (opts, reqOpts) => {
    return instance_1.api
        ._processRequest({
        method: 'get',
        url: `/map_icon_groups`,
        query: {
            filter: opts.filter,
            page_number: opts.pageNumber,
            page_size: opts.pageSize,
            order_by: opts.orderBy,
        },
        decode: true,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    })
        .pipe(Rx.map(result => utils_1.mapInstances(result, true)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/maps/getMapIcons.ts":
/*!********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/maps/getMapIcons.ts ***!
  \********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getMapIcons = (opts, reqOpts) => {
    return instance_1.api
        ._processRequest({
        method: 'get',
        url: `/map_icons`,
        query: {
            filter: opts.filter,
            page_number: opts.pageNumber,
            page_size: opts.pageSize,
            order_by: opts.orderBy,
        },
        decode: true,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    })
        .pipe(Rx.map(result => utils_1.mapInstances(result, true)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/maps/getMaps.ts":
/*!****************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/maps/getMaps.ts ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getMaps = (opts, reqOpts) => {
    return instance_1.api
        ._processRequest({
        method: 'get',
        url: '/maps',
        query: {
            map_filter: opts.mapFilter || undefined,
            map_device_filter: opts.mapDeviceFilter || undefined,
            page_number: opts.pageNumber,
            page_size: opts.pageSize,
            order_by: opts.orderBy,
        },
        decode: true,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    })
        .pipe(Rx.map((result) => {
        const mapped = utils_1.mapInstances(result, true);
        mapped.items.forEach(item => {
            if (!item.device_count) {
                item.device_count = 0;
            }
        });
        return mapped;
    }));
};


/***/ }),

/***/ "../../packages/open-access-api/src/maps/getSingleMap.ts":
/*!*********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/maps/getSingleMap.ts ***!
  \*********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const getMaps_1 = __webpack_require__(/*! ./getMaps */ "../../packages/open-access-api/src/maps/getMaps.ts");
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
exports.getSingleMap = (opts, reqOpts) => {
    return getMaps_1.getMaps(opts, reqOpts).pipe(Rx.map(result => utils_1.processSingleInstance(result, opts)));
};


/***/ }),

/***/ "../../packages/open-access-api/src/misc/getSuspExpiration.ts":
/*!**************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/misc/getSuspExpiration.ts ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getSuspExpiration = (reqOpts) => {
    const fetchOptions = {
        url: '/susp_expiration',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/misc/keepAlive.ts":
/*!******************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/misc/keepAlive.ts ***!
  \******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.keepAlive = (reqOpts) => {
    const fetchOptions = {
        url: '/keepalive',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/misc/onTokenExpired.ts":
/*!***********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/misc/onTokenExpired.ts ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const __1 = __webpack_require__(/*! ../.. */ "../../packages/open-access-api/index.ts");
const jest_1 = __webpack_require__(/*! utils/jest */ "../../packages/utils/jest.ts");
exports.onTokenExpired = jest_1.mockable((callback) => {
    __1.api.onTokenExpired(callback);
});


/***/ }),

/***/ "../../packages/open-access-api/src/misc/setAccessToken.ts":
/*!***********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/misc/setAccessToken.ts ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const __1 = __webpack_require__(/*! ../.. */ "../../packages/open-access-api/index.ts");
exports.setAccessToken = (accessToken) => {
    __1.api.setAccessToken(accessToken);
};


/***/ }),

/***/ "../../packages/open-access-api/src/query-string.ts":
/*!****************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/query-string.ts ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const queryStringOrg = __importStar(__webpack_require__(/*! query-string */ "query-string"));
exports.queryString = queryStringOrg.default || queryStringOrg;


/***/ }),

/***/ "../../packages/open-access-api/src/recorders/getAllVideoRecorders.ts":
/*!**********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/recorders/getAllVideoRecorders.ts ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const getVideoRecorders_1 = __webpack_require__(/*! ./getVideoRecorders */ "../../packages/open-access-api/src/recorders/getVideoRecorders.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const jest_1 = __webpack_require__(/*! utils/jest */ "../../packages/utils/jest.ts");
const MAX_PAGE = 100;
exports.getAllVideoRecorders = jest_1.mockable((reqOpts) => {
    const newOpts = {
        pageNumber: 1,
        pageSize: MAX_PAGE,
    };
    const firstPage$ = getVideoRecorders_1.getVideoRecorders(newOpts, reqOpts);
    return firstPage$.pipe(Rx.flatMap(firstPage => {
        if (firstPage.totalPages < 2) {
            return Rx.of(firstPage.items);
        }
        return Rx.forkJoin(R.range(2, firstPage.totalPages + 1).map(pageNumber => getVideoRecorders_1.getVideoRecorders({ ...newOpts, pageNumber }, reqOpts))).pipe(Rx.map(restPages => {
            return R.flatMap([firstPage, ...restPages], x => x.items);
        }));
    }));
});


/***/ }),

/***/ "../../packages/open-access-api/src/recorders/getVideoRecorderAuthData.ts":
/*!**************************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/recorders/getVideoRecorderAuthData.ts ***!
  \**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getVideoRecorderAuthData = (recorderId, reqOpts) => {
    return instance_1.api
        ._processRequest({
        url: `/video_recorder/${recorderId}/auth_data`,
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    })
        .pipe(Rx.map((ret) => {
        return ret.authentication_data;
    }));
};


/***/ }),

/***/ "../../packages/open-access-api/src/recorders/getVideoRecorders.ts":
/*!*******************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/recorders/getVideoRecorders.ts ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const utils_1 = __webpack_require__(/*! ../utils */ "../../packages/open-access-api/src/utils.ts");
const jest_1 = __webpack_require__(/*! utils/jest */ "../../packages/utils/jest.ts");
exports.getVideoRecorders = jest_1.mockable((opts, reqOpts) => {
    return instance_1.api
        ._processRequest({
        url: '/video_recorders',
        method: 'GET',
        query: opts && {
            page_number: opts.pageNumber,
            page_size: opts.pageSize,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    })
        .pipe(Rx.map((input) => {
        const ret = utils_1.mapInstances(input);
        ret.items = input.item_list;
        return ret;
    }));
});


/***/ }),

/***/ "../../packages/open-access-api/src/settings/getAuthorizationWarning.ts":
/*!************************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/getAuthorizationWarning.ts ***!
  \************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getAuthorizationWarning = (reqOpts) => {
    const fetchOptions = {
        url: '/settings/authorization_warning',
        method: 'GET',
        auth: false,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/getCardholderOptions.ts":
/*!*********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/getCardholderOptions.ts ***!
  \*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getCardholderOptions = (segmentId, reqOpts) => {
    const fetchOptions = {
        url: '/settings/cardholder',
        method: 'GET',
        query: segmentId != null ? { segment_id: segmentId } : null,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/getEnterpriseSettings.ts":
/*!**********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/getEnterpriseSettings.ts ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getEnterpriseSettings = (reqOpts) => {
    const fetchOptions = {
        url: '/settings/enterprise',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/getInstantRewindTimeInSeconds.ts":
/*!******************************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/getInstantRewindTimeInSeconds.ts ***!
  \******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getInstantRewindTimeInSeconds = (reqOpts) => {
    return instance_1.api
        ._processRequest({
        url: `/settings/video`,
        method: `GET`,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    })
        .pipe(Rx.map((ret) => {
        return ret.instant_rewind_time_in_seconds;
    }));
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/getPasswordSettings.ts":
/*!********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/getPasswordSettings.ts ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
exports.getPasswordSettings = (reqOpts) => {
    const fetchOptions = {
        url: '/settings/password_policy',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map(R.omit(['version'])));
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/getSegmentationSettings.ts":
/*!************************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/getSegmentationSettings.ts ***!
  \************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getSegmentationSettings = (reqOpts) => {
    const fetchOptions = {
        url: '/settings/segmentation',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/getVersion.ts":
/*!***********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/getVersion.ts ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getVersion = (reqOpts) => {
    const fetchOptions = {
        url: '/version',
        method: 'GET',
        auth: false,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/getVisitSettings.ts":
/*!*****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/getVisitSettings.ts ***!
  \*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getVisitSettings = (reqOpts) => {
    const fetchOptions = {
        url: '/settings/visit',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/updatePasswordSettings.ts":
/*!***********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/updatePasswordSettings.ts ***!
  \***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.updatePasswordSettings = (settings, reqOpts) => {
    const fetchOptions = {
        url: '/settings/password_policy',
        method: 'PUT',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        body: settings,
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/settings/updateVisitSettings.ts":
/*!********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/settings/updateVisitSettings.ts ***!
  \********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.updateVisitSettings = (update, reqOpts) => {
    const fetchOptions = {
        url: '/settings/visit',
        method: 'PUT',
        body: update,
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/types.ts":
/*!*********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/types.ts ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });


/***/ }),

/***/ "../../packages/open-access-api/src/user/addManagedAccessLevels.ts":
/*!*******************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/addManagedAccessLevels.ts ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.addManagedAccessLevels = (userId, accessLevelIds, reqOpts) => {
    const fetchOptions = {
        url: `/user/${userId}/managed_access_levels`,
        method: 'POST',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        body: {
            access_level_list: accessLevelIds,
        },
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/addUserSegments.ts":
/*!************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/addUserSegments.ts ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.addUserSegments = (userId, segmentsIds, reqOpts) => {
    const fetchOptions = {
        url: `/user/${userId}/segments`,
        method: 'POST',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        body: {
            segment_list: segmentsIds,
        },
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/deleteManagedAccessLevels.ts":
/*!**********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/deleteManagedAccessLevels.ts ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.deleteManagedAccessLevels = (userId, accessLevelIds, reqOpts) => {
    const fetchOptions = {
        url: `/user/${userId}/managed_access_levels`,
        method: 'DELETE',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        body: {
            access_level_list: accessLevelIds,
        },
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/deleteUserSegments.ts":
/*!***************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/deleteUserSegments.ts ***!
  \***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.deleteUserSegments = (userId, segmentsIds, reqOpts) => {
    const fetchOptions = {
        url: `/user/${userId}/segments`,
        method: 'DELETE',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        body: {
            segment_list: segmentsIds,
        },
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/getEditableSegments.ts":
/*!****************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/getEditableSegments.ts ***!
  \****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getEditableSegments = (reqOpts) => {
    const fetchOptions = {
        url: '/editable_segments',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((x) => x.segment_list));
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/getLoggedInUser.ts":
/*!************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/getLoggedInUser.ts ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getLoggedInUser = (reqOpts) => {
    const fetchOptions = {
        url: '/logged_in_user',
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions).pipe(Rx.map((input) => ({
        username: input.user_name,
        firstName: input.first_name,
        lastName: input.last_name,
        ptzPriority: input.ptz_priority,
        id: input.user_id,
        permissionMap: input.permission_map,
        passwordExpirationTime: input.password_expiration_time,
    })));
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/getManagedAccessLevels.ts":
/*!*******************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/getManagedAccessLevels.ts ***!
  \*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getManagedAccessLevels = (userId, reqOpts) => {
    const fetchOptions = {
        url: `/user/${userId}/managed_access_levels`,
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((x) => x.access_level_list));
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/getUser.ts":
/*!****************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/getUser.ts ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.getUser = (userId, reqOpts) => {
    const fetchOptions = {
        url: `/user/${userId}`,
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/getUserSegments.ts":
/*!************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/getUserSegments.ts ***!
  \************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
exports.getUserSegments = (userId, reqOpts) => {
    const fetchOptions = {
        url: `/user/${userId}/segments`,
        method: 'GET',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
    };
    return instance_1.api
        ._processRequest(fetchOptions)
        .pipe(Rx.map((x) => x.segment_list));
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/updatePassword.ts":
/*!***********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/updatePassword.ts ***!
  \***********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.updatePassword = (values, reqOpts) => {
    const fetchOptions = {
        url: '/user_password',
        method: 'PUT',
        auth: false,
        body: {
            user_name: values.username,
            current_password: values.currentPassword,
            new_password: values.newPassword,
        },
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        query: {},
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/user/updateUser.ts":
/*!*******************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/user/updateUser.ts ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const instance_1 = __webpack_require__(/*! ../instance */ "../../packages/open-access-api/src/instance.ts");
exports.updateUser = (userId, values, reqOpts) => {
    const fetchOptions = {
        url: `/user/${userId}`,
        method: 'PUT',
        reqOpts: instance_1.api._getReqOptions(reqOpts),
        body: values,
    };
    return instance_1.api._processRequest(fetchOptions);
};


/***/ }),

/***/ "../../packages/open-access-api/src/utils.ts":
/*!*********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/open-access-api/src/utils.ts ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const lnl_1 = __webpack_require__(/*! types/lnl */ "../../packages/types/lnl.ts");
function toSnakeCase(obj) {
    return R.mapKeys(obj, key => R.snakeCase(key));
}
exports.toSnakeCase = toSnakeCase;
function toCamelCase(obj) {
    return R.mapKeys(obj, key => R.camelCase(key));
}
exports.toCamelCase = toCamelCase;
function mapResponse(obj) {
    return R.pipe(obj, toCamelCase, R.omit(['version']));
}
exports.mapResponse = mapResponse;
function mapInstances(result, noItemWrap = false) {
    return {
        pageNumber: result.page_number,
        pageSize: result.page_size,
        totalPages: result.total_pages,
        total: result.total_items,
        count: result.count,
        items: (result.item_list || []).map((x) => noItemWrap ? x : x.property_value_map),
    };
}
exports.mapInstances = mapInstances;
function getAllPages(options, extraOptions) {
    const { getPageFetchOptions, api, noItemWrap } = options;
    const { maxPages, onProgress } = extraOptions || {
        maxPages: Infinity,
        onProgress: null,
    };
    const firstPage$ = api._processRequest(getPageFetchOptions(1));
    return firstPage$.pipe(Rx.map(x => mapInstances(x, noItemWrap)), Rx.flatMap(firstPage => {
        const max = Math.min(firstPage.totalPages, maxPages || Infinity) + 1;
        const firstPageItems$ = Rx.of(firstPage.items);
        if (max <= 2) {
            if (onProgress) {
                onProgress.next(100);
                onProgress.complete();
            }
            return firstPageItems$;
        }
        const notify = new Rx.Subject();
        const requests = R.range(2, max).map(getPageFetchOptions);
        if (!requests.length) {
            return firstPageItems$;
        }
        let loadedPages = 1;
        if (onProgress) {
            const totalPages = max - 1;
            const getPercent = (count) => Math.round((count / totalPages) * 100);
            onProgress.next(getPercent(1));
            notify.subscribe({
                next: () => {
                    loadedPages++;
                    onProgress.next(getPercent(loadedPages));
                    if (loadedPages === totalPages) {
                        onProgress.complete();
                    }
                },
            });
        }
        const requests$ = api
            ._processRequests(requests, notify)
            .pipe(Rx.map(R.flatMap(x => x.result.item_list.map((item) => noItemWrap ? item : item.property_value_map))));
        return Rx.concatObs(firstPageItems$, requests$);
    }), Rx.reduce((acc, page) => acc.concat(page), []));
}
exports.getAllPages = getAllPages;
function getAllWithProgress(getAll) {
    return Rx.Observable.create((observer) => {
        const onProgress = new Rx.Subject();
        const onProgressSubscription = onProgress.subscribe({
            next: progress => observer.next({ type: 'progress', progress }),
        });
        const subscription = getAll(onProgress).subscribe({
            next: result => observer.next({ type: 'result', result }),
            error: error => observer.error(error),
            complete: () => observer.complete(),
        });
        return () => {
            subscription.unsubscribe();
            onProgressSubscription.unsubscribe();
        };
    });
}
exports.getAllWithProgress = getAllWithProgress;
function fixIdStr(typeName, items) {
    const fixTypes = [lnl_1.TypeName.Lnl_Badge];
    if (fixTypes.includes(typeName)) {
        items.forEach((item) => {
            item.ID = item.ID_str;
            delete item.ID_str;
        });
    }
}
exports.fixIdStr = fixIdStr;
function processSingleInstance(result, opts) {
    if (result.items.length === 0) {
        if (opts.allowEmpty) {
            return null;
        }
        const err = new Error('Instance not found');
        err.httpCode = 404;
        throw err;
    }
    if (result.items.length > 1) {
        throw new Error(`Expected a single instance. Received ${result.items.length} instances.`);
    }
    return result.items[0];
}
exports.processSingleInstance = processSingleInstance;
function decodeEscapeCodesInObject(str) {
    const encodedJSON = JSON.stringify(str);
    const escapeSequences = {
        '&lt;': '<',
        '&gt;': '>',
        '&amp;': '&',
        '&quot;': '\\"',
    };
    const decodedJSON = encodedJSON
        .replace(/&#x([0-9A-F]+);/g, (match, dec) => {
        const char = String.fromCharCode(parseInt(dec, 16));
        const charJSON = JSON.stringify(char);
        return charJSON.substring(1, charJSON.length - 1);
    })
        .replace(/(&(amp|lt|gt|quot);)/g, match => { var _a; return (_a = escapeSequences[match]) !== null && _a !== void 0 ? _a : match; });
    return JSON.parse(decodedJSON);
}
exports.decodeEscapeCodesInObject = decodeEscapeCodesInObject;


/***/ }),

/***/ "../../packages/r/camelcase.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/camelcase.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/* tslint:disable:prefer-template  **/
Object.defineProperty(exports, "__esModule", { value: true });
function preserveCamelCase(str) {
    let isLastCharLower = false;
    let isLastCharUpper = false;
    let isLastLastCharUpper = false;
    for (let i = 0; i < str.length; i++) {
        const c = str[i];
        if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) {
            str = str.substr(0, i) + '-' + str.substr(i);
            isLastCharLower = false;
            isLastLastCharUpper = isLastCharUpper;
            isLastCharUpper = true;
            i++;
        }
        else if (isLastCharUpper &&
            isLastLastCharUpper &&
            /[a-zA-Z]/.test(c) &&
            c.toLowerCase() === c) {
            str = str.substr(0, i - 1) + '-' + str.substr(i - 1);
            isLastLastCharUpper = isLastCharUpper;
            isLastCharUpper = false;
            isLastCharLower = true;
        }
        else {
            isLastCharLower = c.toLowerCase() === c;
            isLastLastCharUpper = isLastCharUpper;
            isLastCharUpper = c.toUpperCase() === c;
        }
    }
    return str;
}
function camelCase(str) {
    if (arguments.length > 1) {
        str = Array.from(arguments)
            .map(x => x.trim())
            .filter(x => x.length)
            .join('-');
    }
    else {
        str = str.trim();
    }
    if (str.length === 0) {
        return '';
    }
    if (str.length === 1) {
        return str.toLowerCase();
    }
    if (/^[a-z0-9]+$/.test(str)) {
        return str;
    }
    const hasUpperCase = str !== str.toLowerCase();
    if (hasUpperCase) {
        str = preserveCamelCase(str);
    }
    return str
        .replace(/^[_.\- ]+/, '')
        .toLowerCase()
        .replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase());
}
exports.default = camelCase;


/***/ }),

/***/ "../../packages/r/index.ts":
/*!***************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/index.ts ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const snakeCase_1 = __webpack_require__(/*! ./snakeCase */ "../../packages/r/snakeCase.ts");
exports.snakeCase = snakeCase_1.snakeCase;
const camelcase_1 = __importDefault(__webpack_require__(/*! ./camelcase */ "../../packages/r/camelcase.ts"));
exports.camelCase = camelcase_1.default;
const debounce_1 = __importDefault(__webpack_require__(/*! debounce */ "debounce"));
exports.debounce = debounce_1.default;
__export(__webpack_require__(/*! ./src/compact */ "../../packages/r/src/compact.ts"));
__export(__webpack_require__(/*! ./src/difference */ "../../packages/r/src/difference.ts"));
__export(__webpack_require__(/*! ./src/indexBy */ "../../packages/r/src/indexBy.ts"));
__export(__webpack_require__(/*! ./src/map */ "../../packages/r/src/map.ts"));
__export(__webpack_require__(/*! ./src/pipe */ "../../packages/r/src/pipe.ts"));
__export(__webpack_require__(/*! ./src/range */ "../../packages/r/src/range.ts"));
__export(__webpack_require__(/*! ./src/chunk */ "../../packages/r/src/chunk.ts"));
__export(__webpack_require__(/*! ./src/pick */ "../../packages/r/src/pick.ts"));
__export(__webpack_require__(/*! ./src/omit */ "../../packages/r/src/omit.ts"));
__export(__webpack_require__(/*! ./src/once */ "../../packages/r/src/once.ts"));
__export(__webpack_require__(/*! ./src/filter */ "../../packages/r/src/filter.ts"));
__export(__webpack_require__(/*! ./src/getOr */ "../../packages/r/src/getOr.ts"));
__export(__webpack_require__(/*! ./src/flatten */ "../../packages/r/src/flatten.ts"));
__export(__webpack_require__(/*! ./src/flatMap */ "../../packages/r/src/flatMap.ts"));
__export(__webpack_require__(/*! ./src/last */ "../../packages/r/src/last.ts"));
__export(__webpack_require__(/*! ./src/findIndex */ "../../packages/r/src/findIndex.ts"));
__export(__webpack_require__(/*! ./src/clamp */ "../../packages/r/src/clamp.ts"));
__export(__webpack_require__(/*! ./src/intersection */ "../../packages/r/src/intersection.ts"));
__export(__webpack_require__(/*! ./src/equals */ "../../packages/r/src/equals.ts"));
__export(__webpack_require__(/*! ./src/sort */ "../../packages/r/src/sort.ts"));
__export(__webpack_require__(/*! ./src/splitAt */ "../../packages/r/src/splitAt.ts"));
__export(__webpack_require__(/*! ./src/takeWhile */ "../../packages/r/src/takeWhile.ts"));
__export(__webpack_require__(/*! ./src/uniq */ "../../packages/r/src/uniq.ts"));
__export(__webpack_require__(/*! ./src/splitWhen */ "../../packages/r/src/splitWhen.ts"));
__export(__webpack_require__(/*! ./src/type */ "../../packages/r/src/type.ts"));
__export(__webpack_require__(/*! ./src/clone */ "../../packages/r/src/clone.ts"));
__export(__webpack_require__(/*! ./src/groupBy */ "../../packages/r/src/groupBy.ts"));
__export(__webpack_require__(/*! ./src/toPairs */ "../../packages/r/src/toPairs.ts"));
__export(__webpack_require__(/*! ./src/sortBy */ "../../packages/r/src/sortBy.ts"));
__export(__webpack_require__(/*! ./src/find */ "../../packages/r/src/find.ts"));
__export(__webpack_require__(/*! ./src/prop */ "../../packages/r/src/prop.ts"));
__export(__webpack_require__(/*! ./src/reject */ "../../packages/r/src/reject.ts"));
__export(__webpack_require__(/*! ./src/dropLast */ "../../packages/r/src/dropLast.ts"));
__export(__webpack_require__(/*! ./src/reduce */ "../../packages/r/src/reduce.ts"));
__export(__webpack_require__(/*! ./src/merge */ "../../packages/r/src/merge.ts"));
__export(__webpack_require__(/*! ./src/mergeAll */ "../../packages/r/src/mergeAll.ts"));
__export(__webpack_require__(/*! ./src/objOf */ "../../packages/r/src/objOf.ts"));
__export(__webpack_require__(/*! ./src/concat */ "../../packages/r/src/concat.ts"));
__export(__webpack_require__(/*! ./src/createPipe */ "../../packages/r/src/createPipe.ts"));
__export(__webpack_require__(/*! ./src/anyPass */ "../../packages/r/src/anyPass.ts"));
__export(__webpack_require__(/*! ./src/set */ "../../packages/r/src/set.ts"));
__export(__webpack_require__(/*! ./src/addProp */ "../../packages/r/src/addProp.ts"));
__export(__webpack_require__(/*! ./src/indexByIdentity */ "../../packages/r/src/indexByIdentity.ts"));
__export(__webpack_require__(/*! ./src/compareAscending */ "../../packages/r/src/compareAscending.ts"));
__export(__webpack_require__(/*! ./src/randomString */ "../../packages/r/src/randomString.ts"));
__export(__webpack_require__(/*! ./src/noop */ "../../packages/r/src/noop.ts"));
__export(__webpack_require__(/*! ./src/mapKeys */ "../../packages/r/src/mapKeys.ts"));
__export(__webpack_require__(/*! ./src/capitalize */ "../../packages/r/src/capitalize.ts"));
__export(__webpack_require__(/*! ./src/uniqBy */ "../../packages/r/src/uniqBy.ts"));
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
exports.delay = delay;


/***/ }),

/***/ "../../packages/r/snakeCase.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/snakeCase.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// from lodash
Object.defineProperty(exports, "__esModule", { value: true });
// const reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
const rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
const rsApos = "['\u2019]", rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' +
    rsAstralRange +
    rsBreakRange +
    rsDigits +
    rsDingbatRange +
    rsLowerRange +
    rsUpperRange +
    ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
const rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' +
    rsZWJ +
    '(?:' +
    [rsNonAstral, rsRegional, rsSurrPair].join('|') +
    ')' +
    rsOptVar +
    reOptMod +
    ')*', rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)', rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;
/** Used to match complex or compound words. */
const reUnicodeWord = RegExp([
    rsUpper +
        '?' +
        rsLower +
        '+' +
        rsOptContrLower +
        '(?=' +
        [rsBreak, rsUpper, '$'].join('|') +
        ')',
    rsMiscUpper +
        '+' +
        rsOptContrUpper +
        '(?=' +
        [rsBreak, rsUpper + rsMiscLower, '$'].join('|') +
        ')',
    rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
    rsUpper + '+' + rsOptContrUpper,
    rsOrdUpper,
    rsOrdLower,
    rsDigits,
    rsEmoji,
].join('|'), 'g');
exports.snakeCase = (str) => {
    return str.match(reUnicodeWord).join('_').toLowerCase();
};


/***/ }),

/***/ "../../packages/r/src/addProp.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/addProp.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function addProp(arg1, arg2, arg3) {
    if (arguments.length === 2) {
        return (object) => _addProp(object, arg1, arg2);
    }
    return _addProp(arg1, arg2, arg3);
}
exports.addProp = addProp;
function _addProp(obj, prop, value) {
    return {
        ...obj,
        [prop]: value,
    };
}


/***/ }),

/***/ "../../packages/r/src/anyPass.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/anyPass.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function anyPass(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _anyPass(data, arg1);
    }
    return _anyPass(arg1, arg2);
}
exports.anyPass = anyPass;
function _anyPass(data, fns) {
    return fns.some(fn => fn(data));
}


/***/ }),

/***/ "../../packages/r/src/capitalize.ts":
/*!************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/capitalize.ts ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
exports.capitalize = capitalize;


/***/ }),

/***/ "../../packages/r/src/chunk.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/chunk.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function chunk(array, size) {
    const ret = [];
    let current = null;
    array.forEach(x => {
        if (!current) {
            current = [];
            ret.push(current);
        }
        current.push(x);
        if (current.length === size) {
            current = null;
        }
    });
    return ret;
}
exports.chunk = chunk;


/***/ }),

/***/ "../../packages/r/src/clamp.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/clamp.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function clamp(value, limits) {
    if (limits.min != null) {
        if (limits.min > value) {
            return limits.min;
        }
    }
    if (limits.max != null) {
        if (limits.max < value) {
            return limits.max;
        }
    }
    return value;
}
exports.clamp = clamp;


/***/ }),

/***/ "../../packages/r/src/clone.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/clone.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// from https://github.com/ramda/ramda/blob/master/source/internal/_clone.js
Object.defineProperty(exports, "__esModule", { value: true });
const type_1 = __webpack_require__(/*! ./type */ "../../packages/r/src/type.ts");
function _cloneRegExp(pattern) {
    return new RegExp(pattern.source, (pattern.global ? 'g' : '') +
        (pattern.ignoreCase ? 'i' : '') +
        (pattern.multiline ? 'm' : '') +
        (pattern.sticky ? 'y' : '') +
        (pattern.unicode ? 'u' : ''));
}
function _clone(value, refFrom, refTo, deep) {
    function copy(copiedValue) {
        const len = refFrom.length;
        let idx = 0;
        while (idx < len) {
            if (value === refFrom[idx]) {
                return refTo[idx];
            }
            idx += 1;
        }
        refFrom[idx + 1] = value;
        refTo[idx + 1] = copiedValue;
        // tslint:disable-next-line:forin
        for (const key in value) {
            copiedValue[key] = deep
                ? _clone(value[key], refFrom, refTo, true)
                : value[key];
        }
        return copiedValue;
    }
    switch (type_1.type(value)) {
        case 'Object':
            return copy({});
        case 'Array':
            return copy([]);
        case 'Date':
            return new Date(value.valueOf());
        case 'RegExp':
            return _cloneRegExp(value);
        default:
            return value;
    }
}
function clone(value) {
    return value != null && typeof value.clone === 'function'
        ? value.clone()
        : _clone(value, [], [], true);
}
exports.clone = clone;


/***/ }),

/***/ "../../packages/r/src/compact.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/compact.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.compact = (items) => items.filter(x => !!x);


/***/ }),

/***/ "../../packages/r/src/compareAscending.ts":
/*!******************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/compareAscending.ts ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function compareAscending(value, other) {
    const isSymbol = (val) => false;
    if (value !== other) {
        const valIsDefined = value !== undefined;
        const valIsNull = value === null;
        const valIsReflexive = value === value;
        const valIsSymbol = isSymbol(value);
        const othIsDefined = other !== undefined;
        const othIsNull = other === null;
        const othIsReflexive = other === other;
        const othIsSymbol = isSymbol(other);
        if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
            (valIsSymbol &&
                othIsDefined &&
                othIsReflexive &&
                !othIsNull &&
                !othIsSymbol) ||
            (valIsNull && othIsDefined && othIsReflexive) ||
            (!valIsDefined && othIsReflexive) ||
            !valIsReflexive) {
            return 1;
        }
        if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
            (othIsSymbol &&
                valIsDefined &&
                valIsReflexive &&
                !valIsNull &&
                !valIsSymbol) ||
            (othIsNull && valIsDefined && valIsReflexive) ||
            (!othIsDefined && valIsReflexive) ||
            !othIsReflexive) {
            return -1;
        }
    }
    return 0;
}
exports.compareAscending = compareAscending;


/***/ }),

/***/ "../../packages/r/src/concat.ts":
/*!********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/concat.ts ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function concat(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _concat(data, arg1);
    }
    return _concat(arg1, arg2);
}
exports.concat = concat;
function _concat(arr1, arr2) {
    return arr1.concat(arr2);
}


/***/ }),

/***/ "../../packages/r/src/createPipe.ts":
/*!************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/createPipe.ts ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function createPipe(...operations) {
    return (value) => operations.reduce((acc, fn) => fn(acc), value);
}
exports.createPipe = createPipe;


/***/ }),

/***/ "../../packages/r/src/difference.ts":
/*!************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/difference.ts ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function difference(arg1, arg2) {
    if (arguments.length === 1) {
        return (array) => {
            return _difference(array, arg1);
        };
    }
    return _difference(arg1, arg2);
}
exports.difference = difference;
function _difference(array, other) {
    const set = new Set(other);
    return array.filter(x => !set.has(x));
}


/***/ }),

/***/ "../../packages/r/src/dropLast.ts":
/*!**********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/dropLast.ts ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function dropLast(items, count) {
    const copy = [...items];
    copy.splice(-count);
    return copy;
}
exports.dropLast = dropLast;


/***/ }),

/***/ "../../packages/r/src/equals.ts":
/*!********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/equals.ts ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
// from https://github.com/epoberezkin/fast-deep-equal/blob/master/index.js
const isArray = Array.isArray;
const keyList = Object.keys;
const hasProp = Object.prototype.hasOwnProperty;
function equals(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _equals(data, arg1);
    }
    return _equals(arg1, arg2);
}
exports.equals = equals;
function _equals(a, b) {
    if (a === b) {
        return true;
    }
    if (a && b && typeof a === 'object' && typeof b === 'object') {
        const arrA = isArray(a);
        const arrB = isArray(b);
        let i;
        let length;
        let key;
        if (arrA && arrB) {
            length = a.length;
            if (length !== b.length) {
                return false;
            }
            for (i = length; i-- !== 0;) {
                if (!equals(a[i], b[i])) {
                    return false;
                }
            }
            return true;
        }
        if (arrA !== arrB) {
            return false;
        }
        const dateA = a instanceof Date;
        const dateB = b instanceof Date;
        if (dateA !== dateB) {
            return false;
        }
        if (dateA && dateB) {
            return a.getTime() === b.getTime();
        }
        const regexpA = a instanceof RegExp;
        const regexpB = b instanceof RegExp;
        if (regexpA !== regexpB) {
            return false;
        }
        if (regexpA && regexpB) {
            return a.toString() === b.toString();
        }
        const keys = keyList(a);
        length = keys.length;
        if (length !== keyList(b).length) {
            return false;
        }
        for (i = length; i-- !== 0;) {
            if (!hasProp.call(b, keys[i])) {
                return false;
            }
        }
        for (i = length; i-- !== 0;) {
            key = keys[i];
            if (!equals(a[key], b[key])) {
                return false;
            }
        }
        return true;
    }
    return a !== a && b !== b;
}
exports._equals = _equals;


/***/ }),

/***/ "../../packages/r/src/filter.ts":
/*!********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/filter.ts ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function filter(arg1, arg2) {
    if (arguments.length === 1) {
        return (items) => _filter(items, arg1);
    }
    return _filter(arg1, arg2);
}
exports.filter = filter;
function _filter(items, fn) {
    return items.filter(item => fn(item));
}


/***/ }),

/***/ "../../packages/r/src/find.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/find.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function find(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _find(data, arg1);
    }
    return _find(arg1, arg2);
}
exports.find = find;
function _find(array, fn) {
    return array.find(x => fn(x));
}


/***/ }),

/***/ "../../packages/r/src/findIndex.ts":
/*!***********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/findIndex.ts ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function findIndex(array, fn) {
    for (let i = 0; i < array.length; i++) {
        if (fn(array[i])) {
            return i;
        }
    }
    return -1;
}
exports.findIndex = findIndex;


/***/ }),

/***/ "../../packages/r/src/flatMap.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/flatMap.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const flatten_1 = __webpack_require__(/*! ./flatten */ "../../packages/r/src/flatten.ts");
function flatMap(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => {
            return _flatMap(data, arg1);
        };
    }
    return _flatMap(arg1, arg2);
}
exports.flatMap = flatMap;
function _flatMap(array, fn) {
    return flatten_1.flatten(array.map(item => fn(item)));
}


/***/ }),

/***/ "../../packages/r/src/flatten.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/flatten.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function flatten(items) {
    const ret = [];
    items.forEach(item => {
        if (Array.isArray(item)) {
            ret.push(...item);
        }
        else {
            ret.push(item);
        }
    });
    return ret;
}
exports.flatten = flatten;


/***/ }),

/***/ "../../packages/r/src/getOr.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/getOr.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function getOr(arg1, arg2, arg3) {
    if (arguments.length === 2) {
        return (data) => _getOr(data, arg1, arg2);
    }
    return _getOr(arg1, arg2, arg3);
}
exports.getOr = getOr;
function _getOr(object, path, defaultValue) {
    let current = object;
    for (const prop of path) {
        if (current == null || current[prop] == null) {
            return defaultValue;
        }
        current = current[prop];
    }
    return current;
}


/***/ }),

/***/ "../../packages/r/src/groupBy.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/groupBy.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function groupBy(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _groupBy(data, arg1);
    }
    return _groupBy(arg1, arg2);
}
exports.groupBy = groupBy;
function _groupBy(array, fn) {
    const ret = {};
    array.forEach(item => {
        const key = fn(item).toString();
        if (!ret[key]) {
            ret[key] = [];
        }
        ret[key].push(item);
    });
    return ret;
}


/***/ }),

/***/ "../../packages/r/src/indexBy.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/indexBy.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function indexBy(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _indexBy(data, arg1);
    }
    return _indexBy(arg1, arg2);
}
exports.indexBy = indexBy;
function _indexBy(array, fn) {
    const ret = {};
    array.forEach(item => {
        ret[String(fn(item))] = item;
    });
    return ret;
}


/***/ }),

/***/ "../../packages/r/src/indexByIdentity.ts":
/*!*****************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/indexByIdentity.ts ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function indexByIdentity(items) {
    return items.reduce((acc, item) => {
        acc[item.toString()] = item;
        return acc;
    }, {});
}
exports.indexByIdentity = indexByIdentity;


/***/ }),

/***/ "../../packages/r/src/intersection.ts":
/*!**************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/intersection.ts ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function intersection(source, other) {
    const set = new Set(other);
    return source.filter(x => set.has(x));
}
exports.intersection = intersection;


/***/ }),

/***/ "../../packages/r/src/last.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/last.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function last(array) {
    return array[array.length - 1];
}
exports.last = last;


/***/ }),

/***/ "../../packages/r/src/map.ts":
/*!*****************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/map.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function map(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => {
            return _map(data, arg1);
        };
    }
    return _map(arg1, arg2);
}
exports.map = map;
function _map(array, fn) {
    return array.map(item => fn(item));
}


/***/ }),

/***/ "../../packages/r/src/mapKeys.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/mapKeys.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function mapKeys(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _mapKeys(data, arg1);
    }
    return _mapKeys(arg1, arg2);
}
exports.mapKeys = mapKeys;
function _mapKeys(obj, fn) {
    return Object.keys(obj).reduce((acc, key) => {
        acc[fn(key, obj[key])] = obj[key];
        return acc;
    }, {});
}


/***/ }),

/***/ "../../packages/r/src/merge.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/merge.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function merge(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _merge(data, arg1);
    }
    return _merge(arg1, arg2);
}
exports.merge = merge;
function _merge(a, b) {
    // tslint:disable-next-line:prefer-object-spread
    return Object.assign({}, a, b);
}


/***/ }),

/***/ "../../packages/r/src/mergeAll.ts":
/*!**********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/mergeAll.ts ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function mergeAll(items) {
    return items.reduce((acc, x) => ({ ...acc, ...x }), {});
}
exports.mergeAll = mergeAll;


/***/ }),

/***/ "../../packages/r/src/noop.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/noop.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.noop = () => undefined;


/***/ }),

/***/ "../../packages/r/src/objOf.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/objOf.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function objOf(arg1, arg2) {
    if (arguments.length === 1) {
        return (object) => _objOf(object, arg1);
    }
    return _objOf(arg1, arg2);
}
exports.objOf = objOf;
function _objOf(value, prop) {
    return { [prop]: value };
}


/***/ }),

/***/ "../../packages/r/src/omit.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/omit.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function omit(arg1, arg2) {
    if (arguments.length === 1) {
        return (object) => _omit(object, arg1);
    }
    return _omit(arg1, arg2);
}
exports.omit = omit;
function _omit(object, names) {
    const set = new Set(names);
    return Object.entries(object).reduce((acc, [name, value]) => {
        if (!set.has(name)) {
            acc[name] = value;
        }
        return acc;
    }, {});
}


/***/ }),

/***/ "../../packages/r/src/once.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/once.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function once(fn) {
    let called = false;
    return () => {
        if (!called) {
            fn();
            called = true;
        }
    };
}
exports.once = once;


/***/ }),

/***/ "../../packages/r/src/pick.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/pick.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function pick(arg1, arg2) {
    if (arguments.length === 1) {
        return (object) => _pick(object, arg1);
    }
    return _pick(arg1, arg2);
}
exports.pick = pick;
function _pick(object, names) {
    return names.reduce((acc, name) => {
        if (object.hasOwnProperty(name)) {
            acc[name] = object[name];
        }
        return acc;
    }, {});
}


/***/ }),

/***/ "../../packages/r/src/pipe.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/pipe.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Perform left-to-right function composition.
 * @param value The initial value.
 * @param operations the list of operations to apply.
 * @example
 *    R.pipe(
 *      [1, 2, 3, 4],
 *      R.map(x => x * 2),
 *      arr => [arr[0] + arr[1], arr[2] + arr[3]],
 *    ) // [6, 14]
 *
 *
 * @data_first
 */
function pipe(value, ...operations) {
    return operations.reduce((acc, fn) => fn(acc), value);
}
exports.pipe = pipe;


/***/ }),

/***/ "../../packages/r/src/prop.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/prop.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function prop(name) {
    return (obj) => obj[name];
}
exports.prop = prop;


/***/ }),

/***/ "../../packages/r/src/randomString.ts":
/*!**************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/randomString.ts ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const range_1 = __webpack_require__(/*! ./range */ "../../packages/r/src/range.ts");
function randomString(length) {
    const characterSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const randomChar = () => characterSet[Math.floor(Math.random() * characterSet.length)];
    return range_1.range(0, length).reduce(text => text + randomChar(), '');
}
exports.randomString = randomString;


/***/ }),

/***/ "../../packages/r/src/range.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/range.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function range(arg1, arg2) {
    const [start, end] = arguments.length === 1 ? [0, arg1] : [arg1, arg2];
    const ret = [];
    for (let i = start; i < end; i++) {
        ret.push(i);
    }
    return ret;
}
exports.range = range;


/***/ }),

/***/ "../../packages/r/src/reduce.ts":
/*!********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/reduce.ts ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function reduce(arg1, arg2, arg3) {
    if (arguments.length === 2) {
        return (data) => _reduce(data, arg1, arg2);
    }
    return _reduce(arg1, arg2, arg3);
}
exports.reduce = reduce;
function _reduce(items, fn, initialValue) {
    return items.reduce((acc, item) => fn(acc, item), initialValue);
}


/***/ }),

/***/ "../../packages/r/src/reject.ts":
/*!********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/reject.ts ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function reject(arg1, arg2) {
    if (arguments.length === 1) {
        return (items) => _reject(items, arg1);
    }
    return _reject(arg1, arg2);
}
exports.reject = reject;
function _reject(items, fn) {
    return items.filter(item => !fn(item));
}


/***/ }),

/***/ "../../packages/r/src/set.ts":
/*!*****************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/set.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function set(arg1, arg2, arg3) {
    if (arguments.length === 2) {
        return (object) => _set(object, arg1, arg2);
    }
    return _set(arg1, arg2, arg3);
}
exports.set = set;
function _set(obj, prop, value) {
    return {
        ...obj,
        [prop]: value,
    };
}


/***/ }),

/***/ "../../packages/r/src/sort.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/sort.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function sort(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => {
            return [...data].sort(arg1);
        };
    }
    return [...arg1].sort(arg2);
}
exports.sort = sort;


/***/ }),

/***/ "../../packages/r/src/sortBy.ts":
/*!********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/sortBy.ts ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function sortBy(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => _sortBy(data, arg1);
    }
    return _sortBy(arg1, arg2);
}
exports.sortBy = sortBy;
function _sortBy(items, fn) {
    const copied = [...items];
    return copied.sort((a, b) => {
        const aa = fn(a);
        const bb = fn(b);
        return aa < bb ? -1 : aa > bb ? 1 : 0;
    });
}


/***/ }),

/***/ "../../packages/r/src/splitAt.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/splitAt.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function splitAt(items, index) {
    const copy = [...items];
    const tail = copy.splice(index);
    return [copy, tail];
}
exports.splitAt = splitAt;


/***/ }),

/***/ "../../packages/r/src/splitWhen.ts":
/*!***********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/splitWhen.ts ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const splitAt_1 = __webpack_require__(/*! ./splitAt */ "../../packages/r/src/splitAt.ts");
function splitWhen(array, fn) {
    for (let i = 0; i < array.length; i++) {
        if (fn(array[i])) {
            return splitAt_1.splitAt(array, i);
        }
    }
    return [array, []];
}
exports.splitWhen = splitWhen;


/***/ }),

/***/ "../../packages/r/src/takeWhile.ts":
/*!***********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/takeWhile.ts ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function takeWhile(items, fn) {
    const ret = [];
    for (const item of items) {
        if (!fn(item)) {
            break;
        }
        ret.push(item);
    }
    return ret;
}
exports.takeWhile = takeWhile;


/***/ }),

/***/ "../../packages/r/src/toPairs.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/toPairs.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function toPairs(object) {
    return Object.entries(object);
}
exports.toPairs = toPairs;


/***/ }),

/***/ "../../packages/r/src/type.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/type.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// from https://github.com/ramda/ramda/blob/master/source/type.js
Object.defineProperty(exports, "__esModule", { value: true });
function type(val) {
    return val === null
        ? 'Null'
        : val === undefined
            ? 'Undefined'
            : Object.prototype.toString.call(val).slice(8, -1);
}
exports.type = type;


/***/ }),

/***/ "../../packages/r/src/uniq.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/uniq.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function uniq(array) {
    const set = new Set();
    return array.filter(item => {
        if (set.has(item)) {
            return false;
        }
        set.add(item);
        return true;
    });
}
exports.uniq = uniq;


/***/ }),

/***/ "../../packages/r/src/uniqBy.ts":
/*!********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/r/src/uniqBy.ts ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function _uniqBy(array, fn) {
    const set = new Set();
    return array.filter(item => {
        const key = fn(item);
        if (set.has(key)) {
            return false;
        }
        set.add(key);
        return true;
    });
}
function uniqBy(arg1, arg2) {
    if (arguments.length === 1) {
        return (data) => {
            return _uniqBy(data, arg1);
        };
    }
    return _uniqBy(arg1, arg2);
}
exports.uniqBy = uniqBy;


/***/ }),

/***/ "../../packages/rx/index.ts":
/*!****************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/rx/index.ts ***!
  \****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const typeless_1 = __webpack_require__(/*! typeless */ "../../packages/typeless/index.ts");
exports.waitForType = typeless_1.waitForType;
exports.ofType = typeless_1.ofType;
const internal_compatibility_1 = __webpack_require__(/*! rxjs/internal-compatibility */ "rxjs/internal-compatibility");
exports.fromPromise = internal_compatibility_1.fromPromise;
var rxjs_1 = __webpack_require__(/*! rxjs */ "rxjs");
exports.Subject = rxjs_1.Subject;
exports.forkJoin = rxjs_1.forkJoin;
exports.empty = rxjs_1.empty;
exports.of = rxjs_1.of;
exports.timer = rxjs_1.timer;
exports.from = rxjs_1.from;
exports.defer = rxjs_1.defer;
exports.Observable = rxjs_1.Observable;
exports.interval = rxjs_1.interval;
exports.concatObs = rxjs_1.concat;
exports.mergeObs = rxjs_1.merge;
exports.raceObs = rxjs_1.race;
exports.throwObs = rxjs_1.throwError;
__export(__webpack_require__(/*! rxjs/operators */ "rxjs/operators"));
__export(__webpack_require__(/*! ./src/catchLog */ "../../packages/rx/src/catchLog.ts"));
__export(__webpack_require__(/*! ./src/log */ "../../packages/rx/src/log.ts"));
__export(__webpack_require__(/*! ./src/mergeToArrayObs */ "../../packages/rx/src/mergeToArrayObs.ts"));
__export(__webpack_require__(/*! ./src/waitForTypeIf */ "../../packages/rx/src/waitForTypeIf.ts"));
var ajax_1 = __webpack_require__(/*! rxjs/ajax */ "rxjs/ajax");
exports.ajax = ajax_1.ajax;


/***/ }),

/***/ "../../packages/rx/src/catchLog.ts":
/*!***********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/rx/src/catchLog.ts ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const operators_1 = __webpack_require__(/*! rxjs/operators */ "rxjs/operators");
exports.catchLog = (fn) => operators_1.catchError((err, source) => {
    console.error(err);
    if (true) {
        console.error(err);
    }
    return fn(err, source);
});


/***/ }),

/***/ "../../packages/rx/src/log.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/rx/src/log.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const operators_1 = __webpack_require__(/*! rxjs/operators */ "rxjs/operators");
exports.log = (name) => (obs
// tslint:disable-next-line:no-console
) => obs.pipe(operators_1.tap((...args) => console.log(name, ...args)));


/***/ }),

/***/ "../../packages/rx/src/mergeToArrayObs.ts":
/*!******************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/rx/src/mergeToArrayObs.ts ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const rxjs_1 = __webpack_require__(/*! rxjs */ "rxjs");
const operators_1 = __webpack_require__(/*! rxjs/operators */ "rxjs/operators");
exports.mergeToArrayObs = (args) => rxjs_1.merge(...args).pipe(operators_1.toArray());


/***/ }),

/***/ "../../packages/rx/src/waitForTypeIf.ts":
/*!****************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/rx/src/waitForTypeIf.ts ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const typeless_1 = __webpack_require__(/*! typeless */ "../../packages/typeless/index.ts");
const rxjs_1 = __webpack_require__(/*! rxjs */ "rxjs");
exports.waitForTypeIf = (action$, type, fn) => {
    if (fn()) {
        return rxjs_1.of(null);
    }
    return action$.pipe(typeless_1.waitForType(type));
};


/***/ }),

/***/ "../../packages/typeless/index.ts":
/*!**********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/index.ts ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./src/createActions */ "../../packages/typeless/src/createActions.ts"));
__export(__webpack_require__(/*! ./src/combineReducers */ "../../packages/typeless/src/combineReducers.ts"));
__export(__webpack_require__(/*! ./src/createConnect */ "../../packages/typeless/src/createConnect.ts"));
__export(__webpack_require__(/*! ./src/createReducer */ "../../packages/typeless/src/createReducer.ts"));
__export(__webpack_require__(/*! ./src/createEpic */ "../../packages/typeless/src/createEpic.ts"));
__export(__webpack_require__(/*! ./src/ofType */ "../../packages/typeless/src/ofType.ts"));
__export(__webpack_require__(/*! ./src/waitForType */ "../../packages/typeless/src/waitForType.ts"));
__export(__webpack_require__(/*! ./src/pick */ "../../packages/typeless/src/pick.ts"));
__export(__webpack_require__(/*! ./src/checkExhaust */ "../../packages/typeless/src/checkExhaust.ts"));
__export(__webpack_require__(/*! ./src/enhanceReducer */ "../../packages/typeless/src/enhanceReducer.ts"));
__export(__webpack_require__(/*! ./src/actions */ "../../packages/typeless/src/actions.ts"));
__export(__webpack_require__(/*! ./src/withBatch */ "../../packages/typeless/src/withBatch.ts"));
__export(__webpack_require__(/*! ./src/withReset */ "../../packages/typeless/src/withReset.ts"));
__export(__webpack_require__(/*! ./src/GetProps */ "../../packages/typeless/src/GetProps.ts"));
__export(__webpack_require__(/*! ./src/redux-observable */ "../../packages/typeless/src/redux-observable/index.ts"));
__export(__webpack_require__(/*! ./src/useActions */ "../../packages/typeless/src/useActions.ts"));
__export(__webpack_require__(/*! ./src/useMappedState */ "../../packages/typeless/src/useMappedState.ts"));
__export(__webpack_require__(/*! ./src/createReducerNext */ "../../packages/typeless/src/createReducerNext.ts"));


/***/ }),

/***/ "../../packages/typeless/src/ChainedReducer.ts":
/*!***********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/ChainedReducer.ts ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const immer_1 = __webpack_require__(/*! immer */ "immer");
const utils_1 = __webpack_require__(/*! ./utils */ "../../packages/typeless/src/utils.ts");
const createNestedReducer = (prop, reducer) => (state, action) => {
    const subState = reducer(state[prop], action);
    if (state[prop] !== subState) {
        return {
            ...state,
            [prop]: subState,
        };
    }
    return state;
};
class ChainedReducer {
    constructor(initial) {
        this.initial = initial;
        this.reducerMap = {};
        this.defaultReducers = [];
        this.reducer = null;
    }
    asReducer() {
        if (!this.reducer) {
            const reducer = this.getReducer();
            Object.getOwnPropertyNames(ChainedReducer.prototype).forEach(key => {
                const prop = this[key];
                if (typeof prop === 'function') {
                    reducer[key] = prop.bind(this);
                }
            });
            this.reducer = reducer;
        }
        return this.reducer;
    }
    attach(prop, fn) {
        if (typeof prop === 'function') {
            this.defaultReducers.push(prop);
        }
        else {
            this.defaultReducers.push(createNestedReducer(prop, fn));
        }
        return this.asReducer();
    }
    replace(actionCreator, fn) {
        this.transform(actionCreator, (state, action) => immer_1.produce(state, draft => fn(draft, action.payload, action)));
        return this.asReducer();
    }
    mergePayload(actionCreators) {
        this.transform(actionCreators, (state, action) => Object.assign({}, state, action.payload));
        return this.asReducer();
    }
    nested(prop, fn) {
        const nested = fn(new ChainedReducer(this.initial[prop]));
        this.defaultReducers.push(createNestedReducer(prop, nested.getReducer()));
        return this.asReducer();
    }
    on(actionCreator, fn) {
        this.transform(actionCreator, (state, action) => immer_1.produce(state, draft => fn(draft, action.payload, action)));
        return this.asReducer();
    }
    onMany(actionCreator, fn) {
        return this.on(actionCreator, fn);
    }
    getReducer() {
        return (state = this.initial, action) => {
            const reducers = (this.reducerMap[action.type] || []).concat(this.defaultReducers);
            if (!reducers.length) {
                return state;
            }
            return reducers.reduce((prev, fn) => fn(prev, action), state);
        };
    }
    transform(actionCreators, reducerFn) {
        const actionTypes = utils_1.toArray(actionCreators).map(ac => ac.toString());
        actionTypes.forEach(action => {
            if (!this.reducerMap[action]) {
                this.reducerMap[action] = [];
            }
            this.reducerMap[action].push(reducerFn);
        });
    }
}
exports.ChainedReducer = ChainedReducer;


/***/ }),

/***/ "../../packages/typeless/src/GetProps.ts":
/*!*****************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/GetProps.ts ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });


/***/ }),

/***/ "../../packages/typeless/src/actions.ts":
/*!****************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/actions.ts ***!
  \****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const createActions_1 = __webpack_require__(/*! ./createActions */ "../../packages/typeless/src/createActions.ts");
_a = createActions_1.createActions('@@typeless', {
    batchUpdate: (actions) => ({ payload: actions }),
    resetRedux: null,
}), exports.batchUpdate = _a.batchUpdate, exports.resetRedux = _a.resetRedux;


/***/ }),

/***/ "../../packages/typeless/src/checkExhaust.ts":
/*!*********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/checkExhaust.ts ***!
  \*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function checkExhaust(component, props) {
    // no op
}
exports.checkExhaust = checkExhaust;


/***/ }),

/***/ "../../packages/typeless/src/combineReducers.ts":
/*!************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/combineReducers.ts ***!
  \************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const redux_1 = __webpack_require__(/*! redux */ "redux");
function combineReducers(map) {
    return redux_1.combineReducers(map);
}
exports.combineReducers = combineReducers;


/***/ }),

/***/ "../../packages/typeless/src/createActions.ts":
/*!**********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/createActions.ts ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const r_1 = __webpack_require__(/*! r */ "../../packages/r/index.ts");
function createActions(ns, actionMap) {
    const Actions = Object.keys(actionMap).reduce((acc, key) => {
        const type = ns + '/' + r_1.snakeCase(key).toUpperCase();
        acc[key] = (...args) => {
            const ac = actionMap[key] || (() => ({}));
            const action = ac(...args);
            if (!action.type) {
                action.type = type;
            }
            return action;
        };
        acc[key].toString = () => type;
        return acc;
    }, {});
    return Actions;
}
exports.createActions = createActions;


/***/ }),

/***/ "../../packages/typeless/src/createConnect.ts":
/*!**********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/createConnect.ts ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const React = __importStar(__webpack_require__(/*! react */ "react"));
const react_redux_1 = __webpack_require__(/*! react-redux */ "react-redux");
const pick_1 = __webpack_require__(/*! ./pick */ "../../packages/typeless/src/pick.ts");
exports.createConnect = () => {
    let mapStateFn = null;
    const actions = {};
    const wrappers = [];
    const getWrapped = (initial) => wrappers.reduce((component, hoc) => hoc(component), initial);
    const meta = {
        getMapState: () => mapStateFn,
    };
    const addMeta = (component) => {
        Object.assign(component, meta);
        return component;
    };
    const chain = {
        external: () => chain,
        mapState: fn => {
            mapStateFn = fn;
            return chain;
        },
        pick: (actionMap, names) => {
            Object.assign(actions, pick_1.pick(actionMap, names));
            return chain;
        },
        actions: actionMap => {
            Object.assign(actions, actionMap);
            return chain;
        },
        sfc: component => {
            return addMeta(react_redux_1.connect(mapStateFn, actions)(getWrapped(component)));
        },
        statefull: fn => {
            return addMeta(react_redux_1.connect(mapStateFn, actions)(getWrapped(fn(React.PureComponent))));
        },
        hoc: hoc => {
            wrappers.push(hoc);
            return chain;
        },
    };
    return chain;
};


/***/ }),

/***/ "../../packages/typeless/src/createEpic.ts":
/*!*******************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/createEpic.ts ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const Rx = __importStar(__webpack_require__(/*! rxjs/operators */ "rxjs/operators"));
const rxjs_1 = __webpack_require__(/*! rxjs */ "rxjs");
const redux_observable_1 = __webpack_require__(/*! ./redux-observable */ "../../packages/typeless/src/redux-observable/index.ts");
const ofType_1 = __webpack_require__(/*! ./ofType */ "../../packages/typeless/src/ofType.ts");
const isAction = (action) => {
    return action && typeof action.type === 'string';
};
const repeat = (str, times) => new Array(times + 1).join(str);
const pad = (num, maxLength) => repeat('0', maxLength - num.toString().length) + num;
const formatTime = (time) => `${pad(time.getHours(), 2)}:${pad(time.getMinutes(), 2)}:${pad(time.getSeconds(), 2)}.${pad(time.getMilliseconds(), 3)}`;
function createEpic(name) {
    const epics = [];
    let epic = null;
    const chain = (action$, store, dependencies) => {
        if (!epic) {
            epic = redux_observable_1.combineEpics(...epics);
        }
        return epic(action$, store, dependencies);
    };
    chain.on = (ac, opOrHandler, handlerOrNull) => {
        const operator = handlerOrNull
            ? opOrHandler
            : Rx.mergeMap;
        const handler = (handlerOrNull
            ? handlerOrNull
            : opOrHandler);
        epics.push((action$, { getState, dispatch }, deps = {}) => {
            let sourceAction;
            return action$.pipe(ac && 'ac' in ac
                ? Rx.filter(action => action.type === ac.ac.toString() && ac.filter(action))
                : ofType_1.ofType(ac), Rx.tap(action => {
                if (false) {}
            }), operator(action => {
                sourceAction = action;
                const result = handler(action.payload, {
                    action$,
                    getState,
                    dispatch,
                    ...deps,
                }, action);
                if (Array.isArray(result)) {
                    return rxjs_1.from(result);
                }
                if (isAction(result)) {
                    return rxjs_1.of(result);
                }
                if (result === null) {
                    return rxjs_1.of(null);
                }
                return result;
            }), Rx.mergeMap((action) => {
                if (action == null) {
                    return rxjs_1.empty();
                }
                if (isAction(action)) {
                    return rxjs_1.of(action);
                }
                if (Array.isArray(action) && action.every(a => isAction(a))) {
                    return action;
                }
                console.error('Invalid action returned in epic.', {
                    sourceAction,
                    action,
                    store: name,
                });
                return rxjs_1.empty();
            }), Rx.catchError(err => {
                console.error('An unhandled error occurred in epic.', {
                    sourceAction,
                    store: name,
                }, err);
                return rxjs_1.empty();
            }));
        });
        return chain;
    };
    chain.attach = (newEpic) => {
        epics.push(...(Array.isArray(newEpic) ? newEpic : [newEpic]));
        return chain;
    };
    return chain;
}
exports.createEpic = createEpic;


/***/ }),

/***/ "../../packages/typeless/src/createReducer.ts":
/*!**********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/createReducer.ts ***!
  \**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const toArray = (input) => Array.isArray(input) ? input : [input];
const getTransformer = (reducerMap) => (actionCreators, reducerFn) => {
    const actionTypes = toArray(actionCreators).map(ac => ac.toString());
    actionTypes.forEach(action => {
        if (!reducerMap[action]) {
            reducerMap[action] = [];
        }
        reducerMap[action].push(reducerFn);
    });
};
const createNestedReducer = (prop, reducer) => (state, action) => {
    const subState = reducer(state[prop], action);
    if (state[prop] !== subState) {
        // tslint:disable-next-line:prefer-object-spread
        return Object.assign({}, state, {
            [prop]: subState,
        });
    }
    return state;
};
function createReducer(initial) {
    const reducerMap = {};
    const defaultReducers = [];
    const transform = getTransformer(reducerMap);
    const chainedReducer = ((state = initial, action) => {
        const reducers = (reducerMap[action.type] || []).concat(defaultReducers);
        if (!reducers.length) {
            return state;
        }
        return reducers.reduce((prev, fn) => fn(prev, action), state);
    });
    chainedReducer.merge = ((actionCreators, fn) => {
        transform(actionCreators, (state, action) => {
            const values = fn(action.payload, state, action);
            if (values == null || typeof values !== 'object') {
                throw new Error(`Merge should return an object. Received ${values}.`);
            }
            if (Array.isArray(values)) {
                throw new Error(`Merge should return an object. Received an array.`);
            }
            // tslint:disable-next-line:prefer-object-spread
            return Object.assign({}, state, values);
        });
        return chainedReducer;
    });
    chainedReducer.replace = ((actionCreators, fn) => {
        transform(actionCreators, (state, action) => fn(action.payload, state, action));
        return chainedReducer;
    });
    chainedReducer.on = ((actionCreators, fn) => {
        transform(actionCreators, (state, action) => fn(state, action));
        return chainedReducer;
    });
    chainedReducer.push = ((actionCreators, fn) => {
        transform(actionCreators, (state, action) => [...state, fn(action.payload, state, action)]);
        return chainedReducer;
    });
    chainedReducer.unshift = ((actionCreators, fn) => {
        transform(actionCreators, (state, action) => [fn(action.payload, state, action), ...state]);
        return chainedReducer;
    });
    chainedReducer.reject = ((actionCreators, fn) => {
        transform(actionCreators, (state, action) => {
            const handler = fn(action.payload, state, action);
            const filter = (item, index, array) => !handler(item, index, array);
            return state.filter(filter);
        });
        return chainedReducer;
    });
    chainedReducer.filter = ((actionCreators, fn) => {
        transform(actionCreators, (state, action) => {
            const handler = fn(action.payload, state, action);
            return state.filter(handler);
        });
        return chainedReducer;
    });
    chainedReducer.map = ((actionCreators, fn) => {
        transform(actionCreators, (state, action) => {
            const handler = fn(action.payload, state, action);
            return state.map(handler);
        });
        return chainedReducer;
    });
    chainedReducer.nested = ((prop, fn) => {
        const nested = fn(createReducer(initial[prop]));
        defaultReducers.push(createNestedReducer(prop, nested));
        return chainedReducer;
    });
    chainedReducer.attach = ((prop, fn) => {
        if (typeof prop === 'function') {
            defaultReducers.push(prop);
        }
        else {
            defaultReducers.push(createNestedReducer(prop, fn));
        }
        return chainedReducer;
    });
    return chainedReducer;
}
exports.createReducer = createReducer;


/***/ }),

/***/ "../../packages/typeless/src/createReducerNext.ts":
/*!**************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/createReducerNext.ts ***!
  \**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const ChainedReducer_1 = __webpack_require__(/*! ./ChainedReducer */ "../../packages/typeless/src/ChainedReducer.ts");
function createReducerNext(initial) {
    return new ChainedReducer_1.ChainedReducer(initial).asReducer();
}
exports.createReducerNext = createReducerNext;


/***/ }),

/***/ "../../packages/typeless/src/enhanceReducer.ts":
/*!***********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/enhanceReducer.ts ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.enhanceReducer = (...args) => {
    const [baseReducer, ...wrappers] = args.reverse();
    return wrappers.reduce((acc, wrapper) => wrapper(acc), baseReducer);
};


/***/ }),

/***/ "../../packages/typeless/src/ofType.ts":
/*!***************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/ofType.ts ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const Rx = __importStar(__webpack_require__(/*! rxjs/operators */ "rxjs/operators"));
const getType = (ac) => (ac.getType ? ac.getType() : ac.toString());
function compare(ac, action) {
    const acType = getType(ac);
    if (Array.isArray(acType)) {
        const [symbol, type] = acType;
        return symbol === action.type[0] && type === action.type[1];
    }
    return action.type === acType;
}
exports.ofType = (ac) => {
    if (Array.isArray(ac)) {
        return Rx.filter((action) => ac.some(item => compare(item, action)));
    }
    return Rx.filter((action) => compare(ac, action));
};


/***/ }),

/***/ "../../packages/typeless/src/pick.ts":
/*!*************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/pick.ts ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.pick = (actionMap, names) => {
    return names.reduce((acc, name) => {
        acc[name] = actionMap[name];
        return acc;
    }, {});
};


/***/ }),

/***/ "../../packages/typeless/src/redux-observable/EPIC_END.ts":
/*!**********************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/redux-observable/EPIC_END.ts ***!
  \**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.EPIC_END = '@@redux-observable/EPIC_END';


/***/ }),

/***/ "../../packages/typeless/src/redux-observable/combineEpics.ts":
/*!**************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/redux-observable/combineEpics.ts ***!
  \**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const rxjs_1 = __webpack_require__(/*! rxjs */ "rxjs");
/**
 * Merges all epics into a single one.
 */
exports.combineEpics = (...epics) => (...args) => rxjs_1.merge(...epics.map(epic => {
    const output$ = epic(...args);
    if (!output$) {
        throw new TypeError(`combineEpics: one of the provided Epics "${epic.name || '<anonymous>'}" does not return a stream. Double check you\'re not missing a return statement!`);
    }
    return output$;
}));


/***/ }),

/***/ "../../packages/typeless/src/redux-observable/createEpicMiddleware.ts":
/*!**********************************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/redux-observable/createEpicMiddleware.ts ***!
  \**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const rxjs_1 = __webpack_require__(/*! rxjs */ "rxjs");
const operators_1 = __webpack_require__(/*! rxjs/operators */ "rxjs/operators");
const EPIC_END_1 = __webpack_require__(/*! ./EPIC_END */ "../../packages/typeless/src/redux-observable/EPIC_END.ts");
function createEpicMiddleware(rootEpic, options = {}) {
    const epic$ = new rxjs_1.Subject();
    let store;
    const actionSubject$ = new rxjs_1.Subject().pipe(operators_1.observeOn(rxjs_1.queueScheduler));
    const epicMiddleware = (_store) => {
        store = _store;
        return next => {
            epic$
                .pipe(operators_1.map(epic => epic(actionSubject$, store, options.dependencies)), operators_1.switchMap(x => x))
                .pipe(operators_1.subscribeOn(rxjs_1.queueScheduler), operators_1.observeOn(rxjs_1.queueScheduler))
                .subscribe(x => {
                store.dispatch(x);
            });
            // Setup initial root epic
            epic$.next(rootEpic);
            return action => {
                const result = next(action);
                actionSubject$.next(action);
                return result;
            };
        };
    };
    epicMiddleware.replaceEpic = newRootEpic => {
        // gives the previous root Epic a last chance
        // to do some clean up
        store.dispatch({ type: EPIC_END_1.EPIC_END });
        // switches to the new root Epic, synchronously terminating
        // the previous one
        epic$.next(newRootEpic);
    };
    return epicMiddleware;
}
exports.createEpicMiddleware = createEpicMiddleware;


/***/ }),

/***/ "../../packages/typeless/src/redux-observable/index.ts":
/*!*******************************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/redux-observable/index.ts ***!
  \*******************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(/*! ./createEpicMiddleware */ "../../packages/typeless/src/redux-observable/createEpicMiddleware.ts"));
__export(__webpack_require__(/*! ./combineEpics */ "../../packages/typeless/src/redux-observable/combineEpics.ts"));
__export(__webpack_require__(/*! ./EPIC_END */ "../../packages/typeless/src/redux-observable/EPIC_END.ts"));


/***/ }),

/***/ "../../packages/typeless/src/useActions.ts":
/*!*******************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/useActions.ts ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const redux_react_hook_1 = __webpack_require__(/*! redux-react-hook */ "redux-react-hook");
const react_1 = __webpack_require__(/*! react */ "react");
function useActions(actionCreators) {
    const dispatch = redux_react_hook_1.useDispatch();
    const names = Object.keys(actionCreators);
    return react_1.useMemo(() => names.reduce((mapped, key) => {
        mapped[key] = (...args) => {
            const action = actionCreators[key](...args);
            dispatch(action);
            return action;
        };
        return mapped;
    }, {}), names);
}
exports.useActions = useActions;


/***/ }),

/***/ "../../packages/typeless/src/useMappedState.ts":
/*!***********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/useMappedState.ts ***!
  \***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const redux_react_hook_1 = __webpack_require__(/*! redux-react-hook */ "redux-react-hook");
const react_1 = __webpack_require__(/*! react */ "react");
function useMappedState(fn, deps) {
    const mapState = react_1.useCallback(fn, deps || []);
    return redux_react_hook_1.useMappedState(mapState);
}
exports.useMappedState = useMappedState;


/***/ }),

/***/ "../../packages/typeless/src/utils.ts":
/*!**************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/utils.ts ***!
  \**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.toArray = (input) => Array.isArray(input) ? input : [input];


/***/ }),

/***/ "../../packages/typeless/src/waitForType.ts":
/*!********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/waitForType.ts ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const operators_1 = __webpack_require__(/*! rxjs/operators */ "rxjs/operators");
const ofType_1 = __webpack_require__(/*! ./ofType */ "../../packages/typeless/src/ofType.ts");
exports.waitForType = (ac) => (obs) => obs.pipe(ofType_1.ofType(ac), operators_1.take(1));


/***/ }),

/***/ "../../packages/typeless/src/withBatch.ts":
/*!******************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/withBatch.ts ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const actions_1 = __webpack_require__(/*! ./actions */ "../../packages/typeless/src/actions.ts");
exports.withBatch = (baseReducer) => (state, action) => {
    if (action.type === actions_1.batchUpdate.toString()) {
        return action.payload.reduce((currentState, currentAction) => baseReducer(currentState, currentAction), state);
    }
    return baseReducer(state, action);
};


/***/ }),

/***/ "../../packages/typeless/src/withReset.ts":
/*!******************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/typeless/src/withReset.ts ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const actions_1 = __webpack_require__(/*! ./actions */ "../../packages/typeless/src/actions.ts");
exports.withReset = (baseReducer) => (state, action) => {
    if (action.type === actions_1.resetRedux.toString()) {
        return baseReducer(undefined, action);
    }
    return baseReducer(state, action);
};


/***/ }),

/***/ "../../packages/types/connector.ts":
/*!***********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/types/connector.ts ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });


/***/ }),

/***/ "../../packages/types/index.ts":
/*!*******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/types/index.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.CALL_HISTORY_METHOD = '@@router/CALL_HISTORY_METHOD';
exports.LOCATION_CHANGE = '@@router/LOCATION_CHANGE';
var FilterOperator;
(function (FilterOperator) {
    FilterOperator["all"] = "all";
    FilterOperator["any"] = "any";
})(FilterOperator = exports.FilterOperator || (exports.FilterOperator = {}));
var FilterFieldType;
(function (FilterFieldType) {
    FilterFieldType["flag"] = "flag";
    FilterFieldType["string"] = "string";
    FilterFieldType["select"] = "select";
    FilterFieldType["fixedSelect"] = "fixedSelect";
    FilterFieldType["date"] = "date";
    FilterFieldType["bool"] = "bool";
    FilterFieldType["number"] = "number";
})(FilterFieldType = exports.FilterFieldType || (exports.FilterFieldType = {}));


/***/ }),

/***/ "../../packages/types/lnl.ts":
/*!*****************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/types/lnl.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/* tslint:disable class-name */
var TypeName;
(function (TypeName) {
    TypeName["Lnl_AccessGroup"] = "Lnl_AccessGroup";
    TypeName["Lnl_AccessLevel"] = "Lnl_AccessLevel";
    TypeName["Lnl_AccessLevelAssignment"] = "Lnl_AccessLevelAssignment";
    TypeName["Lnl_AccessLevelGroupAssignment"] = "Lnl_AccessLevelGroupAssignment";
    TypeName["Lnl_AccessLevelReaderAssignment"] = "Lnl_AccessLevelReaderAssignment";
    TypeName["Lnl_Account"] = "Lnl_Account";
    TypeName["Lnl_AlarmAckHistory"] = "Lnl_AlarmAckHistory";
    TypeName["Lnl_AlarmDefinition"] = "Lnl_AlarmDefinition";
    TypeName["Lnl_AlarmInput"] = "Lnl_AlarmInput";
    TypeName["Lnl_AlarmOutput"] = "Lnl_AlarmOutput";
    TypeName["Lnl_AlarmPanel"] = "Lnl_AlarmPanel";
    TypeName["Lnl_Area"] = "Lnl_Area";
    TypeName["Lnl_AuthenticationMode"] = "Lnl_AuthenticationMode";
    TypeName["Lnl_Badge"] = "Lnl_Badge";
    TypeName["Lnl_BadgeFIPS201"] = "Lnl_BadgeFIPS201";
    TypeName["Lnl_BadgeLastLocation"] = "Lnl_BadgeLastLocation";
    TypeName["Lnl_BadgeOwner"] = "Lnl_BadgeOwner";
    TypeName["Lnl_BadgeStatus"] = "Lnl_BadgeStatus";
    TypeName["Lnl_BadgeType"] = "Lnl_BadgeType";
    TypeName["Lnl_Camera"] = "Lnl_Camera";
    TypeName["Lnl_CameraDeviceLink"] = "Lnl_CameraDeviceLink";
    TypeName["Lnl_CameraGroup"] = "Lnl_CameraGroup";
    TypeName["Lnl_CameraGroupCameraLink"] = "Lnl_CameraGroupCameraLink";
    TypeName["Lnl_Cardholder"] = "Lnl_Cardholder";
    TypeName["Lnl_CardholderAccount"] = "Lnl_CardholderAccount";
    TypeName["Lnl_CardholderBadge"] = "Lnl_CardholderBadge";
    TypeName["Lnl_CardholderMultimediaObject"] = "Lnl_CardholderMultimediaObject";
    TypeName["Lnl_DeviceGroup"] = "Lnl_DeviceGroup";
    TypeName["Lnl_Directory"] = "Lnl_Directory";
    TypeName["Lnl_DirectoryAccount"] = "Lnl_DirectoryAccount";
    TypeName["Lnl_Element"] = "Lnl_Element";
    TypeName["Lnl_ElevatorTerminal"] = "Lnl_ElevatorTerminal";
    TypeName["Lnl_EventAlarmDefinitionLink"] = "Lnl_EventAlarmDefinitionLink";
    TypeName["Lnl_EventParameter"] = "Lnl_EventParameter";
    TypeName["Lnl_EventSubtypeDefinition"] = "Lnl_EventSubtypeDefinition";
    TypeName["Lnl_EventSubtypeParameterLink"] = "Lnl_EventSubtypeParameterLink";
    TypeName["Lnl_EventType"] = "Lnl_EventType";
    TypeName["Lnl_GuardTour"] = "Lnl_GuardTour";
    TypeName["Lnl_Holiday"] = "Lnl_Holiday";
    TypeName["Lnl_HolidayType"] = "Lnl_HolidayType";
    TypeName["Lnl_HolidayTypeLink"] = "Lnl_HolidayTypeLink";
    TypeName["Lnl_IncomingEvent"] = "Lnl_IncomingEvent";
    TypeName["Lnl_Input"] = "Lnl_Input";
    TypeName["Lnl_IntrusionArea"] = "Lnl_IntrusionArea";
    TypeName["Lnl_IntrusionDoor"] = "Lnl_IntrusionDoor";
    TypeName["Lnl_IntrusionOutput"] = "Lnl_IntrusionOutput";
    TypeName["Lnl_IntrusionZone"] = "Lnl_IntrusionZone";
    TypeName["Lnl_Location"] = "Lnl_Location";
    TypeName["Lnl_LoggedEvent"] = "Lnl_LoggedEvent";
    TypeName["Lnl_LogicalDevice"] = "Lnl_LogicalDevice";
    TypeName["Lnl_LogicalSource"] = "Lnl_LogicalSource";
    TypeName["Lnl_LogicalSubDevice"] = "Lnl_LogicalSubDevice";
    TypeName["Lnl_MonitoringZone"] = "Lnl_MonitoringZone";
    TypeName["Lnl_MonitoringZoneCameraLink"] = "Lnl_MonitoringZoneCameraLink";
    TypeName["Lnl_MonitoringZoneDeviceLink"] = "Lnl_MonitoringZoneDeviceLink";
    TypeName["Lnl_MonitoringZoneRecordLink"] = "Lnl_MonitoringZoneRecordLink";
    TypeName["Lnl_MultimediaObject"] = "Lnl_MultimediaObject";
    TypeName["Lnl_MultimediaObjectOwner"] = "Lnl_MultimediaObjectOwner";
    TypeName["Lnl_OffBoardRelay"] = "Lnl_OffBoardRelay";
    TypeName["Lnl_OnBoardRelay"] = "Lnl_OnBoardRelay";
    TypeName["Lnl_Output"] = "Lnl_Output";
    TypeName["Lnl_Panel"] = "Lnl_Panel";
    TypeName["Lnl_Person"] = "Lnl_Person";
    TypeName["Lnl_PersonAccount"] = "Lnl_PersonAccount";
    TypeName["Lnl_PersonSecondarySegments"] = "Lnl_PersonSecondarySegments";
    TypeName["Lnl_PrecisionAccessGroup"] = "Lnl_PrecisionAccessGroup";
    TypeName["Lnl_PrecisionAccessGroupAssignment"] = "Lnl_PrecisionAccessGroupAssignment";
    TypeName["Lnl_PTZPreset"] = "Lnl_PTZPreset";
    TypeName["Lnl_ProhibitedPassword"] = "Lnl_ProhibitedPassword";
    TypeName["Lnl_Reader"] = "Lnl_Reader";
    TypeName["Lnl_ReaderEntersArea"] = "Lnl_ReaderEntersArea";
    TypeName["Lnl_ReaderExitsArea"] = "Lnl_ReaderExitsArea";
    TypeName["Lnl_ReaderInput"] = "Lnl_ReaderInput";
    TypeName["Lnl_ReaderInput1"] = "Lnl_ReaderInput1";
    TypeName["Lnl_ReaderInput2"] = "Lnl_ReaderInput2";
    TypeName["Lnl_ReaderOutput"] = "Lnl_ReaderOutput";
    TypeName["Lnl_ReaderOutput1"] = "Lnl_ReaderOutput1";
    TypeName["Lnl_ReaderOutput2"] = "Lnl_ReaderOutput2";
    TypeName["Lnl_Segment"] = "Lnl_Segment";
    TypeName["Lnl_SegmentGroup"] = "Lnl_SegmentGroup";
    TypeName["Lnl_SegmentGroupMember"] = "Lnl_SegmentGroupMember";
    TypeName["Lnl_SegmentUnit"] = "Lnl_SegmentUnit";
    TypeName["Lnl_Timezone"] = "Lnl_Timezone";
    TypeName["Lnl_TimezoneInterval"] = "Lnl_TimezoneInterval";
    TypeName["Lnl_User"] = "Lnl_User";
    TypeName["Lnl_UserAccount"] = "Lnl_UserAccount";
    TypeName["Lnl_UserFieldPermissionGroup"] = "Lnl_UserFieldPermissionGroup";
    TypeName["Lnl_UserPermissionDeviceGroupLink"] = "Lnl_UserPermissionDeviceGroupLink";
    TypeName["Lnl_UserPermissionGroup"] = "Lnl_UserPermissionGroup";
    TypeName["Lnl_UserReportPermissionGroup"] = "Lnl_UserReportPermissionGroup";
    TypeName["Lnl_UserSecondarySegment"] = "Lnl_UserSecondarySegment";
    TypeName["Lnl_VideoLayout"] = "Lnl_VideoLayout";
    TypeName["Lnl_VideoRecorder"] = "Lnl_VideoRecorder";
    TypeName["Lnl_VideoTemplate"] = "Lnl_VideoTemplate";
    TypeName["Lnl_Visit"] = "Lnl_Visit";
    TypeName["Lnl_VisitEvent"] = "Lnl_VisitEvent";
    TypeName["Lnl_VisitDelegateAssignment"] = "Lnl_VisitDelegateAssignment";
    TypeName["Lnl_VisitEmailRecipient"] = "Lnl_VisitEmailRecipient";
    TypeName["Lnl_Visitor"] = "Lnl_Visitor";
    TypeName["Lnl_VisitorAccount"] = "Lnl_VisitorAccount";
    TypeName["Lnl_VisitorBadge"] = "Lnl_VisitorBadge";
    TypeName["Lnl_VisitorMultimediaObject"] = "Lnl_VisitorMultimediaObject";
    TypeName["Lnl_VisitSignInLocation"] = "Lnl_VisitSignInLocation";
    TypeName["Lnl_Workstation"] = "Lnl_Workstation";
    TypeName["Lnl_WorldTimezone"] = "Lnl_WorldTimezone";
})(TypeName = exports.TypeName || (exports.TypeName = {}));
var MultimediaDataType;
(function (MultimediaDataType) {
    MultimediaDataType[MultimediaDataType["NormalImage"] = 0] = "NormalImage";
    MultimediaDataType[MultimediaDataType["ThumbnailImage"] = 2] = "ThumbnailImage";
    MultimediaDataType[MultimediaDataType["PdfDocument"] = 13] = "PdfDocument";
})(MultimediaDataType = exports.MultimediaDataType || (exports.MultimediaDataType = {}));
var MultimediaObjectType;
(function (MultimediaObjectType) {
    MultimediaObjectType[MultimediaObjectType["Photo"] = 1] = "Photo";
    MultimediaObjectType[MultimediaObjectType["VisitorDocument"] = 513] = "VisitorDocument";
})(MultimediaObjectType = exports.MultimediaObjectType || (exports.MultimediaObjectType = {}));
var DirectoryType;
(function (DirectoryType) {
    DirectoryType[DirectoryType["Internal"] = 1] = "Internal";
    DirectoryType[DirectoryType["LDAP"] = 0] = "LDAP";
    DirectoryType[DirectoryType["ActiveDirectory"] = 1] = "ActiveDirectory";
    DirectoryType[DirectoryType["NT4"] = 2] = "NT4";
    DirectoryType[DirectoryType["LocalAccounts"] = 3] = "LocalAccounts";
    DirectoryType[DirectoryType["OpenID"] = 4] = "OpenID";
})(DirectoryType = exports.DirectoryType || (exports.DirectoryType = {}));
var AccessLevelSearchTypeEnum;
(function (AccessLevelSearchTypeEnum) {
    AccessLevelSearchTypeEnum["AnyOf"] = "any_of";
    AccessLevelSearchTypeEnum["NoneOf"] = "none_of";
    AccessLevelSearchTypeEnum["AllOf"] = "all_of";
    AccessLevelSearchTypeEnum["Exactly"] = "exactly";
})(AccessLevelSearchTypeEnum = exports.AccessLevelSearchTypeEnum || (exports.AccessLevelSearchTypeEnum = {}));
exports.BadgeActiveType = 1;
var BadgeTypeClass;
(function (BadgeTypeClass) {
    BadgeTypeClass[BadgeTypeClass["Standard"] = 0] = "Standard";
    BadgeTypeClass[BadgeTypeClass["Temporary"] = 1] = "Temporary";
    BadgeTypeClass[BadgeTypeClass["Visitor"] = 2] = "Visitor";
    BadgeTypeClass[BadgeTypeClass["Guest"] = 3] = "Guest";
    BadgeTypeClass[BadgeTypeClass["SpecialPurpose"] = 4] = "SpecialPurpose";
})(BadgeTypeClass = exports.BadgeTypeClass || (exports.BadgeTypeClass = {}));
var DefaultDeactivationDateType;
(function (DefaultDeactivationDateType) {
    DefaultDeactivationDateType[DefaultDeactivationDateType["None"] = 0] = "None";
    DefaultDeactivationDateType[DefaultDeactivationDateType["Exact"] = 1] = "Exact";
    DefaultDeactivationDateType[DefaultDeactivationDateType["After"] = 2] = "After";
})(DefaultDeactivationDateType = exports.DefaultDeactivationDateType || (exports.DefaultDeactivationDateType = {}));
var BadgeIDAllocationType;
(function (BadgeIDAllocationType) {
    BadgeIDAllocationType[BadgeIDAllocationType["Automatic"] = 1] = "Automatic";
    BadgeIDAllocationType[BadgeIDAllocationType["FromCardholderID"] = 2] = "FromCardholderID";
    BadgeIDAllocationType[BadgeIDAllocationType["ManualEntry"] = 3] = "ManualEntry";
    BadgeIDAllocationType[BadgeIDAllocationType["InternalCardholderID"] = 5] = "InternalCardholderID";
    BadgeIDAllocationType[BadgeIDAllocationType["FASC"] = 7] = "FASC";
    BadgeIDAllocationType[BadgeIDAllocationType["ImportFromCard"] = 8] = "ImportFromCard";
})(BadgeIDAllocationType = exports.BadgeIDAllocationType || (exports.BadgeIDAllocationType = {}));
exports.READER_INPUT1_ID = 1;
exports.READER_INPUT2_ID = 2;
exports.READER_OUTPUT1_ID = 17;
exports.READER_OUTPUT2_ID = 18;
exports.ALARM_PANEL_FIRST_ID = 65;
exports.ALARM_PANEL_OUTPUT_FIRST_ID = 17;
var LabelAlignment;
(function (LabelAlignment) {
    LabelAlignment[LabelAlignment["LEFT"] = 0] = "LEFT";
    LabelAlignment[LabelAlignment["CENTER"] = 1] = "CENTER";
    LabelAlignment[LabelAlignment["RIGHT"] = 2] = "RIGHT";
})(LabelAlignment = exports.LabelAlignment || (exports.LabelAlignment = {}));
var MapItemType;
(function (MapItemType) {
    MapItemType[MapItemType["PANEL"] = 1] = "PANEL";
    MapItemType[MapItemType["READER"] = 2] = "READER";
    MapItemType[MapItemType["ALARM_PANEL"] = 3] = "ALARM_PANEL";
    MapItemType[MapItemType["INPUT"] = 4] = "INPUT";
    MapItemType[MapItemType["OUTPUT"] = 5] = "OUTPUT";
    MapItemType[MapItemType["MAP"] = 6] = "MAP";
    MapItemType[MapItemType["READER_AUX_INPUT"] = 10] = "READER_AUX_INPUT";
    MapItemType[MapItemType["READER_AUX_OUTPUT"] = 11] = "READER_AUX_OUTPUT";
    MapItemType[MapItemType["CCTV_PANEL"] = 15] = "CCTV_PANEL";
    MapItemType[MapItemType["CCTV_CAMERA"] = 17] = "CCTV_CAMERA";
    MapItemType[MapItemType["LOGICAL_SOURCE"] = 47] = "LOGICAL_SOURCE";
    MapItemType[MapItemType["LOGICAL_DEVICE"] = 62] = "LOGICAL_DEVICE";
    MapItemType[MapItemType["LOGICAL_SUB_DEVICE"] = 63] = "LOGICAL_SUB_DEVICE";
})(MapItemType = exports.MapItemType || (exports.MapItemType = {}));
var ControlType;
(function (ControlType) {
    ControlType[ControlType["ReaderRU_RM"] = 374] = "ReaderRU_RM";
})(ControlType = exports.ControlType || (exports.ControlType = {}));


/***/ }),

/***/ "../../packages/utils/cookie.ts":
/*!********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/cookie.ts ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function create(name, value, minutes, domain) {
    let expires;
    if (minutes) {
        const date = new Date();
        date.setTime(date.getTime() + minutes * 60 * 1000);
        expires = '; expires=' + date.toUTCString();
    }
    else {
        expires = '';
    }
    domain = domain ? 'domain=' + domain + ';' : '';
    document.cookie = name + '=' + value + expires + ';' + domain + 'path=/';
}
exports.create = create;
function read(name) {
    const nameEQ = name + '=';
    const ca = document.cookie.split(';');
    for (let c of ca) {
        while (c.charAt(0) === ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) === 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}
exports.read = read;
function remove(name) {
    create(name, '', -1);
}
exports.remove = remove;


/***/ }),

/***/ "../../packages/utils/generate-filter.ts":
/*!*****************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/generate-filter.ts ***!
  \*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const types_1 = __webpack_require__(/*! types */ "../../packages/types/index.ts");
function mapOperator(operator) {
    switch (operator) {
        case 'contains':
            return '$like';
        case 'is equal to':
            return '$eq';
        case 'is not equal to':
            return '$ne';
        case 'begins with':
            return '$startsWith';
        case 'is before':
            return '$lt';
        case 'is after':
            return '$gt';
        default:
            throw new Error(`Not supported operator: ${operator}`);
    }
}
exports.mapOperator = mapOperator;
function mapMultiOperator(operator) {
    switch (operator) {
        case 'is equal to':
            return '$in';
        case 'is not equal to':
            return '$nin';
        default:
            throw new Error(`Not supported multi operator: ${operator}`);
    }
}
exports.mapMultiOperator = mapMultiOperator;
exports.mapToValues = (condition) => {
    if (Array.isArray(condition.value)) {
        return R.map(condition.value, item => Number(item.value));
    }
    return condition.value;
};
exports.getWqlOperator = (condition) => Array.isArray(condition.value)
    ? mapMultiOperator(condition.operator)
    : mapOperator(condition.operator);
exports.mapToBool = (value) => value === 'true';
exports.isValidCondition = (item) => {
    if (!item.operator) {
        return false;
    }
    if (item.operator === 'is empty') {
        return true;
    }
    if (Array.isArray(item.value)) {
        return item.value.length > 0;
    }
    return item.value != null && item.value !== '';
};
exports.filterValidConditions = (conditions, flags) => conditions.filter(condition => (flags && flags[condition.field]) || exports.isValidCondition(condition));
exports.getNameExactFilter = (searchTerm) => {
    if (!searchTerm) {
        return null;
    }
    const keywords = searchTerm
        .split(' ')
        .map(x => x.trim().replace(/,/g, ''))
        .filter(x => x);
    if (keywords.length === 2) {
        // S42539
        return {
            $or: [
                { FIRSTNAME: keywords[0], LASTNAME: keywords[1] },
                { FIRSTNAME: keywords[1], LASTNAME: keywords[0] },
            ],
        };
    }
    return null;
};
exports.mapPropertyToField = (prefix, property, asyncTypes = []) => {
    const base = {
        text: property.display_name || property.name,
        field: `${prefix}${property.name}`,
    };
    if (asyncTypes.includes(property.name)) {
        return {
            ...base,
            type: types_1.FilterFieldType.select,
        };
    }
    switch (property.type) {
        case 'int64':
        case 'int32':
            if (property.possible_values) {
                const options = Object.keys(property.possible_values)
                    .map(key => ({
                    value: Number(key),
                    text: property.possible_values[key],
                }))
                    .filter(option => option.text);
                return {
                    ...base,
                    type: types_1.FilterFieldType.fixedSelect,
                    options,
                };
            }
            return {
                ...base,
                type: types_1.FilterFieldType.number,
            };
        case 'datetime (string)': {
            return {
                ...base,
                type: types_1.FilterFieldType.date,
            };
        }
        case 'bool': {
            return {
                ...base,
                type: types_1.FilterFieldType.bool,
            };
        }
        default:
            return {
                ...base,
                type: types_1.FilterFieldType.string,
            };
    }
};


/***/ }),

/***/ "../../packages/utils/i18n/helper.ts":
/*!*************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/i18n/helper.ts ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function getBrowserLanguages() {
    if (navigator.languages) {
        return [...navigator.languages];
    }
    if (navigator.language) {
        return [navigator.language];
    }
    return null;
}
exports.getBrowserLanguages = getBrowserLanguages;
function checkWhitelisted(langs, whitelist, fallbackLng) {
    if (!langs || langs.length === 0) {
        return fallbackLng;
    }
    for (const lang of langs) {
        const langLowered = lang.toLowerCase();
        for (const allowed of whitelist) {
            if (langLowered === allowed.toLowerCase()) {
                return allowed;
            }
        }
        const getPrefix = (str) => str.split('-')[0].toLowerCase();
        const prefix = getPrefix(lang);
        for (const allowed of whitelist) {
            if (prefix === getPrefix(allowed)) {
                return allowed;
            }
        }
    }
    return fallbackLng;
}
exports.checkWhitelisted = checkWhitelisted;


/***/ }),

/***/ "../../packages/utils/i18n/i18n.ts":
/*!***********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/i18n/i18n.ts ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! isomorphic-fetch */ "isomorphic-fetch");
const Cookie = __importStar(__webpack_require__(/*! ../cookie */ "../../packages/utils/cookie.ts"));
const helper_1 = __webpack_require__(/*! ./helper */ "../../packages/utils/i18n/helper.ts");
const plural_1 = __webpack_require__(/*! ./plural */ "../../packages/utils/i18n/plural.ts");
class I18n {
    constructor() {
        this.language = null;
        this.listeners = [];
        this.options = null;
        this.translations = {};
    }
    loadLang(language) {
        return Promise.all(this.options.modules.map(name => fetch(this.options.loadPath
            .replace('{{lng}}', language)
            .replace('{{name}}', name), {
            credentials: 'include',
        })
            .then(res => res.json())
            .catch(e => {
            console.error(e);
            return {};
        })
            .then(data => {
            this.addTranslation(name, data);
        })));
    }
    detectLanguage() {
        const getLangs = () => {
            const cookieLang = Cookie.read(this.options.lookupCookie);
            if (cookieLang) {
                return [cookieLang];
            }
            const browserLangs = helper_1.getBrowserLanguages() || [];
            if (browserLangs.length) {
                return browserLangs;
            }
            return [this.options.fallbackLng];
        };
        return helper_1.checkWhitelisted(getLangs(), this.options.whitelist, this.options.fallbackLng);
    }
    addTranslation(name, obj) {
        if (!this.translations[name]) {
            this.translations[name] = {};
        }
        Object.assign(this.translations[name], obj);
    }
    t(name, params) {
        const getName = (tryPlural) => {
            if (tryPlural && params && params.count != null) {
                const suffix = plural_1.getSuffix(this.language, params.count);
                return suffix ? name + '_' + suffix : name;
            }
            return name;
        };
        const getValue = (key) => {
            return key
                .split('.')
                .reduce((ret, part) => (ret ? ret[part] : null), this.translations);
        };
        const str = getValue(getName(true)) || getValue(getName(false));
        if (!str) {
            return name;
        }
        if (params) {
            return Object.keys(params).reduce((ret, paramName) => {
                if (paramName === 'count' && params.count_hide) {
                    return ret.replace(`{{count}}`, '');
                }
                return ret.replace(`{{${paramName}}}`, params[paramName]);
            }, str);
        }
        return str;
    }
    init(options) {
        this.options = options;
        this.language = this.detectLanguage();
        return this.loadLang(options.fallbackLng).then(() => {
            if (options.fallbackLng !== this.language) {
                document.documentElement.lang = this.language;
                return this.loadLang(this.language);
            }
            return null;
        });
    }
    changeLanguage(newLang) {
        this.language = helper_1.checkWhitelisted([newLang], this.options.whitelist, this.options.fallbackLng);
        Cookie.create(this.options.lookupCookie, this.language);
        return this.loadLang(this.language).then(() => {
            this.listeners.forEach(fn => fn());
        });
    }
    translateOptions(options) {
        return options.map(opt => ({
            ...opt,
            text: this.t(opt.text),
        }));
    }
    on(name, fn) {
        if (name === 'languageChanged') {
            this.listeners.push(fn);
        }
    }
}
exports.I18n = I18n;


/***/ }),

/***/ "../../packages/utils/i18n/index.ts":
/*!************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/i18n/index.ts ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const i18n_1 = __webpack_require__(/*! ./i18n */ "../../packages/utils/i18n/i18n.ts");
exports.default = new i18n_1.I18n();


/***/ }),

/***/ "../../packages/utils/i18n/plural.ts":
/*!*************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/i18n/plural.ts ***!
  \*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// based on https://github.com/i18next/i18next/blob/master/src/PluralResolver.js
// MIT
Object.defineProperty(exports, "__esModule", { value: true });
// definition http://translate.sourceforge.net/wiki/l10n/pluralforms
/* eslint-disable */
const sets = [
    {
        lngs: [
            'ach',
            'ak',
            'am',
            'arn',
            'br',
            'fil',
            'gun',
            'ln',
            'mfe',
            'mg',
            'mi',
            'oc',
            'pt',
            'pt-BR',
            'tg',
            'ti',
            'tr',
            'uz',
            'wa',
        ],
        nr: [1, 2],
        fc: 1,
    },
    {
        lngs: [
            'af',
            'an',
            'ast',
            'az',
            'bg',
            'bn',
            'ca',
            'da',
            'de',
            'dev',
            'el',
            'en',
            'eo',
            'es',
            'et',
            'eu',
            'fi',
            'fo',
            'fur',
            'fy',
            'gl',
            'gu',
            'ha',
            'he',
            'hi',
            'hu',
            'hy',
            'ia',
            'it',
            'kn',
            'ku',
            'lb',
            'mai',
            'ml',
            'mn',
            'mr',
            'nah',
            'nap',
            'nb',
            'ne',
            'nl',
            'nn',
            'no',
            'nso',
            'pa',
            'pap',
            'pms',
            'ps',
            'pt-PT',
            'rm',
            'sco',
            'se',
            'si',
            'so',
            'son',
            'sq',
            'sv',
            'sw',
            'ta',
            'te',
            'tk',
            'ur',
            'yo',
        ],
        nr: [1, 2],
        fc: 2,
    },
    {
        lngs: [
            'ay',
            'bo',
            'cgg',
            'fa',
            'id',
            'ja',
            'jbo',
            'ka',
            'kk',
            'km',
            'ko',
            'ky',
            'lo',
            'ms',
            'sah',
            'su',
            'th',
            'tt',
            'ug',
            'vi',
            'wo',
            'zh',
        ],
        nr: [1],
        fc: 3,
    },
    { lngs: ['be', 'bs', 'dz', 'hr', 'ru', 'sr', 'uk'], nr: [1, 2, 5], fc: 4 },
    { lngs: ['ar'], nr: [0, 1, 2, 3, 11, 100], fc: 5 },
    { lngs: ['cs', 'sk'], nr: [1, 2, 5], fc: 6 },
    { lngs: ['csb', 'pl'], nr: [1, 2, 5], fc: 7 },
    { lngs: ['cy'], nr: [1, 2, 3, 8], fc: 8 },
    { lngs: ['fr'], nr: [1, 2], fc: 9 },
    { lngs: ['ga'], nr: [1, 2, 3, 7, 11], fc: 10 },
    { lngs: ['gd'], nr: [1, 2, 3, 20], fc: 11 },
    { lngs: ['is'], nr: [1, 2], fc: 12 },
    { lngs: ['jv'], nr: [0, 1], fc: 13 },
    { lngs: ['kw'], nr: [1, 2, 3, 4], fc: 14 },
    { lngs: ['lt'], nr: [1, 2, 10], fc: 15 },
    { lngs: ['lv'], nr: [1, 2, 0], fc: 16 },
    { lngs: ['mk'], nr: [1, 2], fc: 17 },
    { lngs: ['mnk'], nr: [0, 1, 2], fc: 18 },
    { lngs: ['mt'], nr: [1, 2, 11, 20], fc: 19 },
    { lngs: ['or'], nr: [2, 1], fc: 2 },
    { lngs: ['ro'], nr: [1, 2, 20], fc: 20 },
    { lngs: ['sl'], nr: [5, 1, 2, 3], fc: 21 },
];
const _rulesPluralsTypes = {
    1(n) {
        return n > 1;
    },
    2(n) {
        return n !== 1;
    },
    3(n) {
        return 0;
    },
    4(n) {
        return n % 10 === 1 && n % 100 !== 11
            ? 0
            : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20)
                ? 1
                : 2;
    },
    5(n) {
        return n === 0
            ? 0
            : n === 1
                ? 1
                : n === 2
                    ? 2
                    : n % 100 >= 3 && n % 100 <= 10
                        ? 3
                        : n % 100 >= 11
                            ? 4
                            : 5;
    },
    6(n) {
        return n === 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2;
    },
    7(n) {
        return n === 1
            ? 0
            : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20)
                ? 1
                : 2;
    },
    8(n) {
        return n === 1 ? 0 : n === 2 ? 1 : n !== 8 && n !== 11 ? 2 : 3;
    },
    9(n) {
        return n >= 2;
    },
    10(n) {
        return n === 1 ? 0 : n === 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4;
    },
    11(n) {
        return n === 1 || n === 11
            ? 0
            : n === 2 || n === 12
                ? 1
                : n > 2 && n < 20
                    ? 2
                    : 3;
    },
    12(n) {
        return n % 10 !== 1 || n % 100 === 11;
    },
    13(n) {
        return n !== 0;
    },
    14(n) {
        return n === 1 ? 0 : n === 2 ? 1 : n === 3 ? 2 : 3;
    },
    15(n) {
        return n % 10 === 1 && n % 100 !== 11
            ? 0
            : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20)
                ? 1
                : 2;
    },
    16(n) {
        return n % 10 === 1 && n % 100 !== 11 ? 0 : n !== 0 ? 1 : 2;
    },
    17(n) {
        return n === 1 || n % 10 === 1 ? 0 : 1;
    },
    18(n) {
        return n === 0 ? 0 : n === 1 ? 1 : 2;
    },
    19(n) {
        return n === 1
            ? 0
            : n === 0 || (n % 100 > 1 && n % 100 < 11)
                ? 1
                : n % 100 > 10 && n % 100 < 20
                    ? 2
                    : 3;
    },
    20(n) {
        return n === 1 ? 0 : n === 0 || (n % 100 > 0 && n % 100 < 20) ? 1 : 2;
    },
    21(n) {
        return n % 100 === 1
            ? 1
            : n % 100 === 2
                ? 2
                : n % 100 === 3 || n % 100 === 4
                    ? 3
                    : 0;
    },
};
function createRules() {
    const ret = {};
    sets.forEach(set => {
        set.lngs.forEach(l => {
            ret[l] = {
                numbers: set.nr,
                plurals: _rulesPluralsTypes[set.fc],
            };
        });
    });
    return ret;
}
const rules = createRules();
function getRule(code) {
    return rules[code] || rules[code.split('-')[0].toLowerCase()];
}
function getSuffix(code, count) {
    const rule = getRule(code);
    if (rule) {
        const idx = Number(rule.plurals(Math.abs(count)));
        const suffix = rule.numbers[idx];
        // special treatment for lngs only having singular and plural
        if (rule.numbers.length === 2 && rule.numbers[0] === 1) {
            if (suffix === 2) {
                return 'plural';
            }
            else if (suffix === 1) {
                return '';
            }
        }
        return idx.toString();
    }
    console.warn(`no plural rule found for: ${code}`);
    return '';
}
exports.getSuffix = getSuffix;


/***/ }),

/***/ "../../packages/utils/jest.ts":
/*!******************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/jest.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.mockable = (fn) => {
    const ret = ((...args) => {
        if (ret.mock) {
            return ret.mock(...args);
        }
        return fn(...args);
    });
    return ret;
};


/***/ }),

/***/ "../../packages/utils/open-access-helper.ts":
/*!********************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/open-access-helper.ts ***!
  \********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const wql_1 = __importDefault(__webpack_require__(/*! wql */ "../../packages/wql/src/index.ts"));
const OpenAccessAPI = __importStar(__webpack_require__(/*! open-access-api */ "../../packages/open-access-api/index.ts"));
const lnl_1 = __webpack_require__(/*! types/lnl */ "../../packages/types/lnl.ts");
exports.getErrorDetails = (e) => {
    const ret = R.getOr(e.response || e, ['body', 'error'], {});
    return ret;
};
exports.getError = (e) => {
    return (exports.getErrorDetails(e).message ||
        (e.response && e.response.error) ||
        e.message ||
        'Unknown error');
};
function _fetchAccount(idProp, account) {
    return OpenAccessAPI.getDirectoryAccounts({
        filter: `${idProp} eq '${account.AccountID}'`,
        directory_id: account.DirectoryID,
    }).pipe(Rx.map(x => {
        const data = x.item_list[0] || {
            display_name: null,
            email: null,
            user_name: null,
            sid: null,
        };
        return Object.assign({}, data, account);
    }));
}
/**
 * Get Cardholder or User directories
 */
function getDirectoriesBase(typeName, filter) {
    return OpenAccessAPI.getAllInstances({
        typeName,
        filter,
    }).pipe(Rx.mergeMap(accounts => {
        if (!accounts.length) {
            return Rx.of([]);
        }
        return OpenAccessAPI.getAllInstances({
            typeName: lnl_1.TypeName.Lnl_Directory,
        }).pipe(Rx.mergeMap(directories => {
            const directoryIndex = R.indexBy(directories, x => x.ID);
            return Rx.from(accounts).pipe(Rx.mergeMap(acc => _fetchAccount(directoryIndex[acc.DirectoryID].AccountIDAttr, acc)), Rx.toArray(), Rx.map(mappedAccounts => {
                const directoryMap = R.indexBy(directories, R.prop('ID'));
                return mappedAccounts.map(item => Object.assign({}, item, {
                    directory: R.getOr(directoryMap, [item.DirectoryID, 'Name'], ''),
                }));
            }));
        }));
    }));
}
exports.getDirectoriesBase = getDirectoriesBase;
exports.mapPossibleValuesToOptions = (property) => {
    if (!property || !property.possible_values) {
        return [];
    }
    return Object.entries(property.possible_values)
        .filter(x => x[1])
        .map(([key, value]) => ({
        text: value,
        value: Number(key),
    }));
};
exports.mapReaderToId = (reader) => `${reader.PanelID}_${reader.ReaderID}`;
exports.readerIdToValues = (id) => {
    const split = id.split('_');
    return {
        PanelID: Number(split[0]),
        ReaderID: Number(split[1]),
    };
};
function isUsingHttpCookie(version) {
    const [versionMajor, versionMinor] = version.split('.').map(x => Number(x));
    return (versionMajor === 7 && versionMinor >= 6) || versionMajor >= 8;
}
exports.isUsingHttpCookie = isUsingHttpCookie;
function getPrinterHash(printer) {
    return JSON.stringify('badgeTypeId' in printer
        ? [printer.printerName, printer.workstation]
        : [printer.printer_name, printer.workstation]);
}
exports.getPrinterHash = getPrinterHash;
function initPrinters(printers, lastPrinter) {
    const duplicates = {};
    const mapped = printers
        .map(printer => ({
        ...printer,
        value: getPrinterHash(printer),
    }))
        .filter(printer => {
        if (duplicates[printer.value]) {
            return false;
        }
        duplicates[printer.value] = true;
        return true;
    });
    const getPrinterId = () => {
        if (lastPrinter && mapped.some(x => x.value === lastPrinter)) {
            return lastPrinter;
        }
        return mapped.length ? mapped[0].value : null;
    };
    return {
        mapped,
        printerId: getPrinterId(),
    };
}
exports.initPrinters = initPrinters;
function getReferenceValue(str) {
    if (str.includes('=')) {
        return Number(str.split('=')[1]);
    }
    return Number(str);
}
function isDynamicSegment(segment, segmentGroupMembers) {
    if (segment.Type === 'segment_unit') {
        return false;
    }
    if (segment.Type === 'dynamic_segment') {
        return true;
    }
    // There's now way in OpenAccess to get all dynamic segments from a given Enterprise Server
    // The code below assumes that a regular segment_group will always have some
    // segmentGroupMembers while dynamic_segment will never have any
    return !segmentGroupMembers.some(segmentGroupMember => getReferenceValue(segmentGroupMember.Group) === segment.ID);
}
exports.isDynamicSegment = isDynamicSegment;
function getSegmentGroupsContainingSegmentUnit(segment, segmentGroupMembers) {
    return segmentGroupMembers
        .filter(segmentGroupMember => getReferenceValue(segmentGroupMember.Member) === segment.ID)
        .map(segmentGroupMember => getReferenceValue(segmentGroupMember.Group));
}
function getDynamicSegmentsContainingSegmentUnit(segment, allSegments, segmentGroupMembers) {
    return allSegments
        .filter(x => isDynamicSegment(x, segmentGroupMembers))
        .filter(x => x.ServerName === segment.ServerName)
        .map(x => x.ID);
}
function getSegmentsUnitsInDynamicGroup(segmentId, allSegments) {
    const segment = allSegments.find(x => x.ID === segmentId);
    return allSegments
        .filter(x => x.ServerName === segment.ServerName)
        .map(x => x.ID);
}
exports.getSegmentsUnitsInDynamicGroup = getSegmentsUnitsInDynamicGroup;
function getSegmentUnitsInSegmentGroup(segmentId, segmentGroupMembers) {
    return segmentGroupMembers
        .filter(segmentGroupMember => getReferenceValue(segmentGroupMember.Group) === segmentId)
        .map(segmentGroupMember => getReferenceValue(segmentGroupMember.Member));
}
exports.getSegmentUnitsInSegmentGroup = getSegmentUnitsInSegmentGroup;
function getSegmentGroupsAndDynamicSegmentsContainingSegmentUnit(segmentId, segmentGroupMembers, allSegments) {
    const segmentsFilter = [segmentId];
    const currentSegment = allSegments.find(x => x.ID === segmentId);
    if (currentSegment && currentSegment.Type === 'segment_unit') {
        const segmentGroups = getSegmentGroupsContainingSegmentUnit(currentSegment, segmentGroupMembers);
        const dynamicSegments = getDynamicSegmentsContainingSegmentUnit(currentSegment, allSegments, segmentGroupMembers);
        segmentsFilter.push(-1, ...segmentGroups, ...dynamicSegments);
    }
    return R.uniq(segmentsFilter);
}
exports.getSegmentGroupsAndDynamicSegmentsContainingSegmentUnit = getSegmentGroupsAndDynamicSegmentsContainingSegmentUnit;
exports.splitWqlConditions = (options) => {
    const separatorLength = options.type.length + 2; // two extra spaces
    const maxLength = options.maxLength || 2000; // max IE length
    const parts = [];
    let current = [];
    let currentTotalLength = 0;
    options.conditions.forEach(condition => {
        // extra brackets are added when using $or or $and
        const str = '(' + wql_1.default(condition) + ')';
        const length = currentTotalLength + str.length + current.length * separatorLength;
        if (length <= maxLength) {
            current.push(condition);
            currentTotalLength += str.length;
        }
        else {
            parts.push(current);
            current = [condition];
            currentTotalLength = str.length;
        }
    });
    if (current.length) {
        parts.push(current);
    }
    return parts;
};
function getAllInstancesWithSplit(opts, orConditions, reqOpts, extraOptions) {
    const conditions = exports.splitWqlConditions({
        type: 'or',
        conditions: orConditions,
    });
    return Rx.from(conditions).pipe(Rx.mergeMap(part => OpenAccessAPI.getAllInstances({
        ...opts,
        filter: wql_1.default({
            $or: part,
        }),
    }, reqOpts, extraOptions)), Rx.toArray(), Rx.map(R.flatten));
}
exports.getAllInstancesWithSplit = getAllInstancesWithSplit;


/***/ }),

/***/ "../../packages/utils/shared-connector.ts":
/*!******************************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/shared-connector.ts ***!
  \******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const wql_1 = __importDefault(__webpack_require__(/*! wql */ "../../packages/wql/src/index.ts"));
const generate_filter_1 = __webpack_require__(/*! ./generate-filter */ "../../packages/utils/generate-filter.ts");
const open_access_helper_1 = __webpack_require__(/*! ./open-access-helper */ "../../packages/utils/open-access-helper.ts");
const i18n_1 = __importDefault(__webpack_require__(/*! ./i18n */ "../../packages/utils/i18n/index.ts"));
const notNullableConditions = [
    'LOCATION',
    'BUILDING',
    'TITLE',
    'DIVISION',
    'ALLOWEDVISITORS',
    'DEPT',
];
exports.getBaseCardholderFilter = (conditions) => {
    const ret = {};
    const conditionIndex = R.indexBy(conditions, x => x.field);
    const check = (propTrue, propFalse, out) => {
        if (conditionIndex[propTrue]) {
            ret[out] = true;
        }
        if (conditionIndex[propFalse]) {
            ret[out] = false;
        }
    };
    check('quick|has_a_badge', 'quick|has_no_badge', 'hasBadges');
    check('quick|has_a_photo', 'quick|has_no_photo', 'hasPhoto');
    check('quick|has_a_signature', 'quick|has_no_signature', 'hasSignature');
    check('quick|has_a_account', 'quick|has_no_account', 'hasAnyDirectoryAccount');
    const alCondition = conditionIndex.access_levels;
    if (alCondition &&
        alCondition.operator &&
        Array.isArray(alCondition.value) &&
        alCondition.value.length) {
        ret.accessLevelList = alCondition.value.map(x => Number(x.value));
        ret.accessLevelSearchType = alCondition.operator;
    }
    return ret;
};
function mapFilterPrefixed(prefix, conditions) {
    if (!conditions) {
        return [];
    }
    return conditions
        .filter(item => item.field.startsWith(prefix))
        .map(item => ({
        ...item,
        field: item.field.split('|')[1],
    }));
}
function generateCardholderFilter(data) {
    const { operator, segmentId, columnConfigMap, segmentGroupMembers, allSegments, } = data;
    const conditions = mapFilterPrefixed('cardholder|', data.conditions);
    const validConditions = generate_filter_1.filterValidConditions(conditions);
    const and = [];
    if (segmentId != null && allSegments != null && segmentGroupMembers != null) {
        and.push({
            PRIMARYSEGMENTID: {
                $in: open_access_helper_1.getSegmentGroupsAndDynamicSegmentsContainingSegmentUnit(segmentId, segmentGroupMembers, allSegments),
            },
        });
    }
    if (validConditions.length) {
        const mappedConditions = validConditions.map(item => {
            const simplifiedField = item.field.split('|')[1]
                ? item.field.split('|')[1]
                : item.field;
            if (item.operator === 'is empty') {
                if (notNullableConditions.some(condition => condition === simplifiedField)) {
                    return {
                        [item.field]: 0,
                    };
                }
                return {
                    [item.field]: null,
                };
            }
            switch (item.field) {
                default: {
                    const columnConfig = columnConfigMap[item.field];
                    const wqlOperator = generate_filter_1.getWqlOperator(item);
                    let value = generate_filter_1.mapToValues(item);
                    if (columnConfig) {
                        if (columnConfig.isDate && value) {
                            value = new Date(value).toISOString();
                        }
                        else if (columnConfig.isBool) {
                            value = generate_filter_1.mapToBool(value);
                        }
                        else if (columnConfig.isInt) {
                            if (typeof value === 'string') {
                                value = Number(value);
                            }
                        }
                        else if (columnConfig.isInt64) {
                            value = { $int64: value };
                        }
                    }
                    if (wqlOperator === '$ne') {
                        return {
                            $or: [
                                { [item.field]: { $ne: value } },
                                { [item.field]: { $eq: null } },
                            ],
                        };
                    }
                    return {
                        [item.field]: {
                            [wqlOperator]: value,
                        },
                    };
                }
            }
        });
        and.push({
            [operator === 'any' ? '$or' : '$and']: mappedConditions,
        });
    }
    if (!and.length) {
        return null;
    }
    return { $and: and };
}
exports.generateCardholderFilter = generateCardholderFilter;
function generateSerializedCardholderFilter(data) {
    const filter = generateCardholderFilter(data);
    return filter ? wql_1.default(filter) : undefined;
}
exports.generateSerializedCardholderFilter = generateSerializedCardholderFilter;
function generateBadgeFilter(data) {
    const { operator, badgePropsMap } = data;
    const conditions = mapFilterPrefixed('badge|', data.conditions);
    const validConditions = generate_filter_1.filterValidConditions(conditions);
    const and = [];
    if (validConditions.length) {
        const mappedConditions = validConditions.map(item => {
            const simplifiedField = item.field.split('|')[1];
            if (item.operator === 'is empty') {
                if (notNullableConditions.some(condition => condition === simplifiedField)) {
                    return {
                        [item.field]: 0,
                    };
                }
                return {
                    [item.field]: null,
                };
            }
            switch (item.field) {
                default: {
                    const wqlOperator = generate_filter_1.getWqlOperator(item);
                    const prop = badgePropsMap[item.field];
                    let value = generate_filter_1.mapToValues(item);
                    if (prop.type === 'datetime (string)') {
                        value = new Date(value).toISOString();
                    }
                    else if (prop.type === 'bool') {
                        value = generate_filter_1.mapToBool(value);
                    }
                    else if (prop.type === 'int32') {
                        if (typeof value === 'string') {
                            value = Number(value);
                        }
                    }
                    else if (prop.type === 'int64') {
                        value = { $int64: value };
                    }
                    if (wqlOperator === '$ne') {
                        return {
                            $or: [
                                { [item.field]: { $ne: value } },
                                { [item.field]: { $eq: null } },
                            ],
                        };
                    }
                    return {
                        [item.field]: {
                            [wqlOperator]: value,
                        },
                    };
                }
            }
        });
        and.push({
            [operator === 'any' ? '$or' : '$and']: mappedConditions,
        });
    }
    if (!and.length) {
        return null;
    }
    return { $and: and };
}
exports.generateBadgeFilter = generateBadgeFilter;
function generateSerializedBadgeFilter(data) {
    const filter = generateBadgeFilter(data);
    return filter ? wql_1.default(filter) : undefined;
}
exports.generateSerializedBadgeFilter = generateSerializedBadgeFilter;
function getColumnConfigMap(cardholderType) {
    const config = {
        photo: {
            isResizable: false,
            width: 60,
            flexGrow: 0,
            value: 'photo',
            text: i18n_1.default.t('common.photo'),
            disabled: false,
            searchable: false,
        },
        activity: {
            isResizable: true,
            width: 250,
            flexGrow: 1,
            value: 'activity',
            text: i18n_1.default.t('cm.activity_last_location'),
            disabled: false,
            searchable: false,
        },
    };
    cardholderType.properties
        .filter(prop => prop.name !== 'ID')
        .forEach(prop => {
        config[prop.name] = {
            isResizable: true,
            width: 160,
            flexGrow: 1,
            searchable: prop.type === 'string',
            isDate: prop.type === 'datetime (string)',
            isBool: prop.type === 'bool',
            isInt: prop.type === 'int32',
            isInt64: prop.type === 'int64',
            text: prop.display_name || prop.name,
            value: prop.name,
        };
    });
    config.actions = {
        isResizable: false,
        width: 45,
        flexGrow: 0,
        value: 'actions',
        text: i18n_1.default.t('common.actions'),
        disabled: true,
        rightDisabled: true,
        searchable: false,
    };
    return config;
}
exports.getColumnConfigMap = getColumnConfigMap;


/***/ }),

/***/ "../../packages/utils/url.ts":
/*!*****************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/utils/url.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function parseQueryString(qs) {
    return (qs || '')
        .replace(/^\?/, '')
        .split('&')
        .reduce((params, param) => {
        const [key, value] = param.split('=');
        if (key) {
            params[key] = value ? decodeURIComponent(value) : '';
        }
        return params;
    }, {});
}
exports.parseQueryString = parseQueryString;
function stringifyQueryString(params) {
    if (!params) {
        return '';
    }
    const keys = Object.keys(params).filter(key => key.length > 0);
    if (!keys.length) {
        return '';
    }
    return ('?' +
        keys
            .map(key => params[key] == null
            ? key
            : `${key}=${encodeURIComponent(params[key].toString())}`)
            .join('&'));
}
exports.stringifyQueryString = stringifyQueryString;
function omitQueryParams(url, params) {
    if (!url.includes('?')) {
        return url;
    }
    const [, base, query, hash] = /^(.+?)(\?.*?)?(\#.*)?$/.exec(url);
    const qs = parseQueryString(query);
    if (Object.keys(qs).length === 0) {
        // return original url with empty query e.g. `/foo?`
        return url;
    }
    params.forEach(param => {
        delete qs[param];
    });
    return base + stringifyQueryString(qs) + (hash || '');
}
exports.omitQueryParams = omitQueryParams;
function getRelativeUrl(location, overrideParams = {}) {
    const search = 'search' in overrideParams ? overrideParams.search : location.search;
    const hash = 'hash' in overrideParams ? overrideParams.hash : location.hash;
    return location.pathname + (search || '') + (hash + '');
}
exports.getRelativeUrl = getRelativeUrl;


/***/ }),

/***/ "../../packages/wql/src/index.ts":
/*!*********************************************************!*\
  !*** G:/B/W/7c552b8bd45deb16/packages/wql/src/index.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
// @ts-ignore
const _ = __importStar(__webpack_require__(/*! lodash */ "lodash"));
const _operators = [
    '$nin',
    '$in',
    '$like',
    '$startsWith',
    '$ne',
    '$eq',
    '$gte',
    '$lte',
    '$gt',
    '$lt',
    '$int64',
];
const _simpleOperators = {
    $ne: '!=',
    $eq: '=',
    $lte: '<=',
    $lt: '<',
    $gt: '>',
    $gte: '>=',
};
/**
 * Serialize value
 * @param {*} value
 * @returns {String}
 * @private
 */
function _serializeValue(value) {
    if (value === null) {
        return 'null';
    }
    if (_.isString(value)) {
        return `"${value}"`;
    }
    if (_.isNumber(value) || _.isBoolean(value)) {
        return String(value);
    }
    if (_.isDate(value)) {
        return value.toISOString();
    }
    if (value && value.$int64) {
        if (typeof value.$int64 !== 'string') {
            throw new Error('$int64 value must be a string');
        }
        return value.$int64;
    }
    throw new Error(`Cannot serialize ${value}. Only strings, numbers, booleans and dates are allowed.`);
}
/**
 * Join conditions by AND/OR
 * @param {Array} conditions
 * @param {String} op
 * @returns {String}
 * @private
 */
function _joinConditions(conditions, op) {
    const joined = conditions.join(` ${op} `);
    if (conditions.length > 1) {
        return `(${joined})`;
    }
    return joined;
}
/**
 * Parse condition to string
 * @param {String} name
 * @param {Object} obj
 * @returns {String}
 * @private
 */
function _convertToString(name, obj) {
    const keys = _.keys(obj);
    if (!keys.length) {
        throw new Error('Must define an operator: ' + _operators.join(', '));
    }
    _.forEach(keys, (key) => {
        if (!_.includes(_operators, key)) {
            throw new Error(`Operator not supported: ${key}`);
        }
    });
    const operators = ['$nin', '$in', '$ne', '$eq', '$like', '$startsWith'];
    if (keys.length > 1 && _.some(operators, (op) => _.has(obj, op))) {
        throw new Error(`${operators.join(', ')} must be the only statement`);
    }
    if (_.has(obj, '$in')) {
        const values = obj.$in;
        if (!_.isArray(values)) {
            throw new Error('Values for $in must be an array');
        }
        if (!values.length) {
            throw new Error('Values for $in must contain at least 1 element');
        }
        // tslint:disable-next-line:no-shadowed-variable
        const conditions = _.map(values, (value) => `${name} = ${_serializeValue(value)}`);
        return _joinConditions(conditions, 'OR');
    }
    if (_.has(obj, '$nin')) {
        const values = obj.$nin;
        if (!_.isArray(values)) {
            throw new Error('Values for $nin must be an array');
        }
        if (!values.length) {
            throw new Error('Values for $nin must contain at least 1 element');
        }
        // tslint:disable-next-line:no-shadowed-variable
        const conditions = _.map(values, (value) => `${name} != ${_serializeValue(value)}`);
        return _joinConditions(conditions, 'AND');
    }
    if (_.has(obj, '$like')) {
        const like = obj.$like;
        if (!_.isString(like)) {
            throw new Error('Value for $like must be a string');
        }
        if (!like) {
            throw new Error('value for $like cannot be null or empty');
        }
        return `${name} like "%${like}%"`;
    }
    if (_.has(obj, '$startsWith')) {
        const like = obj.$startsWith;
        if (!_.isString(like)) {
            throw new Error('Value for $startsWith must be a string');
        }
        if (!like) {
            throw new Error('value for $startsWith cannot be null or empty');
        }
        return `${name} like "${like}%"`;
    }
    if (_.has(obj, '$ne')) {
        return `${name} != ${_serializeValue(obj.$ne)}`;
    }
    if (_.has(obj, '$eq')) {
        return `${name} = ${_serializeValue(obj.$eq)}`;
    }
    if (_.has(obj, '$int64')) {
        if (typeof obj.$int64 !== 'string') {
            throw new Error('$int64 value must be a string');
        }
        return `${name} = ${obj.$int64}`;
    }
    const conditions = [];
    const ops = ['$lte', '$lt', '$gte', '$gt'];
    _.forEach(ops, (op) => {
        if (_.has(obj, op)) {
            conditions.push(`${name} ${_simpleOperators[op]} ${_serializeValue(obj[op])}`);
        }
    });
    return _joinConditions(conditions, 'AND');
}
/**
 * Build a WQL where clause using syntax from MongoDB
 * @param {Object} query
 * @returns {String} the serialized query
 */
function buildFilter(query) {
    if (!_.isObject(query)) {
        throw new Error(`query must be an object, got: ${query}`);
    }
    const keys = _.keys(query);
    if (query.$and || query.$or) {
        if (keys.length > 1) {
            throw new Error('$or/$and must be used without any properties');
        }
        // tslint:disable-next-line:no-shadowed-variable
        const conditions = query.$and || query.$or;
        if (!_.isArray(conditions)) {
            throw new Error('Must pass an array for $or/$and');
        }
        let mapped = _.map(conditions, buildFilter);
        if (mapped.length > 1) {
            mapped = _.map(mapped, (part) => `(${part})`);
        }
        return mapped.join(query.$and ? ' AND ' : ' OR ');
    }
    const conditions = [];
    _.forEach(query, (value, prop) => {
        if (prop[0] === '$') {
            throw new Error(`Invalid query. ${prop} is not allowed.`);
        }
        if (_.isPlainObject(value)) {
            conditions.push(_convertToString(prop, value));
        }
        else {
            conditions.push(`${prop} = ${_serializeValue(value)}`);
        }
    });
    return conditions.join(' AND ');
}
exports.default = buildFilter;


/***/ }),

/***/ "./src/Const.ts":
/*!**********************!*\
  !*** ./src/Const.ts ***!
  \**********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.APP_START_DATE = new Date();
exports.GENERIC_EVENT_PARAMS = {
    event_type: 30,
    event_id: 0,
    source_id: 0,
};
exports.DEFAULT_CARDHOLDER_LIMIT = 5000;
exports.ACC_OBJECT_ID = 181;


/***/ }),

/***/ "./src/bindings/express.ts":
/*!*********************************!*\
  !*** ./src/bindings/express.ts ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const defensive_1 = __webpack_require__(/*! defensive */ "defensive");
defensive_1.ContractBinding.prototype.express = function (options) {
    if (!this.fn.expressOptions) {
        this.fn.expressOptions = [];
    }
    this.fn.expressOptions.push(options);
    return this.fn;
};


/***/ }),

/***/ "./src/bootstrap.ts":
/*!**************************!*\
  !*** ./src/bootstrap.ts ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! reflect-metadata */ "reflect-metadata");
__webpack_require__(/*! ./validation */ "./src/validation.ts");
__webpack_require__(/*! ./bindings/express */ "./src/bindings/express.ts");
__webpack_require__(/*! ./onGuardApi */ "./src/onGuardApi.ts");
const fs_1 = __importDefault(__webpack_require__(/*! fs */ "fs"));
const path_1 = __importDefault(__webpack_require__(/*! path */ "path"));
const regedit_1 = __importDefault(__webpack_require__(/*! regedit */ "regedit"));
const defensive_1 = __webpack_require__(/*! defensive */ "defensive");
const logger_1 = __webpack_require__(/*! ./common/logger */ "./src/common/logger.ts");
const loggerMap = {};
defensive_1.setDefaultConfig({
    removeFields: ['password', 'token', 'accessToken', 'apiKey'],
    getLogger(serviceName) {
        if (!loggerMap[serviceName]) {
            const logger = logger_1.createLogger(serviceName);
            loggerMap[serviceName] = logger;
        }
        return loggerMap[serviceName];
    },
});
if (process.pkg) {
    const vbsPath = path_1.default.join(path_1.default.dirname(process.execPath), 'vbs');
    if (!fs_1.default.existsSync(vbsPath)) {
        throw new Error('"vbs" directory does not exist!');
    }
    regedit_1.default.setExternalVBSLocation(vbsPath);
}


/***/ }),

/***/ "./src/common/FetchRateLimiter.ts":
/*!****************************************!*\
  !*** ./src/common/FetchRateLimiter.ts ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
class FetchRateLimiter {
    constructor(maxRequests, fetchFn) {
        this.maxRequests = maxRequests;
        this.fetchFn = fetchFn;
        this.current = [];
        this.queue = [];
    }
    async fetch(input, init) {
        return new Promise((resolve, reject) => {
            this.queue.push({
                resolve,
                reject,
                input,
                init,
            });
            this.checkQueue();
        });
    }
    checkQueue() {
        if (this.current.length < this.maxRequests) {
            const count = this.maxRequests - this.current.length;
            const jobs = this.queue.slice(0, count);
            Promise.all(jobs.map(job => this.process(job).catch(e => {
                console.error('failed to process rate limiter job', e);
            })));
        }
    }
    async process(job) {
        this.current.push(job);
        this.queue.splice(this.queue.indexOf(job), 1);
        await this.fetchFn(job.input, job.init)
            .then(res => job.resolve(res))
            .catch(e => job.reject(e));
        this.current.splice(this.current.indexOf(job), 1);
        this.checkQueue();
    }
}
exports.FetchRateLimiter = FetchRateLimiter;


/***/ }),

/***/ "./src/common/dbHelper.ts":
/*!********************************!*\
  !*** ./src/common/dbHelper.ts ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const db_1 = __webpack_require__(/*! ../db */ "./src/db.ts");
/*
 * We used to use connection.manager.save() but this function updates
 * related entities in a cascading manner. This means e.g. if we saved
 * a Push entity, Site was saved to whatever was in push.site.
 * Due to this behavior we don't recommend to use save() anywhere.
 */
async function updateEntity(entity, props) {
    const getClass = () => {
        for (const Entity of db_1.connection.options.entities) {
            if (entity instanceof Entity) {
                return Entity;
            }
        }
        throw new Error('Cannot get entity class');
    };
    await db_1.connection.manager.update(getClass(), {
        id: entity.id,
    }, R.pick(entity, props));
}
exports.updateEntity = updateEntity;


/***/ }),

/***/ "./src/common/dbTypes.ts":
/*!*******************************!*\
  !*** ./src/common/dbTypes.ts ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = __importDefault(__webpack_require__(/*! ../config */ "./src/config.ts"));
exports.NVARCHAR_MAX = {
    type: config_1.default.DB_TYPE === 'oracle'
        ? 'nclob'
        : 'nvarchar',
    length: config_1.default.DB_TYPE === 'oracle' ? undefined : 'MAX',
};
exports.NVARCHAR = {
    type: config_1.default.DB_TYPE === 'oracle'
        ? 'nvarchar2'
        : 'nvarchar',
};


/***/ }),

/***/ "./src/common/elementsApiCache.ts":
/*!****************************************!*\
  !*** ./src/common/elementsApiCache.ts ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ms_1 = __importDefault(__webpack_require__(/*! ms */ "ms"));
const ElementsAPI_1 = __webpack_require__(/*! ../services/ElementsAPI */ "./src/services/ElementsAPI.ts");
const config_1 = __importDefault(__webpack_require__(/*! ../config */ "./src/config.ts"));
const _elementsAPICache = {};
async function getCachedElementsApi(apiKey) {
    if (!apiKey) {
        return null;
    }
    if (!_elementsAPICache[apiKey]) {
        _elementsAPICache[apiKey] = Promise.resolve()
            .then(async () => {
            const elementsAPI = new ElementsAPI_1.ElementsAPI({
                remoteManagementServiceBaseUrl: config_1.default.ELEMENTS_REMOTE_MANAGEMENT_SERVICE_URL,
            });
            const isOnline = await elementsAPI
                .authenticate(apiKey)
                .then(() => true)
                .catch(e => {
                if (e.message === 'access_denied') {
                    return false;
                }
                throw e;
            });
            if (!isOnline) {
                return null;
            }
            const customer = (await elementsAPI.getMyCustomers())[0];
            if (!customer) {
                return null;
            }
            elementsAPI.setCustomerId(customer.id);
            return elementsAPI;
        })
            .then(ret => {
            setTimeout(() => {
                delete _elementsAPICache[apiKey];
            }, ms_1.default('30m'));
            return ret;
        })
            .catch(e => {
            // don't cache errors
            delete _elementsAPICache[apiKey];
            throw e;
        });
    }
    return _elementsAPICache[apiKey];
}
exports.getCachedElementsApi = getCachedElementsApi;


/***/ }),

/***/ "./src/common/errors.ts":
/*!******************************!*\
  !*** ./src/common/errors.ts ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
class HttpError extends Error {
    constructor(statusCode, message) {
        super(message);
        this.statusCode = statusCode;
    }
}
exports.HttpError = HttpError;
class NotFoundError extends HttpError {
    constructor(message) {
        super(404, message);
    }
}
exports.NotFoundError = NotFoundError;
class BadRequestError extends HttpError {
    constructor(message, params) {
        super(400, message);
        this.params = params;
    }
}
exports.BadRequestError = BadRequestError;
class UnauthorizedError extends HttpError {
    constructor(message) {
        super(401, message);
    }
}
exports.UnauthorizedError = UnauthorizedError;
class ForbiddenError extends HttpError {
    constructor(message) {
        super(403, message);
    }
}
exports.ForbiddenError = ForbiddenError;
class ElementsError extends Error {
    constructor(message, errorCode, errors) {
        super(message);
        this.errorCode = errorCode;
        this.errors = errors;
    }
}
exports.ElementsError = ElementsError;


/***/ }),

/***/ "./src/common/getUniqName.ts":
/*!***********************************!*\
  !*** ./src/common/getUniqName.ts ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const wql_1 = __importDefault(__webpack_require__(/*! wql */ "../../packages/wql/src/index.ts"));
const onGuardApi_1 = __webpack_require__(/*! ../onGuardApi */ "./src/onGuardApi.ts");
async function getUniqName(typeName, baseName) {
    const trimmedBaseName = baseName.trim();
    const items = await onGuardApi_1.api.getAllInstances({
        typeName,
        filter: wql_1.default({
            Name: { $startsWith: trimmedBaseName },
        }),
    });
    const map = R.indexBy(items, x => x.Name.trim().toLowerCase());
    let num = 1;
    while (true) {
        const nextName = num > 1 ? `${trimmedBaseName}-${num}` : trimmedBaseName;
        if (!map[nextName.toLowerCase()]) {
            return nextName;
        }
        num++;
    }
}
exports.getUniqName = getUniqName;


/***/ }),

/***/ "./src/common/helper.ts":
/*!******************************!*\
  !*** ./src/common/helper.ts ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ms_1 = __importDefault(__webpack_require__(/*! ms */ "ms"));
const logger_1 = __importDefault(__webpack_require__(/*! ./logger */ "./src/common/logger.ts"));
function decodeApiKey(apiKey) {
    try {
        const json = Buffer.from(apiKey, 'base64').toString('utf8');
        return JSON.parse(json);
    }
    catch (e) {
        throw new Error('Invalid API Key. Cannot decode');
    }
}
exports.decodeApiKey = decodeApiKey;
function getTableName(name) {
    // only for local development to avoid conflicts
    if (Object({"NODE_TLS_REJECT_UNAUTHORIZED":"0","NODE_ENV":"production","IS_LAMBDA":undefined}).TABLE_SUFFIX) {
        return name + '_' + Object({"NODE_TLS_REJECT_UNAUTHORIZED":"0","NODE_ENV":"production","IS_LAMBDA":undefined}).TABLE_SUFFIX;
    }
    return name;
}
exports.getTableName = getTableName;
function runJob(fn, time) {
    const start = () => fn()
        .catch(e => {
        logger_1.default.error(e);
    })
        .then((nextTime) => {
        setTimeout(start, ms_1.default(nextTime || time));
    });
    start();
}
exports.runJob = runJob;
function getTotalSeconds(date) {
    return Math.floor(new Date(date).getTime() / 1000);
}
exports.getTotalSeconds = getTotalSeconds;
async function getMsSqlDatabaseName(connection) {
    return (await connection.query('SELECT DB_NAME() AS name'))[0].name;
}
exports.getMsSqlDatabaseName = getMsSqlDatabaseName;
function getSiteLogEntry(site) {
    return `${site.id} (${site.cloudName})`;
}
exports.getSiteLogEntry = getSiteLogEntry;


/***/ }),

/***/ "./src/common/logger.ts":
/*!******************************!*\
  !*** ./src/common/logger.ts ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/**
 * Global logger
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bunyan_1 = __importDefault(__webpack_require__(/*! bunyan */ "bunyan"));
const fs_1 = __importDefault(__webpack_require__(/*! fs */ "fs"));
const eol_1 = __importDefault(__webpack_require__(/*! eol */ "eol"));
const bunyan_format_1 = __importDefault(__webpack_require__(/*! bunyan-format */ "bunyan-format"));
const config_1 = __importDefault(__webpack_require__(/*! ../config */ "./src/config.ts"));
const util_1 = __importDefault(__webpack_require__(/*! util */ "util"));
const isPacked = !!process.pkg;
const file = isPacked
    ? fs_1.default.createWriteStream(config_1.default.LOG_FILE, { flags: 'a' })
    : null;
const formatOut = new bunyan_format_1.default({ outputMode: 'simple', color: !isPacked }, {
    write(data) {
        const formatted = _sanitize(`${new Date().toISOString()} ${data}`);
        process.stdout.write(formatted);
        if (file) {
            file.write(eol_1.default.crlf(formatted));
        }
    },
});
function createLogger(name) {
    const logger = bunyan_1.default.createLogger({
        name,
        serializers: bunyan_1.default.stdSerializers,
        level: config_1.default.LOG_LEVEL,
        stream: formatOut,
    });
    return logger;
}
exports.createLogger = createLogger;
function traceHttpRequest(logger, method, url, requestBody, responseStatus, responseBody) {
    logger.trace(`[HTTP Request] ${method} ${url}\r\n`, {
        requestBody: util_1.default.inspect(requestBody, { depth: null }),
        responseStatus,
        responseBody: util_1.default.inspect(responseBody, { depth: null }),
    });
}
exports.traceHttpRequest = traceHttpRequest;
exports.default = createLogger('app');
function _sanitize(str) {
    return str.replace(/(username|password)=([^&]+)/g, '$1=<removed>');
}


/***/ }),

/***/ "./src/config.ts":
/*!***********************!*\
  !*** ./src/config.ts ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(__webpack_require__(/*! fs */ "fs"));
const path_1 = __importDefault(__webpack_require__(/*! path */ "path"));
let config;
const isPacked = !!process.pkg;
const configDir = isPacked ? path_1.default.dirname(process.execPath) : process.cwd();
const configPath = path_1.default.join(configDir, 'config.json');
function getConfigFile() {
    if (!fs_1.default.existsSync(configPath)) {
        throw new Error('"config.json" file does not exist!');
    }
    try {
        return JSON.parse(fs_1.default.readFileSync(configPath, 'utf8'));
    }
    catch (_a) {
        throw new Error('config.json" is not a valid JSON file!');
    }
}
config = {
    PORT: 3900,
    OPEN_ACCESS_API_BASE_URL: 'https://localhost:8080',
    APPLICATION_ID: 'SYS_ADMIN_APP',
    GLOBAL_USER_NAME: '',
    GLOBAL_USER_PASSWORD: '',
    GLOBAL_DIRECTORY_ID: 'id-1',
    LOG_FILE: 'C:\\ProgramData\\Lnl\\logs\\LsElementsConnector.log',
    LOG_LEVEL: 'INFO',
    OG_KEY: 'HKLM\\SOFTWARE\\Wow6432Node\\Lenel\\OnGuard',
    ELEMENTS_REMOTE_MANAGEMENT_SERVICE_URL: 'https://remotemanagementservice.elementssecure.com/api',
    ELEMENTS_PING_URL: 'https://portal.elementssecure.com/login',
    DB_TYPE: 'mssql',
    DB_HOST: '127.0.0.1',
    DB_PORT: 1433,
    DB_USERNAME: 'sa',
    DB_PASSWORD: '',
    DB_DATABASE_NAME: 'msdb',
    CARDHOLDER_PUSH_RUNS_DAILY: 1,
    CARDHOLDER_PUSH_FIRST_RUN_HOUR: 0,
    USE_SHORT_ONGUARD_BADGE_ID: false,
    HTTPS_PROXY: undefined,
    ELEMENTS_MAX_PARALLEL_REQUESTS: 5,
    ...getConfigFile(),
};
function updateConfig(values) {
    Object.assign(config, values);
    const newConfig = { ...getConfigFile(), ...values };
    fs_1.default.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));
}
exports.updateConfig = updateConfig;
exports.default = config;


/***/ }),

/***/ "./src/contracts/misc/audit.ts":
/*!*************************************!*\
  !*** ./src/contracts/misc/audit.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const veni_1 = __webpack_require__(/*! veni */ "veni");
const os_1 = __importDefault(__webpack_require__(/*! os */ "os"));
const defensive_1 = __webpack_require__(/*! defensive */ "defensive");
const AuditRecord_1 = __webpack_require__(/*! ../../entity/AuditRecord */ "./src/entity/AuditRecord.ts");
const db_1 = __webpack_require__(/*! ../../db */ "./src/db.ts");
const AccTrans_1 = __webpack_require__(/*! ../../entity/AccTrans */ "./src/entity/AccTrans.ts");
const onGuardApi_1 = __webpack_require__(/*! ../../onGuardApi */ "./src/onGuardApi.ts");
const Const_1 = __webpack_require__(/*! ../../Const */ "./src/Const.ts");
const config_1 = __importDefault(__webpack_require__(/*! ../../config */ "./src/config.ts"));
const auditMap = {
    'site-added': 'Site Added',
    'site-deleted': 'Site Deleted',
    'site-disconnected': 'Site Disconnected',
    'site-reconnected': 'Site Reconnected',
    'logical-source-recreated': 'Logical Source Recreated',
    'push-rules-changed': 'Credential Push Rules Changed',
    'push-initiated': 'Credential Push Initiated',
    'push-canceled': 'Credential Push Canceled',
};
async function insertRawAccTrans(acc) {
    const params = [
        acc.userId,
        acc.operationId,
        acc.objectId,
        acc.enterValue,
        acc.date,
        acc.computerName,
        acc.lnlDatabaseId,
        acc.notes,
        acc.timestamp,
        acc.applicationId,
        acc.persistTypeId,
        acc.regionId,
        acc.utcOffset,
    ];
    if (config_1.default.DB_TYPE === 'oracle') {
        await db_1.connection.manager.query(`INSERT INTO ACCTRANS
    (ACCROWID
    ,USERID
    ,ACCTRANS_OPERATIONID
    ,ACCTRANS_OBJECTID
    ,ENTERVALUE
    ,ACCDATE
    ,COMPUTERN
    ,LNL_DBID
    ,USER_NOTES
    ,TIMESTAMP
    ,APPLICATIONID
    ,PERSIST_TYPEID
    ,REGION_ACCROWID
    ,UTC_OFFSET)
  VALUES
    ("ACC_ROWID".nextval
    ,:0
    ,:1
    ,:2
    ,:3
    ,:4
    ,:5
    ,:6
    ,:7
    ,:8
    ,:9
    ,:10
    ,:11
    ,:12)
  `, params);
    }
    else {
        await db_1.connection.manager.query(`INSERT INTO [dbo].[ACCTRANS]
    ([USERID]
    ,[ACCTRANS_OPERATIONID]
    ,[ACCTRANS_OBJECTID]
    ,[ENTERVALUE]
    ,[ACCDATE]
    ,[COMPUTERN]
    ,[LNL_DBID]
    ,[USER_NOTES]
    ,[TIMESTAMP]
    ,[APPLICATIONID]
    ,[PERSIST_TYPEID]
    ,[REGION_ACCROWID]
    ,[UTC_OFFSET])
  VALUES
    (@0
    ,@1
    ,@2
    ,@3
    ,@4
    ,@5
    ,@6
    ,@7
    ,@8
    ,@9
    ,@10
    ,@11
    ,@12)
  `, params);
    }
}
exports.audit = defensive_1.createContract('misc#audit')
    .params('user', 'site', 'type')
    .schema({
    user: veni_1.V.object()
        .unknown()
        .nullable(),
    site: veni_1.V.object().unknown(),
    type: veni_1.V.enum().literal(...Object.keys(auditMap)),
})
    .fn(async (user, site, type) => {
    const userId = user ? user.id : null;
    const record = new AuditRecord_1.AuditRecord();
    record.timestamp = new Date();
    record.siteId = site.id;
    record.eventType = auditMap[type];
    record.logicalSourceId = site.logicalSourceId;
    record.apiKey = site.apiKey;
    record.customerId = site.customerId;
    record.filter = site.filter;
    record.userId = userId;
    await db_1.connection.manager.insert(AuditRecord_1.AuditRecord, record);
    const enterpriseSettings = await onGuardApi_1.api.getEnterpriseSettings();
    const acc = new AccTrans_1.AccTrans();
    const timestamp = new Date();
    const offset = timestamp.getTimezoneOffset();
    timestamp.setMinutes(timestamp.getMinutes() + offset);
    acc.userId = userId && Number(userId.replace('id', ''));
    acc.date = null;
    acc.computerName = os_1.default.hostname();
    acc.lnlDatabaseId = enterpriseSettings.is_enterprise_system
        ? enterpriseSettings.local_database_id
        : 0;
    acc.notes = null;
    acc.applicationId = null;
    acc.persistTypeId = 746;
    acc.regionId = null;
    acc.timestamp = timestamp;
    acc.utcOffset = -offset;
    acc.objectId = Const_1.ACC_OBJECT_ID;
    const formattedSite = `cloud site ${site.cloudName}(${site.id})`;
    switch (type) {
        case 'site-added':
            acc.operationId = 4;
            acc.enterValue = `Added ${formattedSite}`;
            break;
        case 'site-deleted':
            acc.operationId = 7;
            acc.enterValue = `Removed ${formattedSite}`;
            break;
        case 'site-disconnected':
            acc.operationId = 52;
            acc.enterValue = `Disconnected ${formattedSite}`;
            break;
        case 'site-reconnected':
            acc.operationId = 53;
            acc.enterValue = `Reconnected ${formattedSite}`;
            break;
        case 'logical-source-recreated':
            acc.operationId = 158;
            acc.enterValue = `Recreated logical source for ${formattedSite}`;
            break;
        case 'push-rules-changed':
            acc.operationId = 6;
            acc.enterValue = `Changed cardholder push rules for ${formattedSite}`;
            break;
        case 'push-initiated':
            acc.operationId = 48;
            acc.enterValue = `Manually initiated cardholder push for ${formattedSite}`;
            break;
        case 'push-canceled':
            acc.operationId = 45;
            acc.enterValue = `Canceled cardholder push for ${formattedSite}`;
            break;
    }
    await insertRawAccTrans(acc);
});


/***/ }),

/***/ "./src/contracts/security/_encryption.ts":
/*!***********************************************!*\
  !*** ./src/contracts/security/_encryption.ts ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = __importDefault(__webpack_require__(/*! crypto */ "crypto"));
function encrypt(key, text) {
    const cipher = crypto_1.default.createCipher('aes-256-ctr', key);
    let crypted = cipher.update(text, 'utf8', 'hex');
    crypted += cipher.final('hex');
    return crypted;
}
exports.encrypt = encrypt;
function decrypt(text, key) {
    const decipher = crypto_1.default.createDecipher('aes-256-ctr', key);
    let dec = decipher.update(text, 'hex', 'utf8');
    dec += decipher.final('utf8');
    return dec;
}
exports.decrypt = decrypt;


/***/ }),

/***/ "./src/contracts/security/decryptAPIUser.ts":
/*!**************************************************!*\
  !*** ./src/contracts/security/decryptAPIUser.ts ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const defensive_1 = __webpack_require__(/*! defensive */ "defensive");
const config_1 = __importDefault(__webpack_require__(/*! ../../config */ "./src/config.ts"));
const getKey_1 = __webpack_require__(/*! ./getKey */ "./src/contracts/security/getKey.ts");
const _encryption_1 = __webpack_require__(/*! ./_encryption */ "./src/contracts/security/_encryption.ts");
exports.decryptAPIUser = defensive_1.createContract('security#decryptAPIUser')
    .options({
    removeOutput: true,
})
    .params()
    .fn(async () => {
    if (!config_1.default.IS_ENCRYPTED) {
        return {
            username: config_1.default.GLOBAL_USER_NAME,
            password: config_1.default.GLOBAL_USER_PASSWORD,
            directoryId: config_1.default.GLOBAL_DIRECTORY_ID,
        };
    }
    const key = await getKey_1.getKey();
    return {
        username: _encryption_1.decrypt(config_1.default.GLOBAL_USER_NAME, key),
        password: _encryption_1.decrypt(config_1.default.GLOBAL_USER_PASSWORD, key),
        directoryId: config_1.default.GLOBAL_DIRECTORY_ID,
    };
});


/***/ }),

/***/ "./src/contracts/security/decryptDBUser.ts":
/*!*************************************************!*\
  !*** ./src/contracts/security/decryptDBUser.ts ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const defensive_1 = __webpack_require__(/*! defensive */ "defensive");
const config_1 = __importDefault(__webpack_require__(/*! ../../config */ "./src/config.ts"));
const getKey_1 = __webpack_require__(/*! ./getKey */ "./src/contracts/security/getKey.ts");
const _encryption_1 = __webpack_require__(/*! ./_encryption */ "./src/contracts/security/_encryption.ts");
exports.decryptDBUser = defensive_1.createContract('security#decryptDBUser')
    .options({
    removeOutput: true,
})
    .params()
    .fn(async () => {
    if (!config_1.default.DB_IS_ENCRYPTED) {
        return {
            username: config_1.default.DB_USERNAME,
            password: config_1.default.DB_PASSWORD,
        };
    }
    const key = await getKey_1.getKey();
    return {
        username: _encryption_1.decrypt(config_1.default.DB_USERNAME, key),
        password: _encryption_1.decrypt(config_1.default.DB_PASSWORD, key),
    };
});


/***/ }),

/***/ "./src/contracts/security/getKey.ts":
/*!******************************************!*\
  !*** ./src/contracts/security/getKey.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const defensive_1 = __webpack_require__(/*! defensive */ "defensive");
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const crypto_1 = __importDefault(__webpack_require__(/*! crypto */ "crypto"));
const config_1 = __importDefault(__webpack_require__(/*! ../../config */ "./src/config.ts"));
const regedit_1 = __importDefault(__webpack_require__(/*! regedit */ "regedit"));
exports.getKey = defensive_1.createContract('security#getKey')
    .options({
    removeOutput: true,
})
    .params()
    .fn(async () => {
    const result = await new Promise((resolve, reject) => regedit_1.default.list(config_1.default.OG_KEY, (err, value) => {
        if (err) {
            reject(err);
        }
        else {
            resolve(value);
        }
    }));
    let key = R.getOr(result[config_1.default.OG_KEY], ['values', 'ElementsConnectorProductCode', 'value'], '');
    if (key) {
        return key;
    }
    key = crypto_1.default.randomBytes(10).toString('hex');
    const registryValue = {
        [config_1.default.OG_KEY]: {
            ElementsConnectorProductCode: {
                value: key,
                type: 'REG_SZ',
            },
        },
    };
    await new Promise((resolve, reject) => regedit_1.default.putValue(registryValue, err => (err ? reject(err) : resolve())));
    return key;
});


/***/ }),

/***/ "./src/contracts/site/_checkAccess.ts":
/*!********************************************!*\
  !*** ./src/contracts/site/_checkAccess.ts ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = __webpack_require__(/*! ../../common/errors */ "./src/common/errors.ts");
const onGuardApi_1 = __webpack_require__(/*! ../../onGuardApi */ "./src/onGuardApi.ts");
const wql_1 = __importDefault(__webpack_require__(/*! wql */ "../../packages/wql/src/index.ts"));
const lnl_1 = __webpack_require__(/*! types/lnl */ "../../packages/types/lnl.ts");
async function _checkAccess(user, logicalSourceId) {
    const segmentationSettings = await onGuardApi_1.api.getSegmentationSettings();
    if (segmentationSettings.segmentation_enabled) {
        const logicalSource = await onGuardApi_1.api.getSingleInstances({
            typeName: lnl_1.TypeName.Lnl_LogicalSource,
            filter: wql_1.default({
                ID: logicalSourceId,
            }),
            allowEmpty: true,
        });
        if (!logicalSource) {
            return;
        }
        if (!user.segments.some(item => item.segment_id === logicalSource.SegmentID)) {
            throw new errors_1.ForbiddenError(`You don't have permission to access this site`);
        }
    }
}
exports._checkAccess = _checkAccess;


/***/ }),

/***/ "./src/contracts/site/_getDbSite.ts":
/*!******************************************!*\
  !*** ./src/contracts/site/_getDbSite.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = __webpack_require__(/*! ../../common/errors */ "./src/common/errors.ts");
const db_1 = __webpack_require__(/*! ../../db */ "./src/db.ts");
const Site_1 = __webpack_require__(/*! ../../entity/Site */ "./src/entity/Site.ts");
const _checkAccess_1 = __webpack_require__(/*! ./_checkAccess */ "./src/contracts/site/_checkAccess.ts");
async function getDbSite(user, id) {
    const site = await db_1.connection.manager.findOne(Site_1.ConnectorSite, { id });
    if (!site) {
        throw new errors_1.NotFoundError(`Site ${id} does not exist`);
    }
    if (user) {
        await _checkAccess_1._checkAccess(user, site.logicalSourceId);
    }
    return site;
}
exports.getDbSite = getDbSite;


/***/ }),

/***/ "./src/contracts/site/_initElements.ts":
/*!*********************************************!*\
  !*** ./src/contracts/site/_initElements.ts ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ElementsAPI_1 = __webpack_require__(/*! ../../services/ElementsAPI */ "./src/services/ElementsAPI.ts");
const config_1 = __importDefault(__webpack_require__(/*! ../../config */ "./src/config.ts"));
const errors_1 = __webpack_require__(/*! ../../common/errors */ "./src/common/errors.ts");
const Const_1 = __webpack_require__(/*! ../../Const */ "./src/Const.ts");
async function _initElements(apiKey) {
    const elementsAPI = new ElementsAPI_1.ElementsAPI({
        remoteManagementServiceBaseUrl: config_1.default.ELEMENTS_REMOTE_MANAGEMENT_SERVICE_URL,
    });
    await elementsAPI.authenticate(apiKey).catch(e => {
        if (e.message === 'access_denied') {
            throw new errors_1.BadRequestError('invalid_api_key');
        }
        throw new errors_1.BadRequestError('Failed to authenticate to the cloud site. Verify that the API key is valid. Original error: ' +
            e.message);
    });
    const customer = (await elementsAPI.getMyCustomers())[0];
    if (!customer) {
        throw new Error('No customer in Elements API');
    }
    elementsAPI.setCustomerId(customer.id);
    if (!customer.externallyManagedPeopleLimit) {
        customer.externallyManagedPeopleLimit = Const_1.DEFAULT_CARDHOLDER_LIMIT;
    }
    return { elementsAPI, customer };
}
exports._initElements = _initElements;


/***/ }),

/***/ "./src/contracts/site/_mapPush.ts":
/*!****************************************!*\
  !*** ./src/contracts/site/_mapPush.ts ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
function _mapPush(item) {
    return {
        id: item.id,
        started: item.started,
        completed: item.completed,
        status: item.status,
        errorCount: item.errorCount || 0,
        cardholderCount: item.cardholderCount || 0,
        badgeCount: item.badgeCount || 0,
    };
}
exports._mapPush = _mapPush;


/***/ }),

/***/ "./src/contracts/site/cancelSync.ts":
/*!******************************************!*\
  !*** ./src/contracts/site/cancelSync.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const veni_1 = __webpack_require__(/*! veni */ "veni");
const defensive_1 = __webpack_require__(/*! defensive */ "defensive");
const _getDbSite_1 = __webpack_require__(/*! ./_getDbSite */ "./src/contracts/site/_getDbSite.ts");
const syncJob_1 = __webpack_require__(/*! ../../jobs/syncJob */ "./src/jobs/syncJob.ts");
const audit_1 = __webpack_require__(/*! ../misc/audit */ "./src/contracts/misc/audit.ts");
const worker_api_1 = __webpack_require__(/*! ../../worker-api */ "./src/worker-api.ts");
exports.cancelSync = defensive_1.createContract('site#cancelSync')
    .params('user', 'siteId')
    .schema({
    user: veni_1.V.object().unknown(),
    siteId: veni_1.V.number(),
})
    .fn(async (user, siteId) => {
    const dbSite = await _getDbSite_1.getDbSite(user, siteId);
    const syncInfo = syncJob_1.getSyncInfo();
    if (syncInfo && syncInfo.site.id === dbSite.id) {
        await syncInfo.cancel();
        await audit_1.audit(user, dbSite, 'push-canceled');
    }
})
    .express({
    method: 'post',
    path: '/sites/:id/cancel',
    async json(req) {
        await worker_api_1.sendWorkerMessage({
            type: 'cancel-sync',
            siteId: req.params.id,
            user: req.user,
        });
    },
});


/***/ }),

/***/ "./src/contracts/site/sync.ts":
/*!************************************!*\
  !*** ./src/contracts/site/sync.ts ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const veni_1 = __webpack_require__(/*! veni */ "veni");
const defensive_1 = __webpack_require__(/*! defensive */ "defensive");
const _getDbSite_1 = __webpack_require__(/*! ./_getDbSite */ "./src/contracts/site/_getDbSite.ts");
const errors_1 = __webpack_require__(/*! ../../common/errors */ "./src/common/errors.ts");
const _mapPush_1 = __webpack_require__(/*! ./_mapPush */ "./src/contracts/site/_mapPush.ts");
const Push_1 = __webpack_require__(/*! ../../entity/Push */ "./src/entity/Push.ts");
const db_1 = __webpack_require__(/*! ../../db */ "./src/db.ts");
const audit_1 = __webpack_require__(/*! ../misc/audit */ "./src/contracts/misc/audit.ts");
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
const worker_api_1 = __webpack_require__(/*! ../../worker-api */ "./src/worker-api.ts");
async function _getSite(user, id) {
    const dbSite = await _getDbSite_1.getDbSite(user, id);
    if (!dbSite.apiKey) {
        throw new errors_1.BadRequestError('Site is disconnected');
    }
    if (!dbSite.filter) {
        throw new errors_1.BadRequestError('Cardholder filter is not set');
    }
    return dbSite;
}
exports.sync = defensive_1.createContract('site#sync')
    .params('user', 'id', 'force')
    .schema({
    user: veni_1.V.object().unknown(),
    id: veni_1.V.number(),
    force: veni_1.V.boolean().optional(),
})
    .fn(async (user, id, force) => {
    const dbSite = await _getSite(user, id);
    const existing = await db_1.connection.manager.findOne(Push_1.Push, {
        where: {
            site: dbSite,
            status: typeorm_1.In(['pending', 'queued']),
        },
    });
    if (existing) {
        if (force) {
            await worker_api_1.sendWorkerMessage({
                type: 'cancel-sync',
                siteId: dbSite.id,
                user,
            });
        }
        else {
            return {
                result: 'sync-in-progress',
            };
        }
    }
    await db_1.connection
        .createQueryBuilder()
        .update(Push_1.Push)
        .set({
        status: 'canceled',
        completed: new Date(),
    })
        .where({
        site: dbSite,
        status: 'queued',
    })
        .execute();
    const push = new Push_1.Push();
    push.site = dbSite;
    push.status = 'queued';
    await db_1.connection.manager.insert(Push_1.Push, push);
    await audit_1.audit(user, dbSite, 'push-initiated');
    return {
        result: 'syncing',
        sitePush: _mapPush_1._mapPush(push),
    };
})
    .express({
    method: 'post',
    path: '/sites/:id/sync',
    async json(req) {
        return exports.sync(req.user, req.params.id, req.body.force);
    },
});
exports.syncAuto = defensive_1.createContract('site#syncAuto')
    .params('id', 'autoScheduledDate')
    .schema({
    id: veni_1.V.number(),
    autoScheduledDate: veni_1.V.date(),
})
    .fn(async (id, autoScheduledDate) => {
    const dbSite = await _getSite(null, id);
    const push = new Push_1.Push();
    push.site = dbSite;
    push.status = 'queued';
    push.isAuto = true;
    push.autoScheduledDate = autoScheduledDate;
    await db_1.connection.manager.insert(Push_1.Push, push);
});


/***/ }),

/***/ "./src/db.ts":
/*!*******************!*\
  !*** ./src/db.ts ***!
  \*******************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
const config_1 = __importDefault(__webpack_require__(/*! ./config */ "./src/config.ts"));
const decryptDBUser_1 = __webpack_require__(/*! ./contracts/security/decryptDBUser */ "./src/contracts/security/decryptDBUser.ts");
const Site_1 = __webpack_require__(/*! ./entity/Site */ "./src/entity/Site.ts");
const Push_1 = __webpack_require__(/*! ./entity/Push */ "./src/entity/Push.ts");
const PushError_1 = __webpack_require__(/*! ./entity/PushError */ "./src/entity/PushError.ts");
const DeviceMapping_1 = __webpack_require__(/*! ./entity/DeviceMapping */ "./src/entity/DeviceMapping.ts");
const AuditRecord_1 = __webpack_require__(/*! ./entity/AuditRecord */ "./src/entity/AuditRecord.ts");
const AccTrans_1 = __webpack_require__(/*! ./entity/AccTrans */ "./src/entity/AccTrans.ts");
const AccObject_1 = __webpack_require__(/*! ./entity/AccObject */ "./src/entity/AccObject.ts");
const helper_1 = __webpack_require__(/*! ./common/helper */ "./src/common/helper.ts");
const logger_1 = __importDefault(__webpack_require__(/*! ./common/logger */ "./src/common/logger.ts"));
exports.connection = null;
function createDatabaseConnection(username, password, params) {
    return typeorm_1.createConnection({
        ...params,
        type: config_1.default.DB_TYPE,
        host: config_1.default.DB_HOST,
        port: config_1.default.DB_PORT,
        username,
        password,
        synchronize: false,
        debug: global.process.env.DEBUG_SQL === '1',
        logging: global.process.env.DEBUG_SQL === '1',
        entities: [
            Site_1.ConnectorSite,
            Push_1.Push,
            PushError_1.PushError,
            DeviceMapping_1.DeviceMapping,
            AuditRecord_1.AuditRecord,
            AccTrans_1.AccTrans,
            AccObject_1.AccObject,
        ],
        options: {
            encrypt: global.process.env.DISABLE_MSSQL_CONNECTION_ENCRYPTION !== 'true',
        },
    });
}
async function initDb() {
    const { username, password } = await decryptDBUser_1.decryptDBUser();
    const params = config_1.default.DB_TYPE === 'mssql'
        ? { database: config_1.default.DB_DATABASE_NAME }
        : { sid: config_1.default.DB_DATABASE_NAME };
    exports.connection = await createDatabaseConnection(username, password, params);
    if (config_1.default.DB_TYPE === 'mssql') {
        const orgDbName = await helper_1.getMsSqlDatabaseName(exports.connection);
        if (orgDbName !== config_1.default.DB_DATABASE_NAME) {
            logger_1.default.info(`Provided database name (${config_1.default.DB_DATABASE_NAME}) ` +
                `is not case sensitive equal to the actual database name ` +
                `(${orgDbName}). Using the actual name to connect to the database.`);
            await exports.connection.close();
            exports.connection = await createDatabaseConnection(username, password, {
                database: orgDbName,
            });
        }
    }
    await exports.connection.synchronize();
}
exports.initDb = initDb;


/***/ }),

/***/ "./src/entity/AccObject.ts":
/*!*********************************!*\
  !*** ./src/entity/AccObject.ts ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __decorate = (this && this.__decorate) || function (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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
let AccObject = class AccObject {
};
__decorate([
    typeorm_1.PrimaryColumn({ name: 'ACCTRANS_OBJECTID' }),
    __metadata("design:type", Number)
], AccObject.prototype, "id", void 0);
__decorate([
    typeorm_1.Column({ name: 'NAME', nullable: true }),
    __metadata("design:type", String)
], AccObject.prototype, "name", void 0);
__decorate([
    typeorm_1.Column({ name: 'OLDNAME', nullable: true }),
    __metadata("design:type", String)
], AccObject.prototype, "oldName", void 0);
AccObject = __decorate([
    typeorm_1.Entity({ name: 'ACCTRANS_OBJECT', synchronize: false })
], AccObject);
exports.AccObject = AccObject;


/***/ }),

/***/ "./src/entity/AccTrans.ts":
/*!********************************!*\
  !*** ./src/entity/AccTrans.ts ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __decorate = (this && this.__decorate) || function (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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
let AccTrans = class AccTrans {
};
__decorate([
    typeorm_1.PrimaryColumn({ name: 'ACCROWID', generated: 'increment' }),
    __metadata("design:type", Number)
], AccTrans.prototype, "id", void 0);
__decorate([
    typeorm_1.Column({ name: 'USERID', nullable: true }),
    __metadata("design:type", Number)
], AccTrans.prototype, "userId", void 0);
__decorate([
    typeorm_1.Column({ name: 'ACCTRANS_OPERATIONID' }),
    __metadata("design:type", Number)
], AccTrans.prototype, "operationId", void 0);
__decorate([
    typeorm_1.Column({ name: 'ACCTRANS_OBJECTID' }),
    __metadata("design:type", Number)
], AccTrans.prototype, "objectId", void 0);
__decorate([
    typeorm_1.Column({ name: 'ENTERVALUE', nullable: true }),
    __metadata("design:type", String)
], AccTrans.prototype, "enterValue", void 0);
__decorate([
    typeorm_1.Column({ name: 'ACCDATE', nullable: true }),
    __metadata("design:type", typeof (_a = typeof Date !== "undefined" && Date) === "function" ? _a : Object)
], AccTrans.prototype, "date", void 0);
__decorate([
    typeorm_1.Column({ name: 'COMPUTERN', nullable: true }),
    __metadata("design:type", String)
], AccTrans.prototype, "computerName", void 0);
__decorate([
    typeorm_1.Column({ name: 'LNL_DBID' }),
    __metadata("design:type", Number)
], AccTrans.prototype, "lnlDatabaseId", void 0);
__decorate([
    typeorm_1.Column({ name: 'USER_NOTES', nullable: true }),
    __metadata("design:type", String)
], AccTrans.prototype, "notes", void 0);
__decorate([
    typeorm_1.Column({ name: 'TIMESTAMP', nullable: true }),
    __metadata("design:type", typeof (_b = typeof Date !== "undefined" && Date) === "function" ? _b : Object)
], AccTrans.prototype, "timestamp", void 0);
__decorate([
    typeorm_1.Column({ name: 'APPLICATIONID', nullable: true }),
    __metadata("design:type", Number)
], AccTrans.prototype, "applicationId", void 0);
__decorate([
    typeorm_1.Column({ name: 'PERSIST_TYPEID' }),
    __metadata("design:type", Number)
], AccTrans.prototype, "persistTypeId", void 0);
__decorate([
    typeorm_1.Column({ name: 'REGION_ACCROWID', nullable: true }),
    __metadata("design:type", Number)
], AccTrans.prototype, "regionId", void 0);
__decorate([
    typeorm_1.Column({ name: 'UTC_OFFSET', nullable: true }),
    __metadata("design:type", Number)
], AccTrans.prototype, "utcOffset", void 0);
AccTrans = __decorate([
    typeorm_1.Entity({ name: 'ACCTRANS', synchronize: false })
], AccTrans);
exports.AccTrans = AccTrans;


/***/ }),

/***/ "./src/entity/AuditRecord.ts":
/*!***********************************!*\
  !*** ./src/entity/AuditRecord.ts ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __decorate = (this && this.__decorate) || function (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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const dbTypes_1 = __webpack_require__(/*! ../common/dbTypes */ "./src/common/dbTypes.ts");
let AuditRecord = class AuditRecord {
};
__decorate([
    typeorm_1.PrimaryColumn({ name: 'UCA_ID', generated: 'increment' }),
    __metadata("design:type", Number)
], AuditRecord.prototype, "id", void 0);
__decorate([
    typeorm_1.Column({ name: 'TIMESTAMP' }),
    __metadata("design:type", typeof (_a = typeof Date !== "undefined" && Date) === "function" ? _a : Object)
], AuditRecord.prototype, "timestamp", void 0);
__decorate([
    typeorm_1.Column({ name: 'USER_ID', nullable: true }),
    __metadata("design:type", String)
], AuditRecord.prototype, "userId", void 0);
__decorate([
    typeorm_1.Column({ name: 'EVENT_TYPE' }),
    __metadata("design:type", String)
], AuditRecord.prototype, "eventType", void 0);
__decorate([
    typeorm_1.Column({ name: 'CONNECTOR_SITEID' }),
    __metadata("design:type", Number)
], AuditRecord.prototype, "siteId", void 0);
__decorate([
    typeorm_1.Column({ name: 'LOGICAL_SOURCE_ID' }),
    __metadata("design:type", Number)
], AuditRecord.prototype, "logicalSourceId", void 0);
__decorate([
    typeorm_1.Column({ name: 'API_KEY', nullable: true, length: 1024 }),
    __metadata("design:type", String)
], AuditRecord.prototype, "apiKey", void 0);
__decorate([
    typeorm_1.Column({ name: 'CUSTOMER_ID' }),
    __metadata("design:type", String)
], AuditRecord.prototype, "customerId", void 0);
__decorate([
    typeorm_1.Column({
        name: 'CREDENTIAL_FILTER',
        nullable: true,
        ...dbTypes_1.NVARCHAR_MAX,
    }),
    __metadata("design:type", String)
], AuditRecord.prototype, "filter", void 0);
AuditRecord = __decorate([
    typeorm_1.Entity({ name: helper_1.getTableName('UDO_CONNECTOR_AUDIT') })
], AuditRecord);
exports.AuditRecord = AuditRecord;


/***/ }),

/***/ "./src/entity/DeviceMapping.ts":
/*!*************************************!*\
  !*** ./src/entity/DeviceMapping.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __decorate = (this && this.__decorate) || function (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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
const Site_1 = __webpack_require__(/*! ./Site */ "./src/entity/Site.ts");
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
let DeviceMapping = class DeviceMapping {
};
__decorate([
    typeorm_1.PrimaryColumn({ name: 'UCDM_ID', generated: 'increment' }),
    __metadata("design:type", Number)
], DeviceMapping.prototype, "id", void 0);
__decorate([
    typeorm_1.JoinColumn({ name: 'SITE_ID' }),
    typeorm_1.ManyToOne(() => Site_1.ConnectorSite, site => site.id, {
        cascade: true,
        lazy: true,
        nullable: false,
        onDelete: 'CASCADE',
    }),
    __metadata("design:type", typeof (_a = typeof Site_1.ConnectorSite !== "undefined" && Site_1.ConnectorSite) === "function" ? _a : Object)
], DeviceMapping.prototype, "site", void 0);
__decorate([
    typeorm_1.Column({ name: 'ON_GUARD_ID' }),
    __metadata("design:type", Number)
], DeviceMapping.prototype, "onGuardId", void 0);
__decorate([
    typeorm_1.Column({ name: 'ELEMENTS_ID' }),
    __metadata("design:type", String)
], DeviceMapping.prototype, "elementsId", void 0);
__decorate([
    typeorm_1.Column({ name: 'ELEMENTS_NAME' }),
    __metadata("design:type", String)
], DeviceMapping.prototype, "elementsName", void 0);
__decorate([
    typeorm_1.Column({ name: 'LAST_EVENT', nullable: true }),
    __metadata("design:type", String)
], DeviceMapping.prototype, "lastEvent", void 0);
DeviceMapping = __decorate([
    typeorm_1.Entity({ name: helper_1.getTableName('UDO_CONNECTOR_DEVICE_MAPPING') })
], DeviceMapping);
exports.DeviceMapping = DeviceMapping;


/***/ }),

/***/ "./src/entity/Push.ts":
/*!****************************!*\
  !*** ./src/entity/Push.ts ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __decorate = (this && this.__decorate) || function (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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var _a, _b, _c, _d, _e;
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
const Site_1 = __webpack_require__(/*! ./Site */ "./src/entity/Site.ts");
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const connector_1 = __webpack_require__(/*! types/connector */ "../../packages/types/connector.ts");
const dbTypes_1 = __webpack_require__(/*! ../common/dbTypes */ "./src/common/dbTypes.ts");
let Push = class Push {
};
__decorate([
    typeorm_1.PrimaryColumn({ name: 'UCP_ID', generated: 'increment' }),
    __metadata("design:type", Number)
], Push.prototype, "id", void 0);
__decorate([
    typeorm_1.JoinColumn({ name: 'SITE_ID' }),
    typeorm_1.ManyToOne(() => Site_1.ConnectorSite, site => site.id, {
        cascade: true,
        lazy: true,
        nullable: false,
        onDelete: 'CASCADE',
    }),
    __metadata("design:type", typeof (_a = typeof Site_1.ConnectorSite !== "undefined" && Site_1.ConnectorSite) === "function" ? _a : Object)
], Push.prototype, "site", void 0);
__decorate([
    typeorm_1.Column({ name: 'STARTED', nullable: true }),
    __metadata("design:type", typeof (_b = typeof Date !== "undefined" && Date) === "function" ? _b : Object)
], Push.prototype, "started", void 0);
__decorate([
    typeorm_1.Column({
        name: 'STATUS',
        ...dbTypes_1.NVARCHAR,
    }),
    __metadata("design:type", typeof (_c = typeof connector_1.PushStatus !== "undefined" && connector_1.PushStatus) === "function" ? _c : Object)
], Push.prototype, "status", void 0);
__decorate([
    typeorm_1.Column({ name: 'COMPLETED', nullable: true }),
    __metadata("design:type", typeof (_d = typeof Date !== "undefined" && Date) === "function" ? _d : Object)
], Push.prototype, "completed", void 0);
__decorate([
    typeorm_1.Column({ name: 'ERROR_COUNT', nullable: true }),
    __metadata("design:type", Number)
], Push.prototype, "errorCount", void 0);
__decorate([
    typeorm_1.Column({ name: 'CARDHOLDER_COUNT', nullable: true }),
    __metadata("design:type", Number)
], Push.prototype, "cardholderCount", void 0);
__decorate([
    typeorm_1.Column({ name: 'BADGE_COUNT', nullable: true }),
    __metadata("design:type", Number)
], Push.prototype, "badgeCount", void 0);
__decorate([
    typeorm_1.Column({ name: 'IS_AUTO', nullable: true }),
    __metadata("design:type", Boolean)
], Push.prototype, "isAuto", void 0);
__decorate([
    typeorm_1.Column({ name: 'AUTO_SCHEDULED_DATE', nullable: true }),
    __metadata("design:type", typeof (_e = typeof Date !== "undefined" && Date) === "function" ? _e : Object)
], Push.prototype, "autoScheduledDate", void 0);
Push = __decorate([
    typeorm_1.Entity({ name: helper_1.getTableName('UDO_CONNECTOR_PUSH') })
], Push);
exports.Push = Push;


/***/ }),

/***/ "./src/entity/PushError.ts":
/*!*********************************!*\
  !*** ./src/entity/PushError.ts ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __decorate = (this && this.__decorate) || function (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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const Push_1 = __webpack_require__(/*! ./Push */ "./src/entity/Push.ts");
let PushError = class PushError {
};
__decorate([
    typeorm_1.PrimaryColumn({ name: 'UCPE_ID', generated: 'increment' }),
    __metadata("design:type", Number)
], PushError.prototype, "id", void 0);
__decorate([
    typeorm_1.JoinColumn({ name: 'PUSH_ID' }),
    typeorm_1.ManyToOne(() => Push_1.Push, push => push.id, {
        cascade: true,
        lazy: true,
        nullable: false,
        onDelete: 'CASCADE',
    }),
    __metadata("design:type", typeof (_a = typeof Push_1.Push !== "undefined" && Push_1.Push) === "function" ? _a : Object)
], PushError.prototype, "push", void 0);
__decorate([
    typeorm_1.Column({ name: 'I18N_KEY' }),
    __metadata("design:type", String)
], PushError.prototype, "i18nKey", void 0);
__decorate([
    typeorm_1.Column({ name: 'I18N_PARAMS', length: '2000' }),
    __metadata("design:type", String)
], PushError.prototype, "i18nParams", void 0);
__decorate([
    typeorm_1.Column({ name: 'CARDHOLDER_ID', nullable: true }),
    __metadata("design:type", Number)
], PushError.prototype, "cardholderId", void 0);
__decorate([
    typeorm_1.Column({ name: 'BADGE_ID', nullable: true }),
    __metadata("design:type", String)
], PushError.prototype, "badgeId", void 0);
PushError = __decorate([
    typeorm_1.Entity({ name: helper_1.getTableName('UDO_CONNECTOR_PUSH_ERROR') })
], PushError);
exports.PushError = PushError;


/***/ }),

/***/ "./src/entity/Site.ts":
/*!****************************!*\
  !*** ./src/entity/Site.ts ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __decorate = (this && this.__decorate) || function (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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const dbTypes_1 = __webpack_require__(/*! ../common/dbTypes */ "./src/common/dbTypes.ts");
let ConnectorSite = class ConnectorSite {
};
__decorate([
    typeorm_1.PrimaryColumn({ name: 'UCS_ID', generated: 'increment' }),
    __metadata("design:type", Number)
], ConnectorSite.prototype, "id", void 0);
__decorate([
    typeorm_1.Column({ name: 'LOGICAL_SOURCE_ID', unique: true }),
    __metadata("design:type", Number)
], ConnectorSite.prototype, "logicalSourceId", void 0);
__decorate([
    typeorm_1.Column({ name: 'API_KEY', nullable: true, length: 1024 }),
    __metadata("design:type", String)
], ConnectorSite.prototype, "apiKey", void 0);
__decorate([
    typeorm_1.Column({ name: 'CLOUD_NAME' }),
    __metadata("design:type", String)
], ConnectorSite.prototype, "cloudName", void 0);
__decorate([
    typeorm_1.Column({ name: 'CUSTOMER_ID', unique: true }),
    __metadata("design:type", String)
], ConnectorSite.prototype, "customerId", void 0);
__decorate([
    typeorm_1.Column({ name: 'REMOVED_NOTIFICATION_DATE', nullable: true }),
    __metadata("design:type", String)
], ConnectorSite.prototype, "removedNotificationDate", void 0);
__decorate([
    typeorm_1.Column({ name: 'LAST_EVENT_PROCESSED_TIME', nullable: true }),
    __metadata("design:type", String)
], ConnectorSite.prototype, "lastEventProcessedTimestamp", void 0);
__decorate([
    typeorm_1.Column({
        name: 'FILTER',
        nullable: true,
        ...dbTypes_1.NVARCHAR_MAX,
    }),
    __metadata("design:type", String)
], ConnectorSite.prototype, "filter", void 0);
__decorate([
    typeorm_1.Column({ name: 'PEOPLE_LIMIT', default: 0, nullable: true }),
    __metadata("design:type", Number)
], ConnectorSite.prototype, "peopleLimit", void 0);
ConnectorSite = __decorate([
    typeorm_1.Entity({ name: helper_1.getTableName('UDO_CONNECTOR_SITE') })
], ConnectorSite);
exports.ConnectorSite = ConnectorSite;


/***/ }),

/***/ "./src/jobs/checkRemovedLogicalSourcesJob.ts":
/*!***************************************************!*\
  !*** ./src/jobs/checkRemovedLogicalSourcesJob.ts ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const wql_1 = __importDefault(__webpack_require__(/*! wql */ "../../packages/wql/src/index.ts"));
const DateFns = __importStar(__webpack_require__(/*! date-fns */ "date-fns"));
const logger_1 = __importDefault(__webpack_require__(/*! ../common/logger */ "./src/common/logger.ts"));
const db_1 = __webpack_require__(/*! ../db */ "./src/db.ts");
const Site_1 = __webpack_require__(/*! ../entity/Site */ "./src/entity/Site.ts");
const onGuardApi_1 = __webpack_require__(/*! ../onGuardApi */ "./src/onGuardApi.ts");
const lnl_1 = __webpack_require__(/*! types/lnl */ "../../packages/types/lnl.ts");
const Const_1 = __webpack_require__(/*! ../Const */ "./src/Const.ts");
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const dbHelper_1 = __webpack_require__(/*! ../common/dbHelper */ "./src/common/dbHelper.ts");
function getLogicalSourceRemovedMessage(siteName) {
    return ('Logical Source Not Found\r\n' +
        `The logical source for cloud site ${siteName} has been removed. ` +
        'Synchronization between OnGuard and the cloud site is broken. ' +
        'Open OnGuard Elements Connector to recreate the logical source.');
}
async function _run() {
    const dbSites = await db_1.connection.manager.find(Site_1.ConnectorSite);
    if (!dbSites.length) {
        return;
    }
    const sourceIds = R.map(dbSites, x => x.logicalSourceId);
    const logicalSources = await onGuardApi_1.api.getAllInstances({
        typeName: lnl_1.TypeName.Lnl_LogicalSource,
        filter: wql_1.default({
            ID: {
                $in: sourceIds,
            },
        }),
    });
    const map = R.indexBy(logicalSources, x => x.ID);
    await Promise.all(dbSites.map(async (site) => {
        try {
            if (map[site.logicalSourceId]) {
                return;
            }
            if (site.removedNotificationDate &&
                DateFns.isSameDay(new Date(site.removedNotificationDate), new Date())) {
                return;
            }
            const failed = await onGuardApi_1.api.sendIncomingEvents([
                {
                    ...Const_1.GENERIC_EVENT_PARAMS,
                    event_text: getLogicalSourceRemovedMessage(site.cloudName),
                },
            ]);
            if (failed.length) {
                throw new Error('Failed to sendIncomingEvents');
            }
            site.removedNotificationDate = new Date().toISOString();
            await dbHelper_1.updateEntity(site, ['removedNotificationDate']);
        }
        catch (e) {
            logger_1.default.error(`checkRemovedLogicalSourcesJob failed for site ${site.id}`, e);
        }
    }));
}
function checkRemovedLogicalSourcesJob() {
    helper_1.runJob(_run, '5m');
}
exports.checkRemovedLogicalSourcesJob = checkRemovedLogicalSourcesJob;


/***/ }),

/***/ "./src/jobs/eventsJob.ts":
/*!*******************************!*\
  !*** ./src/jobs/eventsJob.ts ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const wql_1 = __importDefault(__webpack_require__(/*! wql */ "../../packages/wql/src/index.ts"));
const ms_1 = __importDefault(__webpack_require__(/*! ms */ "ms"));
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const dbHelper_1 = __webpack_require__(/*! ../common/dbHelper */ "./src/common/dbHelper.ts");
const db_1 = __webpack_require__(/*! ../db */ "./src/db.ts");
const Site_1 = __webpack_require__(/*! ../entity/Site */ "./src/entity/Site.ts");
const config_1 = __importDefault(__webpack_require__(/*! ../config */ "./src/config.ts"));
const logger_1 = __importDefault(__webpack_require__(/*! ../common/logger */ "./src/common/logger.ts"));
const onGuardApi_1 = __webpack_require__(/*! ../onGuardApi */ "./src/onGuardApi.ts");
const lnl_1 = __webpack_require__(/*! types/lnl */ "../../packages/types/lnl.ts");
const DeviceMapping_1 = __webpack_require__(/*! ../entity/DeviceMapping */ "./src/entity/DeviceMapping.ts");
const getUniqName_1 = __webpack_require__(/*! ../common/getUniqName */ "./src/common/getUniqName.ts");
const elementsApiCache_1 = __webpack_require__(/*! ../common/elementsApiCache */ "./src/common/elementsApiCache.ts");
const _deviceCache = {};
const _eventMapCache = {};
function _getDevice(site, device) {
    if (!device) {
        return null;
    }
    const key = `${site.id}-${device.id}`;
    const createLogicalDevice = async () => {
        const name = await getUniqName_1.getUniqName(lnl_1.TypeName.Lnl_LogicalDevice, device.name);
        const ret = await onGuardApi_1.api.addInstance(lnl_1.TypeName.Lnl_LogicalDevice, {
            SourceID: site.logicalSourceId,
            Name: name,
        });
        ret.Name = name;
        return ret;
    };
    if (!_deviceCache[key]) {
        _deviceCache[key] = Promise.resolve()
            .then(async () => {
            const deviceMapping = await db_1.connection.manager.findOne(DeviceMapping_1.DeviceMapping, {
                site,
                elementsId: device.id,
            });
            if (!deviceMapping) {
                const logicalDevice = await createLogicalDevice();
                const newMapping = new DeviceMapping_1.DeviceMapping();
                newMapping.site = site;
                newMapping.elementsId = device.id;
                newMapping.onGuardId = logicalDevice.ID;
                newMapping.elementsName = device.name;
                await db_1.connection.manager.insert(DeviceMapping_1.DeviceMapping, newMapping);
                return { logicalDevice, deviceMapping: newMapping };
            }
            else {
                let logicalDevice = await onGuardApi_1.api.getSingleInstances({
                    allowEmpty: true,
                    typeName: lnl_1.TypeName.Lnl_LogicalDevice,
                    filter: wql_1.default({
                        ID: deviceMapping.onGuardId,
                    }),
                });
                if (!logicalDevice) {
                    logicalDevice = await createLogicalDevice();
                    deviceMapping.onGuardId = logicalDevice.ID;
                    deviceMapping.elementsName = logicalDevice.Name;
                    await dbHelper_1.updateEntity(deviceMapping, ['onGuardId', 'elementsName']);
                }
                if (deviceMapping.elementsName !== device.name) {
                    logicalDevice.Name = await getUniqName_1.getUniqName(lnl_1.TypeName.Lnl_LogicalDevice, device.name);
                    await onGuardApi_1.api.modifyInstance(lnl_1.TypeName.Lnl_LogicalDevice, logicalDevice);
                    deviceMapping.elementsName = logicalDevice.Name;
                    await dbHelper_1.updateEntity(deviceMapping, ['elementsName']);
                }
                return { logicalDevice, deviceMapping };
            }
        })
            .then(ret => {
            setTimeout(() => {
                delete _deviceCache[key];
            }, ms_1.default('10m'));
            return ret;
        })
            .catch(e => {
            // don't cache errors
            delete _deviceCache[key];
            throw e;
        });
    }
    return _deviceCache[key];
}
function _getEventMapCache(site, elementsAPI) {
    if (!_eventMapCache[site.id]) {
        _eventMapCache[site.id] = Promise.resolve()
            .then(() => elementsAPI.getEventTypeMap())
            .then(ret => {
            setTimeout(() => {
                delete _eventMapCache[site.id];
            }, ms_1.default('24h'));
            return ret;
        })
            .catch(e => {
            // don't cache errors
            delete _eventMapCache[site.id];
            throw e;
        });
    }
    return _eventMapCache[site.id];
}
async function _sendSingleEvent(site, event) {
    const MAX_RETRY_ATTEMPTS = 5;
    for (let i = 1; i <= MAX_RETRY_ATTEMPTS; i++) {
        try {
            const failedEvents = await onGuardApi_1.api.sendIncomingEvents([event]);
            if (failedEvents.length === 0) {
                return;
            }
        }
        catch (e) {
            // ignore
        }
        logger_1.default.info(`Failed to send event for site ${helper_1.getSiteLogEntry(site)} (attempt ${i}/${MAX_RETRY_ATTEMPTS})`);
    }
    logger_1.default.error(`Failed to send event for site ${helper_1.getSiteLogEntry(site)} - reporting error`, event);
    await onGuardApi_1.api.sendIncomingEvents([
        {
            event_type: 30,
            event_id: 0,
            source_id: site.logicalSourceId,
            event_text: `Failed to inject event from a Cloud Site\r\n` +
                `Site name: ${site.cloudName}\r\n` +
                `Logical Source ID: ${event.source_id}\r\n` +
                `Logical Device ID: ${event.device_id}\r\n` +
                `Event time: ${new Date(event.time).toISOString()}\r\n` +
                `Event type: ${event.event_type}\r\n` +
                `Event subtype: ${event.event_id}\r\n` +
                `Badge ID: ${event.badge_id}\r\n` +
                `Event text: ${event.event_text}\r\n\r\n` +
                `Refer to OnGuard Elements Connector logs for more details.`,
        },
    ]);
}
function _mapElementsEvent(site, eventMap, { event, device }) {
    const defaultType = { type: 30, subtype: 0 };
    const { type, subtype } = device
        ? eventMap.map[event.eventType] || defaultType
        : defaultType;
    function getBadgeParameter() {
        if (!event.credential || !event.credential.badgeId) {
            return {};
        }
        return config_1.default.USE_SHORT_ONGUARD_BADGE_ID
            ? { badge_id: +event.credential.badgeId }
            : { badge_id_str: event.credential.badgeId };
    }
    return {
        event_type: type,
        event_id: subtype,
        source_id: site.logicalSourceId,
        device_id: device ? device.logicalDevice.ID : 0,
        event_text: `${event.eventTypeLocalized}\r\n` +
            `${event.eventDescriptionLocalized}`,
        time: event.timestamp,
        ...getBadgeParameter(),
    };
}
async function _updateDeviceLastEvent(eventData) {
    eventData.sort((a, b) => new Date(b.event.timestamp).getTime() -
        new Date(a.event.timestamp).getTime());
    const deviceGroups = R.groupBy(eventData.filter(x => x.device), x => x.device.deviceMapping.id);
    await Promise.all(Object.values(deviceGroups).map(group => {
        const { event, device: { deviceMapping }, } = group[0];
        deviceMapping.lastEvent = event.timestamp;
        return dbHelper_1.updateEntity(deviceMapping, ['lastEvent']);
    }));
}
function _toISODate(date) {
    return new Date(date).toISOString();
}
async function _run() {
    const dbSites = await db_1.connection.manager.find(Site_1.ConnectorSite);
    if (!dbSites.length) {
        return;
    }
    await Promise.all(dbSites.map(async (site) => {
        try {
            const elementsAPI = await elementsApiCache_1.getCachedElementsApi(site.apiKey);
            // Unable to authorize to Elements or removed logical source
            if (!elementsAPI || site.removedNotificationDate) {
                return;
            }
            const eventsMap = await _getEventMapCache(site, elementsAPI);
            const processNextPage = async (lastEventProcessedTimestamp, after) => {
                const result = await elementsAPI.searchEvents({
                    sortBy: 'eventProcessedTimestamp',
                    sortDirection: 1,
                    after,
                    top: 100,
                    filter: lastEventProcessedTimestamp
                        ? `eventProcessedTimestamp gt ${lastEventProcessedTimestamp}`
                        : undefined,
                });
                if (!result.data.length) {
                    return;
                }
                const eventData = [];
                for (const event of result.data) {
                    eventData.push({
                        event,
                        device: await _getDevice(site, event.device),
                    });
                }
                for (const item of eventData) {
                    const mappedEvent = _mapElementsEvent(site, eventsMap, item);
                    await _sendSingleEvent(site, mappedEvent);
                }
                site.lastEventProcessedTimestamp = _toISODate(R.last(result.data).eventProcessedTimestamp);
                await dbHelper_1.updateEntity(site, ['lastEventProcessedTimestamp']);
                await _updateDeviceLastEvent(eventData);
                if (result.after) {
                    await processNextPage(lastEventProcessedTimestamp, result.after);
                }
            };
            await processNextPage(site.lastEventProcessedTimestamp, '');
        }
        catch (e) {
            logger_1.default.error(`Failed to synchronize events for site ${helper_1.getSiteLogEntry(site)}`, e);
        }
    }));
}
function eventsJob() {
    helper_1.runJob(_run, '10s');
}
exports.eventsJob = eventsJob;


/***/ }),

/***/ "./src/jobs/pushJob.ts":
/*!*****************************!*\
  !*** ./src/jobs/pushJob.ts ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const db_1 = __webpack_require__(/*! ../db */ "./src/db.ts");
const Site_1 = __webpack_require__(/*! ../entity/Site */ "./src/entity/Site.ts");
const config_1 = __importDefault(__webpack_require__(/*! ../config */ "./src/config.ts"));
const sync_1 = __webpack_require__(/*! ../contracts/site/sync */ "./src/contracts/site/sync.ts");
const Push_1 = __webpack_require__(/*! ../entity/Push */ "./src/entity/Push.ts");
const getScheduledDate_1 = __webpack_require__(/*! ../sync/getScheduledDate */ "./src/sync/getScheduledDate.ts");
const ErrorHandler_1 = __webpack_require__(/*! ../sync/ErrorHandler */ "./src/sync/ErrorHandler.ts");
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const typeorm_1 = __webpack_require__(/*! typeorm */ "typeorm");
async function _processSite(id) {
    const site = await db_1.connection.manager.findOne(Site_1.ConnectorSite, id);
    // site deleted or not configured
    if (!site || !site.apiKey || !site.filter) {
        return;
    }
    const [lastPush] = await db_1.connection.manager.find(Push_1.Push, {
        where: {
            site,
        },
        order: {
            id: 'DESC',
        },
        take: 1,
    });
    const pushCount = await db_1.connection.manager.count(Push_1.Push, {
        where: {
            status: typeorm_1.In(['pending', 'queued']),
        },
        order: { id: 'DESC' },
    });
    if (pushCount) {
        return;
    }
    const pushTime = getScheduledDate_1.getScheduledDate(lastPush, false);
    if (pushTime) {
        await sync_1.syncAuto(id, pushTime);
    }
}
async function _run() {
    const sites = await db_1.connection.manager.find(Site_1.ConnectorSite);
    for (const site of sites) {
        try {
            await _processSite(site.id);
        }
        catch (e) {
            const errorHandler = new ErrorHandler_1.ErrorHandler(site);
            errorHandler.reportError(e, 'sync_failed', {});
        }
    }
}
function pushJob() {
    if (![0, 1, 2, 3, 4, 6, 8, 12, 24].includes(config_1.default.CARDHOLDER_PUSH_RUNS_DAILY)) {
        throw new Error('CARDHOLDER_PUSH_RUNS_DAILY is invalid. Allowed values: [0, 1, 2, 3, 4, 6, 8, 12, 24].');
    }
    if (config_1.default.CARDHOLDER_PUSH_FIRST_RUN_HOUR < 0 ||
        config_1.default.CARDHOLDER_PUSH_FIRST_RUN_HOUR >= 24) {
        throw new Error('CARDHOLDER_PUSH_FIRST_RUN_HOUR is invalid. Must be greater or equal to 0 and less than 24.');
    }
    if (!config_1.default.CARDHOLDER_PUSH_RUNS_DAILY) {
        return;
    }
    helper_1.runJob(_run, '1m');
}
exports.pushJob = pushJob;


/***/ }),

/***/ "./src/jobs/syncJob.ts":
/*!*****************************!*\
  !*** ./src/jobs/syncJob.ts ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const wql_1 = __importDefault(__webpack_require__(/*! wql */ "../../packages/wql/src/index.ts"));
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const dbHelper_1 = __webpack_require__(/*! ../common/dbHelper */ "./src/common/dbHelper.ts");
const db_1 = __webpack_require__(/*! ../db */ "./src/db.ts");
const SyncStatus_1 = __webpack_require__(/*! ../sync/SyncStatus */ "./src/sync/SyncStatus.ts");
const Push_1 = __webpack_require__(/*! ../entity/Push */ "./src/entity/Push.ts");
const ErrorHandler_1 = __webpack_require__(/*! ../sync/ErrorHandler */ "./src/sync/ErrorHandler.ts");
const _initElements_1 = __webpack_require__(/*! ../contracts/site/_initElements */ "./src/contracts/site/_initElements.ts");
const getOnGuardData_1 = __webpack_require__(/*! ../sync/getOnGuardData */ "./src/sync/getOnGuardData.ts");
const Const_1 = __webpack_require__(/*! ../Const */ "./src/Const.ts");
const getSyncDiff_1 = __webpack_require__(/*! ../sync/getSyncDiff */ "./src/sync/getSyncDiff.ts");
const removeCardholders_1 = __webpack_require__(/*! ../sync/process/removeCardholders */ "./src/sync/process/removeCardholders.ts");
const updateCardholders_1 = __webpack_require__(/*! ../sync/process/updateCardholders */ "./src/sync/process/updateCardholders.ts");
const removeBadges_1 = __webpack_require__(/*! ../sync/process/removeBadges */ "./src/sync/process/removeBadges.ts");
const addBadges_1 = __webpack_require__(/*! ../sync/process/addBadges */ "./src/sync/process/addBadges.ts");
const IncrementalPhotoSync_1 = __webpack_require__(/*! ../sync/IncrementalPhotoSync */ "./src/sync/IncrementalPhotoSync.ts");
const addPhotos_1 = __webpack_require__(/*! ../sync/process/addPhotos */ "./src/sync/process/addPhotos.ts");
const updatePhotos_1 = __webpack_require__(/*! ../sync/process/updatePhotos */ "./src/sync/process/updatePhotos.ts");
const removePhotos_1 = __webpack_require__(/*! ../sync/process/removePhotos */ "./src/sync/process/removePhotos.ts");
const logger_1 = __importDefault(__webpack_require__(/*! ../common/logger */ "./src/common/logger.ts"));
const PushError_1 = __webpack_require__(/*! ../entity/PushError */ "./src/entity/PushError.ts");
const onGuardApi_1 = __webpack_require__(/*! ../onGuardApi */ "./src/onGuardApi.ts");
const lnl_1 = __webpack_require__(/*! types/lnl */ "../../packages/types/lnl.ts");
let _syncInfo = null;
function getSyncInfo() {
    return _syncInfo;
}
exports.getSyncInfo = getSyncInfo;
function _cancelablePromise(fn, cancel$) {
    return Rx.defer(() => fn)
        .pipe(Rx.takeUntil(cancel$))
        .toPromise();
}
async function _processSync(info, errorHandler) {
    const { site: dbSite, cancel$ } = info;
    const hasConnection = await _cancelablePromise(onGuardApi_1.api
        .getVersion()
        .then(() => true)
        .catch(() => false), cancel$);
    if (!hasConnection) {
        errorHandler.reportError(null, 'cannot_connect_to_onguard', {});
        return;
    }
    if (info.isCanceled) {
        return;
    }
    const initialData = await _cancelablePromise(Promise.all([
        await onGuardApi_1.api.getSingleInstances({
            typeName: lnl_1.TypeName.Lnl_LogicalSource,
            filter: wql_1.default({
                ID: dbSite.logicalSourceId,
            }),
            allowEmpty: true,
        }),
        _initElements_1._initElements(dbSite.apiKey),
    ]), cancel$);
    if (info.isCanceled) {
        return;
    }
    const [logicalSource, { elementsAPI, customer }] = initialData;
    if (!logicalSource) {
        errorHandler.reportError(null, 'logical_source_deleted', {});
        return;
    }
    let filter = null;
    try {
        filter = JSON.parse(dbSite.filter);
    }
    catch (e) {
        throw new Error('Cannot parse filter');
    }
    const cardholderLimit = customer.externallyManagedPeopleLimit || Const_1.DEFAULT_CARDHOLDER_LIMIT;
    const apiData = await _cancelablePromise(Promise.all([
        getOnGuardData_1.getOnGuardData(cardholderLimit, logicalSource.SegmentID, filter),
        elementsAPI.getAllPeople(),
    ]), cancel$);
    if (info.isCanceled) {
        return;
    }
    const [onGuardData, persons] = apiData;
    if (onGuardData.isLimitExceeded) {
        errorHandler.reportError(null, 'cardholder_limit_exceeded', {
            count: cardholderLimit,
        });
    }
    const diff = getSyncDiff_1.getSyncDiff(onGuardData, persons);
    info.push.cardholderCount = onGuardData.cardholders.length;
    info.push.badgeCount = onGuardData.badges.length;
    const options = { cancel$, elementsAPI, errorHandler, dbSite };
    await removeCardholders_1.removeCardholders(diff.removeCardholders, options);
    await updateCardholders_1.updateCardholders(diff.updateCardholders, options);
    await removeBadges_1.removeBadges(diff.removeBadges, options);
    await addBadges_1.addBadges(diff.addBadges, options);
    const incPhotoSync = new IncrementalPhotoSync_1.IncrementalPhotoSync(persons, diff.keepPhotos);
    const checkPhotoChunks = R.chunk(diff.checkPhotoCardholders, 10);
    const processPhotoDiff = async (photoDiff) => {
        await addPhotos_1.addPhotos(photoDiff.addPhotos, options);
        await updatePhotos_1.updatePhotos(photoDiff.updatePhotos, options);
        await removePhotos_1.removePhotos(photoDiff.removePhotos, options);
    };
    for (const cardholders of checkPhotoChunks) {
        const images = await _cancelablePromise(getOnGuardData_1.getOnGuardImagesData(cardholders), cancel$);
        if (info.isCanceled) {
            return;
        }
        await processPhotoDiff(incPhotoSync.process(images, cardholders));
    }
    await processPhotoDiff(incPhotoSync.finalize());
    // Simulate long running sync
    // await Rx.of(null)
    //   .pipe(
    //     Rx.delay(20000),
    //     Rx.takeUntil(cancel$)
    //   )
    //   .toPromise();
    if (info.errorCount) {
        logger_1.default.error(`Sync for ${dbSite.id} finished with errors`);
    }
}
function _getPush(status) {
    return db_1.connection.manager.findOne(Push_1.Push, {
        where: {
            status,
        },
        order: { id: 'DESC' },
    });
}
async function _cancelPending() {
    const push = await _getPush('pending');
    if (!push) {
        return;
    }
    const pushError = new PushError_1.PushError();
    pushError.push = push;
    pushError.i18nKey = 'push_interrupted';
    pushError.i18nParams = JSON.stringify({});
    await db_1.connection.manager.insert(PushError_1.PushError, pushError);
    push.completed = new Date();
    push.status = 'error';
    push.errorCount = await db_1.connection.manager.count(PushError_1.PushError, {
        where: {
            push,
        },
    });
    await dbHelper_1.updateEntity(push, ['completed', 'status', 'errorCount']);
}
async function _run() {
    const [push] = await Promise.all([_getPush('queued'), _cancelPending()]);
    if (!push) {
        return;
    }
    const site = await push.site;
    push.status = 'pending';
    push.started = new Date();
    await dbHelper_1.updateEntity(push, ['status', 'started']);
    _syncInfo = new SyncStatus_1.SyncInfo(site, push);
    const errorHandler = new ErrorHandler_1.ErrorHandler(site, _syncInfo);
    try {
        await _processSync(_syncInfo, errorHandler);
        push.status = _syncInfo.isCanceled
            ? 'canceled'
            : _syncInfo.errorCount
                ? 'error'
                : 'completed';
    }
    catch (e) {
        errorHandler.reportError(e, 'sync_failed', {});
        push.status = 'error';
    }
    finally {
        push.errorCount = _syncInfo.errorCount;
        push.completed = new Date();
        await dbHelper_1.updateEntity(push, [
            'status',
            'errorCount',
            'completed',
            'cardholderCount',
            'badgeCount',
        ]);
    }
    _syncInfo.completed$.complete();
    _syncInfo = null;
}
function syncJob() {
    helper_1.runJob(_run, '3s');
}
exports.syncJob = syncJob;


/***/ }),

/***/ "./src/onGuardApi.ts":
/*!***************************!*\
  !*** ./src/onGuardApi.ts ***!
  \***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = __importDefault(__webpack_require__(/*! ./config */ "./src/config.ts"));
const OpenAccessAPI_1 = __webpack_require__(/*! ./services/OpenAccessAPI */ "./src/services/OpenAccessAPI.ts");
const decryptAPIUser_1 = __webpack_require__(/*! ./contracts/security/decryptAPIUser */ "./src/contracts/security/decryptAPIUser.ts");
exports.api = new OpenAccessAPI_1.OpenAccessAPI({
    baseUrl: config_1.default.OPEN_ACCESS_API_BASE_URL,
    applicationId: config_1.default.APPLICATION_ID,
    getCredentials: decryptAPIUser_1.decryptAPIUser,
});


/***/ }),

/***/ "./src/services/ElementsAPI.ts":
/*!*************************************!*\
  !*** ./src/services/ElementsAPI.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const isomorphic_fetch_1 = __importDefault(__webpack_require__(/*! isomorphic-fetch */ "isomorphic-fetch"));
const ms_1 = __importDefault(__webpack_require__(/*! ms */ "ms"));
const url_1 = __importDefault(__webpack_require__(/*! url */ "url"));
const https_1 = __importDefault(__webpack_require__(/*! https */ "https"));
const proxy_agent_1 = __importDefault(__webpack_require__(/*! proxy-agent */ "proxy-agent"));
const logger_1 = __importStar(__webpack_require__(/*! ../common/logger */ "./src/common/logger.ts"));
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
const errors_1 = __webpack_require__(/*! ../common/errors */ "./src/common/errors.ts");
const url_2 = __webpack_require__(/*! utils/url */ "../../packages/utils/url.ts");
const config_1 = __importDefault(__webpack_require__(/*! ../config */ "./src/config.ts"));
const FetchRateLimiter_1 = __webpack_require__(/*! ../common/FetchRateLimiter */ "./src/common/FetchRateLimiter.ts");
// Using global.process.env so that webpack EnvironmentPlugin does not touch it
const proxyUrl = config_1.default.HTTPS_PROXY !== undefined
    ? config_1.default.HTTPS_PROXY
    : global.process.env.HTTPS_PROXY;
exports.extraHttpOptions = proxyUrl
    ? {
        agent: proxy_agent_1.default({
            ...url_1.default.parse(proxyUrl),
            keepAlive: true,
        }),
    }
    : {
        agent: new https_1.default.Agent({ keepAlive: true }),
    };
function _truncateBody(body) {
    if (!body) {
        return body;
    }
    if (body.photo) {
        return {
            ...body,
            photo: '<truncated>',
        };
    }
    return body;
}
function _getRandomWaitSeconds() {
    const min = 60;
    const max = 300;
    return Math.round(Math.random() * (max - min)) + min;
}
async function _waitRetryAfter(retryAfter) {
    const waitSeconds = retryAfter ? Number(retryAfter) : _getRandomWaitSeconds();
    await new Promise(resolve => setTimeout(resolve, waitSeconds * 1000));
}
class ElementsAPI {
    constructor(options) {
        this.options = options;
        this.apiKey = null;
        this.token = null;
        this.tokenCreatedAt = null;
        this.customerId = null;
        this.rateLimiter = new FetchRateLimiter_1.FetchRateLimiter(config_1.default.ELEMENTS_MAX_PARALLEL_REQUESTS, isomorphic_fetch_1.default);
    }
    async getResponseJSON(res) {
        const text = await res.text();
        try {
            return JSON.parse(text);
        }
        catch (e) {
            return { raw: text };
        }
    }
    async makeRequest(options) {
        if (Date.now() - this.tokenCreatedAt.getTime() > ms_1.default('30m')) {
            const originalTokenCreatedAt = this.tokenCreatedAt;
            try {
                // update tokenCreatedAt now to avoid multiple refreshes if there are parallel requests
                this.tokenCreatedAt = new Date();
                await this.authenticate(this.apiKey);
            }
            catch (e) {
                this.tokenCreatedAt = originalTokenCreatedAt;
                throw e;
            }
        }
        const fullUrl = `${options.baseUrl}/${options.url}`;
        const res = await this.rateLimiter.fetch(fullUrl, {
            method: options.method,
            body: options.body && JSON.stringify(options.body),
            headers: {
                'content-type': 'application/json',
                authorization: `Bearer ${this.token}`,
                'X-Active-Customer-ID': this.customerId ? this.customerId : undefined,
            },
            ...exports.extraHttpOptions,
        });
        const body = await this.getResponseJSON(res);
        logger_1.traceHttpRequest(logger_1.default, options.method, fullUrl, options.body, res.status, body);
        if (res.status === 429) {
            const retryHeader = res.headers.get('Retry-After');
            await _waitRetryAfter(retryHeader);
            return this.makeRequest(options);
        }
        if (!res.ok || body.errorMessage) {
            const error = body.raw ||
                body.errorMessage ||
                (body.errors ? JSON.stringify(body.errors) : 'Unknown error');
            logger_1.default.error('Elements API Error', {
                ...options,
                body: _truncateBody(options.body),
            }, {
                error,
                status: res.status,
            });
            throw new errors_1.ElementsError(error, body.errorCode || 'unknown', body.errors || []);
        }
        return body;
    }
    setCustomerId(customerId) {
        this.customerId = customerId;
    }
    async authenticate(apiKey) {
        const { url, payload } = helper_1.decodeApiKey(apiKey);
        const res = await this.rateLimiter.fetch(`${url}?${payload}`, {
            method: 'POST',
            headers: {
                'content-type': 'application/x-www-form-urlencoded',
            },
            ...exports.extraHttpOptions,
        });
        const body = await this.getResponseJSON(res);
        if (!res.ok || body.error) {
            logger_1.default.error('failed to fetch Elements token', body);
            throw new Error(body.error || body.raw);
        }
        this.apiKey = apiKey;
        this.token = body.access_token;
        this.tokenCreatedAt = new Date();
    }
    async getMyCustomers() {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'GET',
            url: '/v1/customers/my',
        });
    }
    async getPhoto(externalId) {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'GET',
            url: `/v1/photos/external/${externalId}`,
        });
    }
    async getAllPeople() {
        const ret = [];
        const processNextPage = async (after) => {
            const query = {
                $top: 100,
                after,
            };
            const result = await this.makeRequest({
                baseUrl: this.options.remoteManagementServiceBaseUrl,
                method: 'GET',
                url: `/v1/people/external${url_2.stringifyQueryString(query)}`,
            });
            ret.push(...result.data);
            if (result.after) {
                await processNextPage(result.after);
            }
        };
        await processNextPage(undefined);
        return ret;
    }
    async upsertPerson(externalId, values) {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'PUT',
            url: `/v1/people/external/${externalId}`,
            body: values,
        });
    }
    async deletePerson(externalId) {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'DELETE',
            url: `/v1/people/external/${externalId}`,
        });
    }
    async addPhoto(externalId, externallyUpdated, photo) {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'POST',
            url: `/v1/photos/external`,
            body: { externalId, externallyUpdated, photo },
        });
    }
    async updatePhoto(externalId, externallyUpdated, photo) {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'PUT',
            url: `/v1/photos/external/${externalId}`,
            body: { photo, externallyUpdated },
        });
    }
    async removePhoto(externalId) {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'DELETE',
            url: `/v1/photos/external/${externalId}`,
        });
    }
    async searchEvents(criteria) {
        const query = {
            $filter: criteria.filter,
            $top: criteria.top,
            $sortBy: criteria.sortBy,
            $sortDirection: criteria.sortDirection,
            after: criteria.after,
        };
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'GET',
            url: `/v1/events${url_2.stringifyQueryString(query)}`,
        });
    }
    async getEventTypeMap() {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'GET',
            url: `/v1/events/maps?eventMapType=onGuard`,
        });
    }
    async addBadge(externalPersonId, badgeId) {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'POST',
            url: `/v1/credentials/external`,
            body: { externalPersonId, badgeId },
        });
    }
    async removeBadge(badgeId) {
        return this.makeRequest({
            baseUrl: this.options.remoteManagementServiceBaseUrl,
            method: 'DELETE',
            url: `/v1/credentials/external/badge/${badgeId}`,
        });
    }
}
exports.ElementsAPI = ElementsAPI;


/***/ }),

/***/ "./src/services/OpenAccessAPI.ts":
/*!***************************************!*\
  !*** ./src/services/OpenAccessAPI.ts ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const isomorphic_fetch_1 = __importDefault(__webpack_require__(/*! isomorphic-fetch */ "isomorphic-fetch"));
const query_string_1 = __importDefault(__webpack_require__(/*! query-string */ "query-string"));
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const https_1 = __importDefault(__webpack_require__(/*! https */ "https"));
const utils_1 = __webpack_require__(/*! open-access-api/src/utils */ "../../packages/open-access-api/src/utils.ts");
const logger_1 = __importStar(__webpack_require__(/*! ../common/logger */ "./src/common/logger.ts"));
const agent = new https_1.default.Agent({ keepAlive: true });
const MAX_RETRY = 5;
const MAX_PAGE_SIZE = 100;
async function wait(delay) {
    return new Promise(resolve => setTimeout(resolve, delay));
}
class OpenAccessAPI {
    constructor(options) {
        this.options = options;
        this.accessToken = null;
        this.segmentationSettings = null;
        this.enterpriseSettings = null;
    }
    async getToken() {
        if (!this.accessToken) {
            logger_1.default.debug('OnGuard access token is missing or expired. Authenticating to OnGuard...');
            try {
                const credentials = await this.options.getCredentials();
                const ret = await this.makeRequest({
                    url: '/authentication',
                    method: 'POST',
                    auth: false,
                    body: {
                        user_name: credentials.username,
                        password: credentials.password,
                        directory_id: credentials.directoryId,
                    },
                    trimPayloadFromLogs: true,
                });
                this.accessToken = ret.session_token;
                logger_1.default.debug('Authentication to OnGuard finished successfully.');
            }
            catch (e) {
                logger_1.default.error(e);
                throw new Error('Failed to authenticate to OnGuard. Please check configuration. Original error: ' +
                    e.message);
            }
        }
        return this.accessToken;
    }
    async getResponseJSON(res) {
        const text = await res.text();
        try {
            return JSON.parse(text);
        }
        catch (e) {
            return { raw: text };
        }
    }
    async makeRequest(fetchOptions, retry = MAX_RETRY) {
        if (!retry) {
            throw new Error(`Cannot fetch ${fetchOptions.method} ${fetchOptions.url}. Max retry exceeded.`);
        }
        const { auth = true, query, url, method, trimPayloadFromLogs, } = fetchOptions;
        const requestBody = fetchOptions.body && JSON.stringify(fetchOptions.body);
        const headers = {
            'application-id': this.options.applicationId,
            'content-type': 'application/json',
        };
        if (auth) {
            headers['Session-Token'] = await this.getToken();
        }
        const queryStr = query_string_1.default.stringify({
            version: '1.0',
            ...(query || {}),
        });
        const relativeUrl = `${url}?${queryStr}`;
        const fullUrl = `${this.options.baseUrl}/api/openaccess${relativeUrl}`;
        const res = await isomorphic_fetch_1.default(fullUrl, {
            method,
            headers,
            body: requestBody,
            // @ts-ignore
            agent,
        });
        const body = await this.getResponseJSON(res);
        logger_1.traceHttpRequest(logger_1.default, fetchOptions.method, fullUrl, trimPayloadFromLogs ? '<removed>' : requestBody, res.status, trimPayloadFromLogs ? '<removed>' : body);
        // expired token
        if (res.status === 401 && auth) {
            this.accessToken = null;
            return this.makeRequest(fetchOptions, retry - 1);
        }
        // retry on internal error or bad gateways
        if (res.status >= 500) {
            logger_1.default.error('Retry fetch', { url: fetchOptions.url, method: fetchOptions.method }, res.status);
            // wait 200ms, 400ms, 600ms... etc
            const delay = (MAX_RETRY - retry + 1) * 200;
            await wait(delay);
            return this.makeRequest(fetchOptions, retry - 1);
        }
        if (!res.ok) {
            const msg = R.getOr(body, ['error', 'message'], JSON.stringify(body));
            throw new Error(`Cannot fetch ${fetchOptions.method} ${fetchOptions.url}: ${msg}`);
        }
        return body;
    }
    createGetInstancesFetch(opts) {
        return {
            url: '/instances',
            method: 'GET',
            query: {
                type_name: opts.typeName,
                filter: opts.filter,
                page_number: opts.pageNumber,
                page_size: opts.pageSize,
                order_by: opts.orderBy,
                version: '1.2',
            },
        };
    }
    addInstance(typeName, values) {
        return this.makeRequest({
            url: '/instances',
            method: 'POST',
            body: {
                type_name: typeName,
                property_value_map: values,
            },
        }).then(result => result.property_value_map);
    }
    modifyInstance(typeName, values) {
        return this.makeRequest({
            url: '/instances',
            method: 'PUT',
            body: {
                type_name: typeName,
                property_value_map: values,
            },
        }).then(result => result.property_value_map);
    }
    async getInstances(opts) {
        const result = await this.makeRequest(this.createGetInstancesFetch({ pageNumber: 1, ...opts }));
        const mapped = utils_1.mapInstances(result);
        utils_1.fixIdStr(opts.typeName, mapped.items);
        return mapped;
    }
    async getSingleInstances(opts) {
        const result = await this.getInstances(opts);
        return utils_1.processSingleInstance(result, opts);
    }
    async getAllInstances(opts, extraOptions = {}) {
        const maxPages = extraOptions.maxPages || Infinity;
        const getPage = (pageNumber) => ({
            ...opts,
            pageNumber,
            pageSize: MAX_PAGE_SIZE,
        });
        const firstPage = await this.getInstances(getPage(1));
        if (!firstPage.count) {
            return [];
        }
        const pages = Math.min(firstPage.totalPages, maxPages);
        const startPage = 2;
        const results = await Promise.all(R.range(startPage, pages + 1).map(page => this.getInstances(getPage(page))));
        return [...firstPage.items, ...R.flatMap(results, x => x.items)];
    }
    async getCardholders(opts) {
        const query = utils_1.toSnakeCase(opts);
        if (query.access_level_list) {
            query.access_level_list = JSON.stringify(query.access_level_list);
        }
        const result = await this.makeRequest({
            url: '/cardholders',
            method: 'GET',
            query,
        });
        return utils_1.mapInstances(result);
    }
    async getAllCardholders(opts, extraOptions = {}) {
        const maxPages = extraOptions.maxPages || Infinity;
        const getPage = (pageNumber) => ({
            ...opts,
            pageNumber,
            pageSize: MAX_PAGE_SIZE,
        });
        const firstPage = await this.getCardholders(getPage(1));
        if (!firstPage.count) {
            return [];
        }
        const pages = Math.min(firstPage.totalPages, maxPages);
        const startPage = 2;
        const results = await Promise.all(R.range(startPage, pages + 1).map(page => this.getCardholders(getPage(page))));
        return [...firstPage.items, ...R.flatMap(results, x => x.items)];
    }
    async getSegmentationSettings() {
        if (!this.segmentationSettings) {
            this.segmentationSettings = await this.makeRequest({
                url: '/settings/segmentation',
                method: 'GET',
            });
        }
        return this.segmentationSettings;
    }
    async getEnterpriseSettings() {
        if (!this.enterpriseSettings) {
            this.enterpriseSettings = await this.makeRequest({
                url: '/settings/enterprise',
                method: 'GET',
            });
        }
        return this.enterpriseSettings;
    }
    sendIncomingEvents(incomingEvents) {
        return this.makeRequest({
            url: '/send_incoming_events',
            method: 'POST',
            body: {
                incoming_event_list: incomingEvents,
            },
        }).then(result => result.failure_list.item_list);
    }
    getVersion() {
        return this.makeRequest({
            url: '/version',
            method: 'GET',
            auth: false,
        });
    }
    getType(typeName) {
        return this.makeRequest({
            url: '/type',
            query: {
                type_name: typeName,
            },
            method: 'GET',
        });
    }
}
exports.OpenAccessAPI = OpenAccessAPI;


/***/ }),

/***/ "./src/sync/ErrorHandler.ts":
/*!**********************************!*\
  !*** ./src/sync/ErrorHandler.ts ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = __importDefault(__webpack_require__(/*! ../common/logger */ "./src/common/logger.ts"));
const onGuardApi_1 = __webpack_require__(/*! ../onGuardApi */ "./src/onGuardApi.ts");
const Const_1 = __webpack_require__(/*! ../Const */ "./src/Const.ts");
const PushError_1 = __webpack_require__(/*! ../entity/PushError */ "./src/entity/PushError.ts");
const db_1 = __webpack_require__(/*! ../db */ "./src/db.ts");
function getFullText(op) {
    switch (op) {
        case 'failed_to_delete_person':
            return 'Failed to delete person.';
        case 'failed_to_add_person':
            return 'Failed to add person.';
        case 'failed_to_update_person':
            return 'Failed to update person.';
        case 'failed_to_add_badge_to_person':
            return 'Failed to add badge to person.';
        case 'failed_to_add_photo':
            return 'Failed to add photo.';
        case 'failed_to_update_photo':
            return 'Failed to update photo.';
        case 'failed_to_remove_photo':
            return 'Failed to remove photo.';
        case 'sync_failed':
            return 'Synchronization failed. Check OnGuard Elements Connector log files for details.';
        case 'duplicate_badge_id':
            return 'Duplicate Badge ID';
        case 'cardholder_limit_exceeded':
            return 'Cardholder limit exceeded';
        case 'logical_source_deleted':
            return 'Logical source deleted';
        case 'cannot_connect_to_onguard':
            return 'Unable to connect to OnGuard';
        default:
            return op;
    }
}
exports.getFullText = getFullText;
class ErrorHandler {
    constructor(dbSite, info) {
        this.dbSite = dbSite;
        this.info = info;
    }
    reportError(error, operation, params) {
        const text = [
            'Cardholders not updated at remote site.',
            `There was an error during cardholder push for site ${this.dbSite.cloudName}.`,
        ];
        if (params.cardholderId) {
            text.push(`Cardholder ID: ${params.cardholderId}`);
        }
        if (params.badgeId) {
            text.push(`Badge ID: ${params.badgeId}`);
        }
        text.push(`Error details: ${getFullText(operation)}`);
        if (error) {
            text.push(`Original error: ${error.message}`);
        }
        const formatted = text.join('\r\n');
        logger_1.default.error(formatted, operation, params, error);
        if (this.info) {
            this.info.errorCount++;
            const pushError = new PushError_1.PushError();
            pushError.push = this.info.push;
            pushError.i18nKey = operation;
            pushError.i18nParams = JSON.stringify(params);
            pushError.cardholderId = params.cardholderId;
            pushError.badgeId = params.badgeId;
            db_1.connection.manager.insert(PushError_1.PushError, pushError).catch(e => {
                logger_1.default.error('Failed to save Push Error', e);
            });
        }
        if (operation === 'cannot_connect_to_onguard' ||
            operation === 'logical_source_deleted') {
            return;
        }
        onGuardApi_1.api
            .sendIncomingEvents([
            {
                ...Const_1.GENERIC_EVENT_PARAMS,
                source_id: this.dbSite.logicalSourceId,
                event_text: formatted,
            },
        ])
            .then(failed => {
            if (failed.length) {
                logger_1.default.error('Failed to send sendIncomingEvents', failed);
            }
        })
            .catch(e => {
            logger_1.default.error('Failed to send sendIncomingEvents', e);
        });
    }
}
exports.ErrorHandler = ErrorHandler;


/***/ }),

/***/ "./src/sync/IncrementalPhotoSync.ts":
/*!******************************************!*\
  !*** ./src/sync/IncrementalPhotoSync.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
class IncrementalPhotoSync {
    constructor(persons, keepPhotos) {
        this.keepPhotos = keepPhotos;
        this.personMapping = {};
        this.cardholderMap = {};
        this.remainingPersons = {};
        this.personMapping = R.indexBy(persons, x => x.externalId);
        this.remainingPersons = { ...this.personMapping };
    }
    process(images, cardholders) {
        const ret = {
            updatePhotos: [],
            addPhotos: [],
            removePhotos: [],
        };
        cardholders.forEach(item => {
            this.cardholderMap[item.ID] = item;
        });
        images.forEach(image => {
            delete this.remainingPersons[image.PersonID];
            const person = this.personMapping[image.PersonID];
            const cardholder = this.cardholderMap[image.PersonID];
            if (!person || !person.hasPhoto) {
                ret.addPhotos.push({ cardholder, image });
                return;
            }
            const hasNewPhoto = !person.externallyUpdatedPhoto ||
                helper_1.getTotalSeconds(image.LastChanged) > person.externallyUpdatedPhoto;
            ret.updatePhotos.push({
                cardholder,
                image,
                useCardholderTimestampOnly: !hasNewPhoto,
            });
        });
        return ret;
    }
    finalize() {
        const keepPhotosMap = R.indexByIdentity(this.keepPhotos);
        const ret = {
            updatePhotos: [],
            addPhotos: [],
            removePhotos: Object.values(this.remainingPersons)
                .filter(x => x.hasPhoto && !keepPhotosMap[x.externalId])
                .map(x => x.externalId),
        };
        return ret;
    }
}
exports.IncrementalPhotoSync = IncrementalPhotoSync;


/***/ }),

/***/ "./src/sync/SyncStatus.ts":
/*!********************************!*\
  !*** ./src/sync/SyncStatus.ts ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
class SyncInfo {
    constructor(site, push) {
        this.site = site;
        this.push = push;
        this.cancel$ = new Rx.Subject();
        this.completed$ = new Rx.Subject();
        this.errorCount = 0;
        this.isCanceled = false;
    }
    async cancel() {
        this.isCanceled = true;
        this.cancel$.next(true);
        await this.completed$.toPromise();
    }
}
exports.SyncInfo = SyncInfo;


/***/ }),

/***/ "./src/sync/getOnGuardData.ts":
/*!************************************!*\
  !*** ./src/sync/getOnGuardData.ts ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const wql_1 = __importDefault(__webpack_require__(/*! wql */ "../../packages/wql/src/index.ts"));
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const lnl_1 = __webpack_require__(/*! types/lnl */ "../../packages/types/lnl.ts");
const shared_connector_1 = __webpack_require__(/*! utils/shared-connector */ "../../packages/utils/shared-connector.ts");
const onGuardApi_1 = __webpack_require__(/*! ../onGuardApi */ "./src/onGuardApi.ts");
const helper_1 = __webpack_require__(/*! ./process/helper */ "./src/sync/process/helper.ts");
async function getAllChunked(options) {
    const result = [];
    const { cardholders, extraFilter, typeName } = options;
    const chunks = R.chunk(cardholders, 100);
    while (chunks.length) {
        const chunk = chunks.shift();
        const ret = await onGuardApi_1.api.getAllInstances({
            typeName,
            filter: wql_1.default({
                PERSONID: { $in: chunk.map(x => x.ID) },
                ...(extraFilter || {}),
            }),
        });
        result.push(...ret);
    }
    return result;
}
async function getCardholderSegmentationData() {
    const segmentationSettings = await onGuardApi_1.api.getSegmentationSettings();
    if (!segmentationSettings.segmentation_enabled ||
        !segmentationSettings.segment_cardholders) {
        return {
            allSegments: null,
            segmentGroupMembers: null,
        };
    }
    const [allSegments, segmentGroupMembers] = await Promise.all([
        onGuardApi_1.api.getAllInstances({
            typeName: lnl_1.TypeName.Lnl_Segment,
        }),
        onGuardApi_1.api.getAllInstances({
            typeName: lnl_1.TypeName.Lnl_SegmentGroupMember,
        }),
    ]);
    return { allSegments, segmentGroupMembers };
}
async function getOnGuardData(cardholderLimit, segmentId, filter) {
    const { conditions, operator } = filter;
    const [cardholderType, badgeType, { allSegments, segmentGroupMembers },] = await Promise.all([
        onGuardApi_1.api.getType(lnl_1.TypeName.Lnl_Cardholder),
        onGuardApi_1.api.getType(lnl_1.TypeName.Lnl_Badge),
        getCardholderSegmentationData(),
    ]);
    let cardholders = await onGuardApi_1.api.getAllCardholders({
        ...shared_connector_1.getBaseCardholderFilter(conditions),
        cardholderFilter: shared_connector_1.generateSerializedCardholderFilter({
            conditions,
            operator,
            columnConfigMap: shared_connector_1.getColumnConfigMap(cardholderType),
            segmentId,
            allSegments,
            segmentGroupMembers,
        }),
        badgeFilter: shared_connector_1.generateSerializedBadgeFilter({
            conditions,
            operator,
            badgePropsMap: R.indexBy(badgeType.properties, x => x.name),
        }),
    }, {
        maxPages: Math.ceil(cardholderLimit / 100) + 1,
    });
    const isLimitExceeded = cardholders.length > cardholderLimit;
    if (isLimitExceeded) {
        cardholders = cardholders.slice(0, cardholderLimit);
    }
    cardholders.forEach(cardholder => {
        if (!cardholder.FIRSTNAME) {
            cardholder.FIRSTNAME = '--';
        }
    });
    const badges = await getAllChunked({
        cardholders,
        typeName: lnl_1.TypeName.Lnl_Badge,
        extraFilter: {
            STATUS: lnl_1.BadgeActiveType,
        },
    });
    const badgeMap = R.groupBy(badges, x => x.PERSONID);
    return {
        cardholders: cardholders.map(cardholder => {
            const cardholderBadges = badgeMap[cardholder.ID] || [];
            return {
                ...cardholder,
                useExtendedTimes: cardholderBadges.some(badge => badge.EXTEND_STRIKE_HELD),
            };
        }),
        badges,
        isLimitExceeded,
    };
}
exports.getOnGuardData = getOnGuardData;
async function getOnGuardImagesData(cardholders) {
    const data = await getAllChunked({
        cardholders,
        typeName: lnl_1.TypeName.Lnl_MultimediaObject,
        extraFilter: {
            DataType: lnl_1.MultimediaDataType.NormalImage,
            ObjectType: lnl_1.MultimediaObjectType.Photo,
        },
    });
    await Promise.all(data.map(async (item) => {
        item.Data.data = await helper_1.resizeImage(item.Data.data);
    }));
    return data;
}
exports.getOnGuardImagesData = getOnGuardImagesData;


/***/ }),

/***/ "./src/sync/getScheduledDate.ts":
/*!**************************************!*\
  !*** ./src/sync/getScheduledDate.ts ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const DateFns = __importStar(__webpack_require__(/*! date-fns */ "date-fns"));
const config_1 = __importDefault(__webpack_require__(/*! ../config */ "./src/config.ts"));
const Const_1 = __webpack_require__(/*! ../Const */ "./src/Const.ts");
function getScheduledDate(lastPush, next) {
    if (!config_1.default.CARDHOLDER_PUSH_RUNS_DAILY) {
        return null;
    }
    if (lastPush && !lastPush.completed) {
        throw new Error(`Cannot schedule next date. Last push ${lastPush.id} is not completed.`);
    }
    const hourDiff = 24 / config_1.default.CARDHOLDER_PUSH_RUNS_DAILY;
    const firstPush = DateFns.startOfDay(Date.now());
    const totalMinutes = Math.round(config_1.default.CARDHOLDER_PUSH_FIRST_RUN_HOUR * 60);
    firstPush.setHours(Math.floor(totalMinutes / 60));
    firstPush.setMinutes(totalMinutes % 60);
    const pushTimes = [];
    for (let i = 0; i < config_1.default.CARDHOLDER_PUSH_RUNS_DAILY + 1; i++) {
        pushTimes.push(DateFns.addHours(firstPush, i * hourDiff));
    }
    if (lastPush) {
        // if there is already a push,
        // we can ignore initial CARDHOLDER_PUSH_FIRST_RUN_HOUR
        // if pushTimes contains a date from tomorrow, add a date with the same time for today
        const endOfDay = DateFns.endOfDay(Date.now()).getTime();
        const extraDates = [];
        pushTimes.forEach(date => {
            if (date.getTime() >= endOfDay) {
                const extra = new Date(date);
                extra.setDate(extra.getDate() - 1);
                extraDates.push(extra);
            }
        });
        pushTimes.push(...extraDates);
        pushTimes.sort((a, b) => a.getTime() - b.getTime());
    }
    return pushTimes.find(date => {
        const time = date.getTime();
        // future push
        if (!next && time > Date.now()) {
            return false;
        }
        // next push can't be less than current day
        if (next && time < Date.now()) {
            return false;
        }
        // api restarted and push is skipped
        if (time < Const_1.APP_START_DATE.getTime()) {
            return false;
        }
        // must be later than last push
        if (lastPush && time <= lastPush.completed.getTime()) {
            return false;
        }
        return true;
    });
}
exports.getScheduledDate = getScheduledDate;


/***/ }),

/***/ "./src/sync/getSyncDiff.ts":
/*!*********************************!*\
  !*** ./src/sync/getSyncDiff.ts ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(__webpack_require__(/*! r */ "../../packages/r/index.ts"));
const helper_1 = __webpack_require__(/*! ../common/helper */ "./src/common/helper.ts");
function isCardholderUpdated(cardholder, person) {
    return (helper_1.getTotalSeconds(cardholder.LASTCHANGED) !== person.externallyUpdated ||
        cardholder.useExtendedTimes !== person.useExtendedTimes);
}
function isImagePotentiallyUpdated(cardholder, person) {
    return (!person.externallyUpdatedPhoto ||
        helper_1.getTotalSeconds(cardholder.LASTCHANGED) > person.externallyUpdatedPhoto);
}
function getSyncDiff(onGuardData, personsInElements) {
    var _a, _b;
    const ret = {
        removeCardholders: [],
        updateCardholders: [],
        checkPhotoCardholders: [],
        addBadges: [],
        removeBadges: [],
        keepPhotos: [],
    };
    const { badges: onGuardBadges, cardholders: onGuardCardholders, } = onGuardData;
    const elementsPersonMap = R.indexBy(personsInElements, x => x.externalId);
    const onGuardCardholderMap = R.indexBy(onGuardCardholders, x => x.ID);
    const onGuardBadgeMap = R.indexBy(onGuardBadges, x => x.ID);
    // check cardholders
    onGuardCardholders.forEach(cardholder => {
        const person = elementsPersonMap[cardholder.ID];
        if (!person || isCardholderUpdated(cardholder, person)) {
            ret.updateCardholders.push(cardholder);
            ret.checkPhotoCardholders.push(cardholder);
        }
        else if (person && isImagePotentiallyUpdated(cardholder, person)) {
            ret.checkPhotoCardholders.push(cardholder);
        }
        else {
            ret.keepPhotos.push(cardholder.ID.toString());
        }
    });
    ret.removeCardholders = personsInElements
        .map(x => x.externalId)
        .filter(x => !onGuardCardholderMap[x]);
    const removedCardholdersMap = R.indexByIdentity(ret.removeCardholders);
    ret.checkPhotoCardholders = ret.checkPhotoCardholders.filter(x => !removedCardholdersMap[x.ID]);
    ret.keepPhotos.push(...ret.removeCardholders);
    // check badges to add
    for (const badge of onGuardBadges) {
        const person = elementsPersonMap[badge.PERSONID];
        if (!person || !person.externalBadgesIds.includes(badge.ID)) {
            ret.addBadges.push({
                badgeId: badge.ID,
                cardholderId: badge.PERSONID,
            });
        }
    }
    // check badges to remove
    // Note: If a badge is moved from one cardholder to another it will both in addBadges and removeBadges
    for (const person of personsInElements) {
        // If cardholder is removed his badges are removed automatically
        // There's no need to remove them manually
        if (removedCardholdersMap[person.externalId]) {
            continue;
        }
        for (const badgeId of person.externalBadgesIds) {
            const newPersonID = (_b = (_a = onGuardBadgeMap[badgeId]) === null || _a === void 0 ? void 0 : _a.PERSONID) === null || _b === void 0 ? void 0 : _b.toString();
            if (newPersonID !== person.externalId) {
                ret.removeBadges.push(badgeId);
            }
        }
    }
    return ret;
}
exports.getSyncDiff = getSyncDiff;


/***/ }),

/***/ "./src/sync/process/addBadges.ts":
/*!***************************************!*\
  !*** ./src/sync/process/addBadges.ts ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = __webpack_require__(/*! ./helper */ "./src/sync/process/helper.ts");
async function addBadges(badges, options) {
    const { cancel$, elementsAPI, errorHandler } = options;
    await helper_1.execAll(cancel$, badges, async (addBadge) => {
        try {
            await elementsAPI.addBadge(addBadge.cardholderId.toString(), addBadge.badgeId);
        }
        catch (e) {
            errorHandler.reportError(e, e.message.includes('BadgeId already in use')
                ? 'duplicate_badge_id'
                : 'failed_to_add_badge_to_person', {
                cardholderId: addBadge.cardholderId,
                badgeId: addBadge.badgeId,
            });
        }
    });
}
exports.addBadges = addBadges;


/***/ }),

/***/ "./src/sync/process/addPhotos.ts":
/*!***************************************!*\
  !*** ./src/sync/process/addPhotos.ts ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = __webpack_require__(/*! ./helper */ "./src/sync/process/helper.ts");
const helper_2 = __webpack_require__(/*! ../../common/helper */ "./src/common/helper.ts");
async function addPhotos(photos, options) {
    const { cancel$, elementsAPI, errorHandler } = options;
    await helper_1.execAll(cancel$, photos, async (photo) => {
        try {
            await elementsAPI.addPhoto(photo.cardholder.ID.toString(), helper_2.getTotalSeconds(photo.image.LastChanged), photo.image.Data.data);
        }
        catch (e) {
            errorHandler.reportError(e, 'failed_to_add_photo', {
                cardholderId: photo.cardholder.ID,
            });
        }
    });
}
exports.addPhotos = addPhotos;


/***/ }),

/***/ "./src/sync/process/helper.ts":
/*!************************************!*\
  !*** ./src/sync/process/helper.ts ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Rx = __importStar(__webpack_require__(/*! rx */ "../../packages/rx/index.ts"));
const jimp_1 = __importDefault(__webpack_require__(/*! jimp */ "jimp"));
const errors_1 = __webpack_require__(/*! ../../common/errors */ "./src/common/errors.ts");
const logger_1 = __importDefault(__webpack_require__(/*! ../../common/logger */ "./src/common/logger.ts"));
async function isNotFoundError(error) {
    if (error instanceof errors_1.ElementsError) {
        if (error.errorCode === 'not_found') {
            return true;
        }
        return error.errors.some(x => x.errorCode === 'not_found');
    }
    return false;
}
exports.isNotFoundError = isNotFoundError;
function ignoreNotFoundError(error) {
    if (!isNotFoundError(error)) {
        throw error;
    }
}
exports.ignoreNotFoundError = ignoreNotFoundError;
async function execAll(cancel$, items, fn) {
    return Rx.from(items)
        .pipe(Rx.mergeMap(item => Rx.fromPromise(fn(item)), 20), Rx.takeUntil(cancel$))
        .toPromise();
}
exports.execAll = execAll;
async function resizeImage(image, maxSize = 1.8 * 1024 * 1024, maxRes = 1000) {
    const buffer = typeof image === 'string' ? Buffer.from(image, 'base64') : image;
    let img = await jimp_1.default.read(buffer);
    if (img.getWidth() > maxRes || img.getHeight() > maxRes) {
        logger_1.default.debug(`Image size: ${img.getWidth()}x${img.getHeight()}. The image will be scaled down.`);
        img = img.scaleToFit(maxRes, maxRes);
    }
    const result = (await img.getBufferAsync(jimp_1.default.MIME_PNG)).toString('base64');
    logger_1.default.debug(`Image size: ${img.getWidth()}x${img.getHeight()}. Result length: ${result.length}`);
    if (result.length <= maxSize) {
        return result;
    }
    logger_1.default.debug(`Image file size: ${result.length}. The image will be scaled down.`);
    return resizeImage(buffer, maxSize, maxRes - 100);
}
exports.resizeImage = resizeImage;


/***/ }),

/***/ "./src/sync/process/removeBadges.ts":
/*!******************************************!*\
  !*** ./src/sync/process/removeBadges.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = __webpack_require__(/*! ./helper */ "./src/sync/process/helper.ts");
async function removeBadges(badges, options) {
    const { cancel$, elementsAPI, errorHandler } = options;
    await helper_1.execAll(cancel$, badges, async (id) => {
        try {
            await elementsAPI.removeBadge(id).catch(helper_1.ignoreNotFoundError);
        }
        catch (e) {
            errorHandler.reportError(e, 'failed_to_remove_badge', {
                badgeId: id,
            });
        }
    });
}
exports.removeBadges = removeBadges;


/***/ }),

/***/ "./src/sync/process/removeCardholders.ts":
/*!***********************************************!*\
  !*** ./src/sync/process/removeCardholders.ts ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = __webpack_require__(/*! ./helper */ "./src/sync/process/helper.ts");
async function removeCardholders(cardholders, options) {
    const { cancel$, elementsAPI, errorHandler } = options;
    await helper_1.execAll(cancel$, cardholders, async (id) => {
        try {
            await elementsAPI.deletePerson(id).catch(helper_1.ignoreNotFoundError);
        }
        catch (e) {
            errorHandler.reportError(e, 'failed_to_delete_person', {
                cardholderId: Number(id),
            });
        }
    });
}
exports.removeCardholders = removeCardholders;


/***/ }),

/***/ "./src/sync/process/removePhotos.ts":
/*!******************************************!*\
  !*** ./src/sync/process/removePhotos.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = __webpack_require__(/*! ./helper */ "./src/sync/process/helper.ts");
async function removePhotos(photos, options) {
    const { cancel$, elementsAPI, errorHandler } = options;
    await helper_1.execAll(cancel$, photos, async (id) => {
        try {
            await elementsAPI.removePhoto(id).catch(helper_1.ignoreNotFoundError);
        }
        catch (e) {
            errorHandler.reportError(e, 'failed_to_remove_photo', {
                cardholderId: Number(id),
            });
        }
    });
}
exports.removePhotos = removePhotos;


/***/ }),

/***/ "./src/sync/process/updateCardholders.ts":
/*!***********************************************!*\
  !*** ./src/sync/process/updateCardholders.ts ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = __webpack_require__(/*! ./helper */ "./src/sync/process/helper.ts");
const helper_2 = __webpack_require__(/*! ../../common/helper */ "./src/common/helper.ts");
async function updateCardholders(cardholders, options) {
    const { cancel$, elementsAPI, errorHandler } = options;
    await helper_1.execAll(cancel$, cardholders, async (cardholder) => {
        try {
            await elementsAPI.upsertPerson(cardholder.ID.toString(), {
                firstName: cardholder.FIRSTNAME,
                lastName: cardholder.LASTNAME,
                useExtendedTimes: cardholder.useExtendedTimes,
                externallyUpdated: helper_2.getTotalSeconds(cardholder.LASTCHANGED),
            });
        }
        catch (e) {
            errorHandler.reportError(e, 'failed_to_update_person', {
                cardholderId: cardholder.ID,
            });
        }
    });
}
exports.updateCardholders = updateCardholders;


/***/ }),

/***/ "./src/sync/process/updatePhotos.ts":
/*!******************************************!*\
  !*** ./src/sync/process/updatePhotos.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = __webpack_require__(/*! ./helper */ "./src/sync/process/helper.ts");
const helper_2 = __webpack_require__(/*! ../../common/helper */ "./src/common/helper.ts");
async function updatePhotos(photos, options) {
    const { cancel$, elementsAPI, errorHandler } = options;
    await helper_1.execAll(cancel$, photos, async ({ image, useCardholderTimestampOnly, cardholder }) => {
        try {
            if (useCardholderTimestampOnly) {
                await elementsAPI.updatePhoto(cardholder.ID.toString(), helper_2.getTotalSeconds(cardholder.LASTCHANGED), undefined);
            }
            else {
                await elementsAPI.updatePhoto(cardholder.ID.toString(), helper_2.getTotalSeconds(image.LastChanged), image.Data.data);
            }
        }
        catch (e) {
            errorHandler.reportError(e, 'failed_to_update_photo', {
                cardholderId: cardholder.ID,
            });
        }
    });
}
exports.updatePhotos = updatePhotos;


/***/ }),

/***/ "./src/validation.ts":
/*!***************************!*\
  !*** ./src/validation.ts ***!
  \***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const veni_1 = __webpack_require__(/*! veni */ "veni");
const helper_1 = __webpack_require__(/*! ./common/helper */ "./src/common/helper.ts");
veni_1.StringSchema.prototype.apiKey = function () {
    this.validators.push({
        type: 'string.apiKey',
        validate: (value, path) => {
            try {
                const { url, payload } = helper_1.decodeApiKey(value);
                if (typeof url !== 'string' ||
                    typeof payload !== 'string' ||
                    !url.startsWith('https://')) {
                    return {
                        stop: true,
                        error: {
                            type: 'array.apiKey',
                            message: `Invalid api key.`,
                            path,
                            value,
                        },
                    };
                }
            }
            catch (e) {
                return {
                    stop: true,
                    error: {
                        type: 'array.apiKey',
                        message: `Api key cannot be decoded.`,
                        path,
                        value,
                    },
                };
            }
            return null;
        },
    });
    return this;
};
veni_1.NumberSchema.prototype.values = function (values) {
    this.validators.push({
        type: 'number.values',
        validate: (value, path) => {
            if (!values.includes(value)) {
                return {
                    stop: true,
                    error: {
                        type: 'number.values',
                        message: `Invalid value. Allowed: ` + values.join(', '),
                        path,
                        value,
                    },
                };
            }
            return null;
        },
    });
    return this;
};
veni_1.NumberSchema.prototype.less = function (less) {
    this.validators.push({
        type: 'number.less',
        validate: (value, path) => {
            if (value >= less) {
                return {
                    stop: true,
                    error: {
                        type: 'number.less',
                        message: `Value must be less than ${less}`,
                        path,
                        value,
                    },
                };
            }
            return null;
        },
    });
    return this;
};


/***/ }),

/***/ "./src/worker-api.ts":
/*!***************************!*\
  !*** ./src/worker-api.ts ***!
  \***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(__dirname) {
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(__webpack_require__(/*! path */ "path"));
const logger_1 = __importDefault(__webpack_require__(/*! ./common/logger */ "./src/common/logger.ts"));
const child_process_1 = __webpack_require__(/*! child_process */ "child_process");
const uuid_1 = __importDefault(__webpack_require__(/*! uuid */ "uuid"));
let workerProcess = null;
const callbacks = {};
function sendWorkerMessage(message) {
    if (!workerProcess) {
        throw new Error('Worker is not running');
    }
    message.messageId = uuid_1.default();
    return new Promise((resolve, rejects) => {
        const timeout = setTimeout(() => {
            rejects(new Error('Worker timeout'));
        }, 10 * 1000);
        callbacks[message.messageId] = { resolve, rejects, timeout };
        workerProcess.send(message);
    });
}
exports.sendWorkerMessage = sendWorkerMessage;
function startWorker() {
    const workerPath = process.pkg
        ? path_1.default.join(path_1.default.dirname(process.pkg.defaultEntrypoint), 'worker.js')
        : path_1.default.join(__dirname, 'worker.ts');
    try {
        workerProcess = child_process_1.fork(workerPath)
            .on('error', e => {
            logger_1.default.error('worker error', e);
            process.exit(1);
        })
            .on('exit', code => {
            logger_1.default.error('worker exited', code);
            process.exit(1);
        });
    }
    catch (e) {
        logger_1.default.error('Failed to start worker', e);
        process.exit(1);
    }
    workerProcess.on('message', (msg) => {
        if (!(msg === null || msg === void 0 ? void 0 : msg.messageId)) {
            logger_1.default.error('Invalid message', msg);
            return;
        }
        const data = callbacks[msg.messageId];
        if (!data) {
            return;
        }
        delete callbacks[msg.messageId];
        const { timeout, resolve, rejects } = data;
        clearTimeout(timeout);
        if (msg.error) {
            rejects(new Error(msg.error));
        }
        else {
            resolve(msg.value);
        }
    });
}
exports.startWorker = startWorker;

/* WEBPACK VAR INJECTION */}.call(this, "/"))

/***/ }),

/***/ "./src/worker.ts":
/*!***********************!*\
  !*** ./src/worker.ts ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ./bootstrap */ "./src/bootstrap.ts");
const checkRemovedLogicalSourcesJob_1 = __webpack_require__(/*! ./jobs/checkRemovedLogicalSourcesJob */ "./src/jobs/checkRemovedLogicalSourcesJob.ts");
const pushJob_1 = __webpack_require__(/*! ./jobs/pushJob */ "./src/jobs/pushJob.ts");
const eventsJob_1 = __webpack_require__(/*! ./jobs/eventsJob */ "./src/jobs/eventsJob.ts");
const syncJob_1 = __webpack_require__(/*! ./jobs/syncJob */ "./src/jobs/syncJob.ts");
const logger_1 = __importDefault(__webpack_require__(/*! ./common/logger */ "./src/common/logger.ts"));
const db_1 = __webpack_require__(/*! ./db */ "./src/db.ts");
const cancelSync_1 = __webpack_require__(/*! ./contracts/site/cancelSync */ "./src/contracts/site/cancelSync.ts");
async function start() {
    await db_1.initDb();
    checkRemovedLogicalSourcesJob_1.checkRemovedLogicalSourcesJob();
    pushJob_1.pushJob();
    eventsJob_1.eventsJob();
    syncJob_1.syncJob();
}
start().catch(e => {
    logger_1.default.error(e);
    process.exit(1);
});
process.on('message', (msg) => {
    if (!(msg === null || msg === void 0 ? void 0 : msg.type)) {
        logger_1.default.error('Invalid worker message', msg);
        return;
    }
    const invoke = () => {
        switch (msg.type) {
            case 'cancel-sync': {
                return cancelSync_1.cancelSync(msg.user, msg.siteId);
            }
        }
    };
    invoke()
        .then(value => {
        process.send({
            messageId: msg.messageId,
            value,
        });
    })
        .catch(e => {
        var _a;
        process.send({
            messageId: msg.messageId,
            error: (_a = e.message) !== null && _a !== void 0 ? _a : 'Worker error',
        });
    });
});


/***/ }),

/***/ "bunyan":
/*!*************************!*\
  !*** external "bunyan" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("bunyan");

/***/ }),

/***/ "bunyan-format":
/*!********************************!*\
  !*** external "bunyan-format" ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("bunyan-format");

/***/ }),

/***/ "child_process":
/*!********************************!*\
  !*** external "child_process" ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("child_process");

/***/ }),

/***/ "crypto":
/*!*************************!*\
  !*** external "crypto" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("crypto");

/***/ }),

/***/ "date-fns":
/*!***************************!*\
  !*** external "date-fns" ***!
  \***************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("date-fns");

/***/ }),

/***/ "debounce":
/*!***************************!*\
  !*** external "debounce" ***!
  \***************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("debounce");

/***/ }),

/***/ "defensive":
/*!****************************!*\
  !*** external "defensive" ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("defensive");

/***/ }),

/***/ "eol":
/*!**********************!*\
  !*** external "eol" ***!
  \**********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("eol");

/***/ }),

/***/ "fs":
/*!*********************!*\
  !*** external "fs" ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("fs");

/***/ }),

/***/ "https":
/*!************************!*\
  !*** external "https" ***!
  \************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("https");

/***/ }),

/***/ "immer":
/*!************************!*\
  !*** external "immer" ***!
  \************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("immer");

/***/ }),

/***/ "isomorphic-fetch":
/*!***********************************!*\
  !*** external "isomorphic-fetch" ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("isomorphic-fetch");

/***/ }),

/***/ "jimp":
/*!***********************!*\
  !*** external "jimp" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("jimp");

/***/ }),

/***/ "lodash":
/*!*************************!*\
  !*** external "lodash" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("lodash");

/***/ }),

/***/ "ms":
/*!*********************!*\
  !*** external "ms" ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("ms");

/***/ }),

/***/ "os":
/*!*********************!*\
  !*** external "os" ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("os");

/***/ }),

/***/ "path":
/*!***********************!*\
  !*** external "path" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("path");

/***/ }),

/***/ "proxy-agent":
/*!******************************!*\
  !*** external "proxy-agent" ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("proxy-agent");

/***/ }),

/***/ "query-string":
/*!*******************************!*\
  !*** external "query-string" ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("query-string");

/***/ }),

/***/ "react":
/*!************************!*\
  !*** external "react" ***!
  \************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("react");

/***/ }),

/***/ "react-redux":
/*!******************************!*\
  !*** external "react-redux" ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("react-redux");

/***/ }),

/***/ "redux":
/*!************************!*\
  !*** external "redux" ***!
  \************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("redux");

/***/ }),

/***/ "redux-react-hook":
/*!***********************************!*\
  !*** external "redux-react-hook" ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("redux-react-hook");

/***/ }),

/***/ "reflect-metadata":
/*!***********************************!*\
  !*** external "reflect-metadata" ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("reflect-metadata");

/***/ }),

/***/ "regedit":
/*!**************************!*\
  !*** external "regedit" ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("regedit");

/***/ }),

/***/ "rxjs":
/*!***********************!*\
  !*** external "rxjs" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("rxjs");

/***/ }),

/***/ "rxjs/ajax":
/*!****************************!*\
  !*** external "rxjs/ajax" ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("rxjs/ajax");

/***/ }),

/***/ "rxjs/internal-compatibility":
/*!**********************************************!*\
  !*** external "rxjs/internal-compatibility" ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("rxjs/internal-compatibility");

/***/ }),

/***/ "rxjs/operators":
/*!*********************************!*\
  !*** external "rxjs/operators" ***!
  \*********************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("rxjs/operators");

/***/ }),

/***/ "typeorm":
/*!**************************!*\
  !*** external "typeorm" ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("typeorm");

/***/ }),

/***/ "url":
/*!**********************!*\
  !*** external "url" ***!
  \**********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("url");

/***/ }),

/***/ "util":
/*!***********************!*\
  !*** external "util" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("util");

/***/ }),

/***/ "uuid":
/*!***********************!*\
  !*** external "uuid" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("uuid");

/***/ }),

/***/ "veni":
/*!***********************!*\
  !*** external "veni" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("veni");

/***/ })

/******/ })));